source: git/src/moviemaker.cc @ 92cfa6ee

stereo-2025
Last change on this file since 92cfa6ee was a3f83057, checked in by Olly Betts <olly@…>, 7 months ago

Use C++11 member initialisation where sensible

  • Property mode set to 100644
File size: 10.9 KB
RevLine 
[6a4cdcb6]1//
2//  moviemaker.cc
3//
4//  Class for writing movies from Aven.
5//
[91a758c]6//  Copyright (C) 2004-2024 Olly Betts
[6a4cdcb6]7//
8//  This program is free software; you can redistribute it and/or modify
9//  it under the terms of the GNU General Public License as published by
10//  the Free Software Foundation; either version 2 of the License, or
11//  (at your option) any later version.
12//
13//  This program is distributed in the hope that it will be useful,
14//  but WITHOUT ANY WARRANTY; without even the implied warranty of
15//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16//  GNU General Public License for more details.
17//
18//  You should have received a copy of the GNU General Public License
19//  along with this program; if not, write to the Free Software
[ecbc6c18]20//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
[6a4cdcb6]21//
22
[cc9e7a06]23/* Based on output-example.c:
24 *
25 * Libavformat API example: Output a media file in any supported
26 * libavformat format. The default codecs are used.
27 *
28 * Copyright (c) 2003 Fabrice Bellard
29 *
30 * Permission is hereby granted, free of charge, to any person obtaining a copy
31 * of this software and associated documentation files (the "Software"), to deal
32 * in the Software without restriction, including without limitation the rights
33 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
34 * copies of the Software, and to permit persons to whom the Software is
35 * furnished to do so, subject to the following conditions:
36 *
37 * The above copyright notice and this permission notice shall be included in
38 * all copies or substantial portions of the Software.
39 *
40 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
43 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
46 * THE SOFTWARE.
47 */
48
[6a4cdcb6]49#include <config.h>
50
[cc9e7a06]51#define __STDC_CONSTANT_MACROS
52
[1805274]53#include <assert.h>
[6a4cdcb6]54#include <stdlib.h>
55#include <string.h>
56
57#include "moviemaker.h"
58
[40d1db36]59#ifdef WITH_FFMPEG
[cc9e7a06]60extern "C" {
[44c4b70]61# include <libavcodec/avcodec.h>
[b282f44]62# include <libavutil/imgutils.h>
[008f2f3]63# include <libavutil/mathematics.h>
[64d06c0]64# include <libavformat/avformat.h>
[86d8ee5]65# include <libswscale/swscale.h>
[cc9e7a06]66}
[0aaa578]67#endif
[6a4cdcb6]68
[40d1db36]69// Handle the "no FFmpeg" case in this file.
70#if !defined WITH_FFMPEG || LIBAVCODEC_VERSION_MAJOR >= 57
[0aaa578]71
[40d1db36]72#ifdef WITH_FFMPEG
[091069f]73enum {
74    MOVIE_NO_SUITABLE_FORMAT = 1,
75    MOVIE_AUDIO_ONLY,
[c648bd1]76    MOVIE_FILENAME_TOO_LONG
[091069f]77};
[bc6faa9]78#endif
[6a4cdcb6]79
[1805274]80MovieMaker::MovieMaker()
[6a4cdcb6]81{
[40d1db36]82#ifdef WITH_FFMPEG
[6a4cdcb6]83    static bool initialised_ffmpeg = false;
[1805274]84    if (initialised_ffmpeg) return;
[6a4cdcb6]85
[0482978]86#if LIBAVCODEC_VERSION_MAJOR < 58
[64d06c0]87    avcodec_register_all();
[1805274]88    av_register_all();
[0482978]89#endif
[6a4cdcb6]90
[1805274]91    initialised_ffmpeg = true;
92#endif
93}
94
[40d1db36]95#ifdef WITH_FFMPEG
[f4e4b56]96static int
[91a758c]97write_packet(void *opaque,
98#if LIBAVFORMAT_VERSION_MAJOR < 61
99             uint8_t *buf,
100#else
101             const uint8_t *buf,
102#endif
103             int buf_size)
104{
[f4e4b56]105    FILE * fh = (FILE*)opaque;
106    size_t res = fwrite(buf, 1, buf_size, fh);
107    return res > 0 ? res : -1;
108}
[420cda9]109
110static int64_t
111seek_stream(void *opaque, int64_t offset, int whence) {
112    FILE * fh = (FILE*)opaque;
113    return fseek(fh, offset, whence);
114}
[0db0f91]115#endif
[f4e4b56]116
117#define MAX_EXTENSION_LEN 8
118
119bool MovieMaker::Open(FILE* fh, const char * ext, int width, int height)
[1805274]120{
[40d1db36]121#ifdef WITH_FFMPEG
[f4e4b56]122    fh_to_close = fh;
123
[0aaa578]124    /* Allocate the output media context. */
[f4e4b56]125    char dummy_filename[MAX_EXTENSION_LEN + 3] = "x.";
[0aaa578]126    oc = NULL;
[f4e4b56]127    if (strlen(ext) <= MAX_EXTENSION_LEN) {
[0aaa578]128        // Use "x." + extension for format detection to avoid having to deal
[f4e4b56]129        // with wide character filenames.
[0aaa578]130        strcpy(dummy_filename + 2, ext);
131        avformat_alloc_output_context2(&oc, NULL, NULL, dummy_filename);
[1805274]132    }
[0aaa578]133    if (!oc) {
134        averrno = MOVIE_NO_SUITABLE_FORMAT;
[1805274]135        return false;
[6a4cdcb6]136    }
137
[44c4b70]138    auto fmt = oc->oformat;
[0aaa578]139    if (fmt->video_codec == AV_CODEC_ID_NONE) {
140        averrno = MOVIE_AUDIO_ONLY;
[1805274]141        return false;
[6a4cdcb6]142    }
143
[64d06c0]144    /* find the video encoder */
[44c4b70]145    auto codec = avcodec_find_encoder(fmt->video_codec);
[64d06c0]146    if (!codec) {
147        // FIXME : Erm - internal ffmpeg library problem?
[63621a7]148        averrno = AVERROR(ENOMEM);
[1805274]149        return false;
[6a4cdcb6]150    }
151
[64d06c0]152    // Add the video stream.
[0aaa578]153    video_st = avformat_new_stream(oc, NULL);
[64d06c0]154    if (!video_st) {
155        averrno = AVERROR(ENOMEM);
156        return false;
157    }
[6a4cdcb6]158
[0aaa578]159    context = avcodec_alloc_context3(codec);
160    context->codec_id = fmt->video_codec;
161    context->width = width;
162    context->height = height;
[5270758]163    video_st->time_base.den = 25; // Frames per second.
164    video_st->time_base.num = 1;
[0aaa578]165    context->time_base = video_st->time_base;
166    context->bit_rate = width * height * (4 * 0.07) * context->time_base.den / context->time_base.num;
167    context->bit_rate_tolerance = context->bit_rate;
168    context->global_quality = 4;
169    context->rc_buffer_size = 2 * 1024 * 1024;
170    context->rc_max_rate = context->bit_rate * 8;
171    context->gop_size = 50; /* Twice the framerate */
172    context->pix_fmt = AV_PIX_FMT_YUV420P;
173    if (context->has_b_frames) {
174        // B frames are backwards predicted - they can improve compression,
175        // but may slow encoding and decoding.
176        context->max_b_frames = 4;
177    }
[6a4cdcb6]178
[64d06c0]179    /* Some formats want stream headers to be separate. */
[cc9e7a06]180    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
[5e46ae2]181        context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
[cc9e7a06]182
[7831cef]183    int retval;
[0aaa578]184    retval = avcodec_open2(context, codec, NULL);
[091069f]185    if (retval < 0) {
186        averrno = retval;
[1805274]187        return false;
[6a4cdcb6]188    }
[1805274]189
[64d06c0]190    /* Allocate the encoded raw picture. */
[8364c65f]191    frame = av_frame_alloc();
[cc9e7a06]192    if (!frame) {
[63621a7]193        averrno = AVERROR(ENOMEM);
[1805274]194        return false;
[6a4cdcb6]195    }
[0aaa578]196
197    frame->format = context->pix_fmt;
198    frame->width = width;
199    frame->height = height;
200    frame->pts = 0;
201
202    retval = av_frame_get_buffer(frame, 32);
[64d06c0]203    if (retval < 0) {
204        averrno = retval;
[1805274]205        return false;
[6a4cdcb6]206    }
[cc9e7a06]207
[0aaa578]208    if (frame->format != AV_PIX_FMT_YUV420P) {
[cc9e7a06]209        // FIXME need to allocate another frame for this case if we stop
[8364c65f]210        // hardcoding AV_PIX_FMT_YUV420P.
[cc9e7a06]211        abort();
212    }
[6a4cdcb6]213
[0aaa578]214    /* copy the stream parameters to the muxer */
215    retval = avcodec_parameters_from_context(video_st->codecpar, context);
216    if (retval < 0) {
217        averrno = retval;
218        return false;
219    }
[5270758]220
[d13aea6]221    pixels = (unsigned char *)av_malloc(width * height * 6);
[6a4cdcb6]222    if (!pixels) {
[63621a7]223        averrno = AVERROR(ENOMEM);
[1805274]224        return false;
[6a4cdcb6]225    }
[1805274]226
[64d06c0]227    // Show the format we've ended up with (for debug purposes).
[0aaa578]228    // av_dump_format(oc, 0, dummy_filename, 1);
[64d06c0]229
230    av_free(sws_ctx);
[ad04c87]231    sws_ctx = sws_getContext(width, height, AV_PIX_FMT_RGB24,
[0aaa578]232                             width, height, context->pix_fmt, SWS_BICUBIC,
[64d06c0]233                             NULL, NULL, NULL);
234    if (sws_ctx == NULL) {
235        fprintf(stderr, "Cannot initialize the conversion context!\n");
236        averrno = AVERROR(ENOMEM);
[1805274]237        return false;
238    }
239
[64d06c0]240    if (!(fmt->flags & AVFMT_NOFILE)) {
[f4e4b56]241        const int buf_size = 8192;
242        void * buf = av_malloc(buf_size);
243        oc->pb = avio_alloc_context(static_cast<uint8_t*>(buf), buf_size, 1,
[420cda9]244                                    fh, NULL, write_packet, seek_stream);
[f4e4b56]245        if (!oc->pb) {
246            averrno = AVERROR(ENOMEM);
[64d06c0]247            return false;
248        }
249    }
250
[1805274]251    // Write the stream header, if any.
[7831cef]252    retval = avformat_write_header(oc, NULL);
[091069f]253    if (retval < 0) {
254        averrno = retval;
[1805274]255        return false;
256    }
[9e516d0d]257
[091069f]258    averrno = 0;
[1805274]259    return true;
[6a4cdcb6]260#else
[f4e4b56]261    (void)fh;
262    (void)ext;
[6e22f11]263    (void)width;
264    (void)height;
[6a4cdcb6]265    return false;
266#endif
267}
268
269unsigned char * MovieMaker::GetBuffer() const {
[40d1db36]270#ifdef WITH_FFMPEG
[cd04101]271    return pixels + GetWidth() * GetHeight() * 3;
[eac4514]272#else
273    return NULL;
274#endif
[6a4cdcb6]275}
276
277int MovieMaker::GetWidth() const {
[40d1db36]278#ifdef WITH_FFMPEG
[ccb83b7]279    assert(video_st);
[0aaa578]280    return video_st->codecpar->width;
[1805274]281#else
282    return 0;
283#endif
[6a4cdcb6]284}
285
286int MovieMaker::GetHeight() const {
[40d1db36]287#ifdef WITH_FFMPEG
[ccb83b7]288    assert(video_st);
[0aaa578]289    return video_st->codecpar->height;
[1805274]290#else
291    return 0;
292#endif
[6a4cdcb6]293}
294
[40d1db36]295#ifdef WITH_FFMPEG
[0aaa578]296// Call with frame=NULL when done.
297int
298MovieMaker::encode_frame(AVFrame* frame_or_null)
299{
300    int ret = avcodec_send_frame(context, frame_or_null);
301    if (ret < 0) return ret;
302
303    AVPacket *pkt = av_packet_alloc();
304    pkt->size = 0;
305    while ((ret = avcodec_receive_packet(context, pkt)) == 0) {
306        // Rescale output packet timestamp values from codec to stream timebase.
307        av_packet_rescale_ts(pkt, context->time_base, video_st->time_base);
308        pkt->stream_index = video_st->index;
309
310        // Write the compressed frame to the media file.
311        ret = av_interleaved_write_frame(oc, pkt);
312        if (ret < 0) {
313            av_packet_free(&pkt);
314            release();
315            return ret;
316        }
317    }
318    av_packet_free(&pkt);
319    return 0;
320}
321#endif
322
[98fd937]323bool MovieMaker::AddFrame()
[6a4cdcb6]324{
[40d1db36]325#ifdef WITH_FFMPEG
[0aaa578]326    int ret = av_frame_make_writable(frame);
327    if (ret < 0) {
328        averrno = ret;
329        return false;
330    }
[cc9e7a06]331
[0aaa578]332    enum AVPixelFormat pix_fmt = context->pix_fmt;
333
334    if (pix_fmt != AV_PIX_FMT_YUV420P) {
[cc9e7a06]335        // FIXME convert...
336        abort();
337    }
[1805274]338
[0aaa578]339    int len = 3 * GetWidth();
[fed3713]340    {
341        // Flip image vertically
[0aaa578]342        int h = GetHeight();
[fed3713]343        unsigned char * src = pixels + h * len;
344        unsigned char * dest = src - len;
345        while (h--) {
346            memcpy(dest, src, len);
347            src += len;
348            dest -= len;
349        }
[6a4cdcb6]350    }
[0aaa578]351    sws_scale(sws_ctx, &pixels, &len, 0, GetHeight(),
352              frame->data, frame->linesize);
[6a4cdcb6]353
[0aaa578]354    ++frame->pts;
[64d06c0]355
[0aaa578]356    // Encode this frame.
357    ret = encode_frame(frame);
[64d06c0]358    if (ret < 0) {
[98fd937]359        averrno = ret;
360        return false;
[64d06c0]361    }
362#endif
[98fd937]363    return true;
[6a4cdcb6]364}
365
[98fd937]366bool
367MovieMaker::Close()
[6a4cdcb6]368{
[40d1db36]369#ifdef WITH_FFMPEG
[64d06c0]370    if (video_st && averrno == 0) {
[0aaa578]371        // Flush out any remaining data.
372        int ret = encode_frame(NULL);
373        if (ret < 0) {
374            averrno = ret;
375            return false;
[6a4cdcb6]376        }
[cc9e7a06]377        av_write_trailer(oc);
[091069f]378    }
[cc9e7a06]379
[98fd937]380    release();
381#endif
382    return true;
383}
384
[40d1db36]385#ifdef WITH_FFMPEG
[98fd937]386void
387MovieMaker::release()
388{
[0aaa578]389    // Close codec.
390    avcodec_free_context(&context);
391    av_frame_free(&frame);
[d13aea6]392    av_free(pixels);
[98fd937]393    pixels = NULL;
[0aaa578]394    sws_freeContext(sws_ctx);
[98fd937]395    sws_ctx = NULL;
[1805274]396
[0aaa578]397    // Free the stream.
398    avformat_free_context(oc);
399    oc = NULL;
[1805274]400
[f4e4b56]401    if (fh_to_close) {
402        fclose(fh_to_close);
403        fh_to_close = NULL;
404    }
[6a4cdcb6]405}
[c648bd1]406#endif
[091069f]407
[98fd937]408MovieMaker::~MovieMaker()
409{
[40d1db36]410#ifdef WITH_FFMPEG
[98fd937]411    release();
[c648bd1]412#endif
[98fd937]413}
414
[091069f]415const char *
416MovieMaker::get_error_string() const
417{
[40d1db36]418#ifdef WITH_FFMPEG
[091069f]419    switch (averrno) {
[63621a7]420        case AVERROR(EIO):
[091069f]421            return "I/O error";
[63621a7]422        case AVERROR(EDOM):
[091069f]423            return "Number syntax expected in filename";
424        case AVERROR_INVALIDDATA:
425            /* same as AVERROR_UNKNOWN: return "unknown error"; */
426            return "invalid data found";
[63621a7]427        case AVERROR(ENOMEM):
[091069f]428            return "not enough memory";
[63621a7]429        case AVERROR(EILSEQ):
[091069f]430            return "unknown format";
[63621a7]431        case AVERROR(ENOSYS):
[091069f]432            return "Operation not supported";
[63621a7]433        case AVERROR(ENOENT):
[091069f]434            return "No such file or directory";
435        case AVERROR_EOF:
436            return "End of file";
437        case AVERROR_PATCHWELCOME:
438            return "Not implemented in FFmpeg";
439        case 0:
440            return "No error";
441        case MOVIE_NO_SUITABLE_FORMAT:
442            return "Couldn't find a suitable output format";
443        case MOVIE_AUDIO_ONLY:
444            return "Audio-only format specified";
445        case MOVIE_FILENAME_TOO_LONG:
446            return "Filename too long";
447    }
[eac4514]448#endif
[f4e4b56]449    return "Unknown error";
[091069f]450}
[0aaa578]451
452#else
453
454#include "moviemaker-legacy.cc"
455
456#endif
Note: See TracBrowser for help on using the repository browser.