source: git/src/moviemaker.cc @ 04078a7

faster-cavernlogwalls-datawalls-data-hanging-as-warning
Last change on this file since 04078a7 was 91a758c, checked in by Olly Betts <olly@…>, 4 weeks ago

Fix build on macOS with newer ffmpeg

  • Property mode set to 100644
File size: 11.0 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#ifdef HAVE_CONFIG_H
50#include <config.h>
51#endif
52
[cc9e7a06]53#define __STDC_CONSTANT_MACROS
54
[1805274]55#include <assert.h>
[6a4cdcb6]56#include <stdlib.h>
57#include <string.h>
58
59#include "moviemaker.h"
60
[40d1db36]61#ifdef WITH_FFMPEG
[cc9e7a06]62extern "C" {
[44c4b70]63# include <libavcodec/avcodec.h>
[b282f44]64# include <libavutil/imgutils.h>
[008f2f3]65# include <libavutil/mathematics.h>
[64d06c0]66# include <libavformat/avformat.h>
[86d8ee5]67# include <libswscale/swscale.h>
[cc9e7a06]68}
[0aaa578]69#endif
[6a4cdcb6]70
[40d1db36]71// Handle the "no FFmpeg" case in this file.
72#if !defined WITH_FFMPEG || LIBAVCODEC_VERSION_MAJOR >= 57
[0aaa578]73
[40d1db36]74#ifdef WITH_FFMPEG
[091069f]75enum {
76    MOVIE_NO_SUITABLE_FORMAT = 1,
77    MOVIE_AUDIO_ONLY,
[c648bd1]78    MOVIE_FILENAME_TOO_LONG
[091069f]79};
[bc6faa9]80#endif
[6a4cdcb6]81
[1805274]82MovieMaker::MovieMaker()
[40d1db36]83#ifdef WITH_FFMPEG
[0aaa578]84    : oc(0), video_st(0), context(0), frame(0), pixels(0), sws_ctx(0), averrno(0)
[ccb83b7]85#endif
[6a4cdcb6]86{
[40d1db36]87#ifdef WITH_FFMPEG
[6a4cdcb6]88    static bool initialised_ffmpeg = false;
[1805274]89    if (initialised_ffmpeg) return;
[6a4cdcb6]90
[0482978]91#if LIBAVCODEC_VERSION_MAJOR < 58
[64d06c0]92    avcodec_register_all();
[1805274]93    av_register_all();
[0482978]94#endif
[6a4cdcb6]95
[1805274]96    initialised_ffmpeg = true;
97#endif
98}
99
[40d1db36]100#ifdef WITH_FFMPEG
[f4e4b56]101static int
[91a758c]102write_packet(void *opaque,
103#if LIBAVFORMAT_VERSION_MAJOR < 61
104             uint8_t *buf,
105#else
106             const uint8_t *buf,
107#endif
108             int buf_size)
109{
[f4e4b56]110    FILE * fh = (FILE*)opaque;
111    size_t res = fwrite(buf, 1, buf_size, fh);
112    return res > 0 ? res : -1;
113}
[420cda9]114
115static int64_t
116seek_stream(void *opaque, int64_t offset, int whence) {
117    FILE * fh = (FILE*)opaque;
118    return fseek(fh, offset, whence);
119}
[0db0f91]120#endif
[f4e4b56]121
122#define MAX_EXTENSION_LEN 8
123
124bool MovieMaker::Open(FILE* fh, const char * ext, int width, int height)
[1805274]125{
[40d1db36]126#ifdef WITH_FFMPEG
[f4e4b56]127    fh_to_close = fh;
128
[0aaa578]129    /* Allocate the output media context. */
[f4e4b56]130    char dummy_filename[MAX_EXTENSION_LEN + 3] = "x.";
[0aaa578]131    oc = NULL;
[f4e4b56]132    if (strlen(ext) <= MAX_EXTENSION_LEN) {
[0aaa578]133        // Use "x." + extension for format detection to avoid having to deal
[f4e4b56]134        // with wide character filenames.
[0aaa578]135        strcpy(dummy_filename + 2, ext);
136        avformat_alloc_output_context2(&oc, NULL, NULL, dummy_filename);
[1805274]137    }
[0aaa578]138    if (!oc) {
139        averrno = MOVIE_NO_SUITABLE_FORMAT;
[1805274]140        return false;
[6a4cdcb6]141    }
142
[44c4b70]143    auto fmt = oc->oformat;
[0aaa578]144    if (fmt->video_codec == AV_CODEC_ID_NONE) {
145        averrno = MOVIE_AUDIO_ONLY;
[1805274]146        return false;
[6a4cdcb6]147    }
148
[64d06c0]149    /* find the video encoder */
[44c4b70]150    auto codec = avcodec_find_encoder(fmt->video_codec);
[64d06c0]151    if (!codec) {
152        // FIXME : Erm - internal ffmpeg library problem?
[63621a7]153        averrno = AVERROR(ENOMEM);
[1805274]154        return false;
[6a4cdcb6]155    }
156
[64d06c0]157    // Add the video stream.
[0aaa578]158    video_st = avformat_new_stream(oc, NULL);
[64d06c0]159    if (!video_st) {
160        averrno = AVERROR(ENOMEM);
161        return false;
162    }
[6a4cdcb6]163
[0aaa578]164    context = avcodec_alloc_context3(codec);
165    context->codec_id = fmt->video_codec;
166    context->width = width;
167    context->height = height;
[5270758]168    video_st->time_base.den = 25; // Frames per second.
169    video_st->time_base.num = 1;
[0aaa578]170    context->time_base = video_st->time_base;
171    context->bit_rate = width * height * (4 * 0.07) * context->time_base.den / context->time_base.num;
172    context->bit_rate_tolerance = context->bit_rate;
173    context->global_quality = 4;
174    context->rc_buffer_size = 2 * 1024 * 1024;
175    context->rc_max_rate = context->bit_rate * 8;
176    context->gop_size = 50; /* Twice the framerate */
177    context->pix_fmt = AV_PIX_FMT_YUV420P;
178    if (context->has_b_frames) {
179        // B frames are backwards predicted - they can improve compression,
180        // but may slow encoding and decoding.
181        context->max_b_frames = 4;
182    }
[6a4cdcb6]183
[64d06c0]184    /* Some formats want stream headers to be separate. */
[cc9e7a06]185    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
[5e46ae2]186        context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
[cc9e7a06]187
[7831cef]188    int retval;
[0aaa578]189    retval = avcodec_open2(context, codec, NULL);
[091069f]190    if (retval < 0) {
191        averrno = retval;
[1805274]192        return false;
[6a4cdcb6]193    }
[1805274]194
[64d06c0]195    /* Allocate the encoded raw picture. */
[8364c65f]196    frame = av_frame_alloc();
[cc9e7a06]197    if (!frame) {
[63621a7]198        averrno = AVERROR(ENOMEM);
[1805274]199        return false;
[6a4cdcb6]200    }
[0aaa578]201
202    frame->format = context->pix_fmt;
203    frame->width = width;
204    frame->height = height;
205    frame->pts = 0;
206
207    retval = av_frame_get_buffer(frame, 32);
[64d06c0]208    if (retval < 0) {
209        averrno = retval;
[1805274]210        return false;
[6a4cdcb6]211    }
[cc9e7a06]212
[0aaa578]213    if (frame->format != AV_PIX_FMT_YUV420P) {
[cc9e7a06]214        // FIXME need to allocate another frame for this case if we stop
[8364c65f]215        // hardcoding AV_PIX_FMT_YUV420P.
[cc9e7a06]216        abort();
217    }
[6a4cdcb6]218
[0aaa578]219    /* copy the stream parameters to the muxer */
220    retval = avcodec_parameters_from_context(video_st->codecpar, context);
221    if (retval < 0) {
222        averrno = retval;
223        return false;
224    }
[5270758]225
[d13aea6]226    pixels = (unsigned char *)av_malloc(width * height * 6);
[6a4cdcb6]227    if (!pixels) {
[63621a7]228        averrno = AVERROR(ENOMEM);
[1805274]229        return false;
[6a4cdcb6]230    }
[1805274]231
[64d06c0]232    // Show the format we've ended up with (for debug purposes).
[0aaa578]233    // av_dump_format(oc, 0, dummy_filename, 1);
[64d06c0]234
235    av_free(sws_ctx);
[ad04c87]236    sws_ctx = sws_getContext(width, height, AV_PIX_FMT_RGB24,
[0aaa578]237                             width, height, context->pix_fmt, SWS_BICUBIC,
[64d06c0]238                             NULL, NULL, NULL);
239    if (sws_ctx == NULL) {
240        fprintf(stderr, "Cannot initialize the conversion context!\n");
241        averrno = AVERROR(ENOMEM);
[1805274]242        return false;
243    }
244
[64d06c0]245    if (!(fmt->flags & AVFMT_NOFILE)) {
[f4e4b56]246        const int buf_size = 8192;
247        void * buf = av_malloc(buf_size);
248        oc->pb = avio_alloc_context(static_cast<uint8_t*>(buf), buf_size, 1,
[420cda9]249                                    fh, NULL, write_packet, seek_stream);
[f4e4b56]250        if (!oc->pb) {
251            averrno = AVERROR(ENOMEM);
[64d06c0]252            return false;
253        }
254    }
255
[1805274]256    // Write the stream header, if any.
[7831cef]257    retval = avformat_write_header(oc, NULL);
[091069f]258    if (retval < 0) {
259        averrno = retval;
[1805274]260        return false;
261    }
[9e516d0d]262
[091069f]263    averrno = 0;
[1805274]264    return true;
[6a4cdcb6]265#else
[f4e4b56]266    (void)fh;
267    (void)ext;
[6e22f11]268    (void)width;
269    (void)height;
[6a4cdcb6]270    return false;
271#endif
272}
273
274unsigned char * MovieMaker::GetBuffer() const {
[40d1db36]275#ifdef WITH_FFMPEG
[cd04101]276    return pixels + GetWidth() * GetHeight() * 3;
[eac4514]277#else
278    return NULL;
279#endif
[6a4cdcb6]280}
281
282int MovieMaker::GetWidth() const {
[40d1db36]283#ifdef WITH_FFMPEG
[ccb83b7]284    assert(video_st);
[0aaa578]285    return video_st->codecpar->width;
[1805274]286#else
287    return 0;
288#endif
[6a4cdcb6]289}
290
291int MovieMaker::GetHeight() const {
[40d1db36]292#ifdef WITH_FFMPEG
[ccb83b7]293    assert(video_st);
[0aaa578]294    return video_st->codecpar->height;
[1805274]295#else
296    return 0;
297#endif
[6a4cdcb6]298}
299
[40d1db36]300#ifdef WITH_FFMPEG
[0aaa578]301// Call with frame=NULL when done.
302int
303MovieMaker::encode_frame(AVFrame* frame_or_null)
304{
305    int ret = avcodec_send_frame(context, frame_or_null);
306    if (ret < 0) return ret;
307
308    AVPacket *pkt = av_packet_alloc();
309    pkt->size = 0;
310    while ((ret = avcodec_receive_packet(context, pkt)) == 0) {
311        // Rescale output packet timestamp values from codec to stream timebase.
312        av_packet_rescale_ts(pkt, context->time_base, video_st->time_base);
313        pkt->stream_index = video_st->index;
314
315        // Write the compressed frame to the media file.
316        ret = av_interleaved_write_frame(oc, pkt);
317        if (ret < 0) {
318            av_packet_free(&pkt);
319            release();
320            return ret;
321        }
322    }
323    av_packet_free(&pkt);
324    return 0;
325}
326#endif
327
[98fd937]328bool MovieMaker::AddFrame()
[6a4cdcb6]329{
[40d1db36]330#ifdef WITH_FFMPEG
[0aaa578]331    int ret = av_frame_make_writable(frame);
332    if (ret < 0) {
333        averrno = ret;
334        return false;
335    }
[cc9e7a06]336
[0aaa578]337    enum AVPixelFormat pix_fmt = context->pix_fmt;
338
339    if (pix_fmt != AV_PIX_FMT_YUV420P) {
[cc9e7a06]340        // FIXME convert...
341        abort();
342    }
[1805274]343
[0aaa578]344    int len = 3 * GetWidth();
[fed3713]345    {
346        // Flip image vertically
[0aaa578]347        int h = GetHeight();
[fed3713]348        unsigned char * src = pixels + h * len;
349        unsigned char * dest = src - len;
350        while (h--) {
351            memcpy(dest, src, len);
352            src += len;
353            dest -= len;
354        }
[6a4cdcb6]355    }
[0aaa578]356    sws_scale(sws_ctx, &pixels, &len, 0, GetHeight(),
357              frame->data, frame->linesize);
[6a4cdcb6]358
[0aaa578]359    ++frame->pts;
[64d06c0]360
[0aaa578]361    // Encode this frame.
362    ret = encode_frame(frame);
[64d06c0]363    if (ret < 0) {
[98fd937]364        averrno = ret;
365        return false;
[64d06c0]366    }
367#endif
[98fd937]368    return true;
[6a4cdcb6]369}
370
[98fd937]371bool
372MovieMaker::Close()
[6a4cdcb6]373{
[40d1db36]374#ifdef WITH_FFMPEG
[64d06c0]375    if (video_st && averrno == 0) {
[0aaa578]376        // Flush out any remaining data.
377        int ret = encode_frame(NULL);
378        if (ret < 0) {
379            averrno = ret;
380            return false;
[6a4cdcb6]381        }
[cc9e7a06]382        av_write_trailer(oc);
[091069f]383    }
[cc9e7a06]384
[98fd937]385    release();
386#endif
387    return true;
388}
389
[40d1db36]390#ifdef WITH_FFMPEG
[98fd937]391void
392MovieMaker::release()
393{
[0aaa578]394    // Close codec.
395    avcodec_free_context(&context);
396    av_frame_free(&frame);
[d13aea6]397    av_free(pixels);
[98fd937]398    pixels = NULL;
[0aaa578]399    sws_freeContext(sws_ctx);
[98fd937]400    sws_ctx = NULL;
[1805274]401
[0aaa578]402    // Free the stream.
403    avformat_free_context(oc);
404    oc = NULL;
[1805274]405
[f4e4b56]406    if (fh_to_close) {
407        fclose(fh_to_close);
408        fh_to_close = NULL;
409    }
[6a4cdcb6]410}
[c648bd1]411#endif
[091069f]412
[98fd937]413MovieMaker::~MovieMaker()
414{
[40d1db36]415#ifdef WITH_FFMPEG
[98fd937]416    release();
[c648bd1]417#endif
[98fd937]418}
419
[091069f]420const char *
421MovieMaker::get_error_string() const
422{
[40d1db36]423#ifdef WITH_FFMPEG
[091069f]424    switch (averrno) {
[63621a7]425        case AVERROR(EIO):
[091069f]426            return "I/O error";
[63621a7]427        case AVERROR(EDOM):
[091069f]428            return "Number syntax expected in filename";
429        case AVERROR_INVALIDDATA:
430            /* same as AVERROR_UNKNOWN: return "unknown error"; */
431            return "invalid data found";
[63621a7]432        case AVERROR(ENOMEM):
[091069f]433            return "not enough memory";
[63621a7]434        case AVERROR(EILSEQ):
[091069f]435            return "unknown format";
[63621a7]436        case AVERROR(ENOSYS):
[091069f]437            return "Operation not supported";
[63621a7]438        case AVERROR(ENOENT):
[091069f]439            return "No such file or directory";
440        case AVERROR_EOF:
441            return "End of file";
442        case AVERROR_PATCHWELCOME:
443            return "Not implemented in FFmpeg";
444        case 0:
445            return "No error";
446        case MOVIE_NO_SUITABLE_FORMAT:
447            return "Couldn't find a suitable output format";
448        case MOVIE_AUDIO_ONLY:
449            return "Audio-only format specified";
450        case MOVIE_FILENAME_TOO_LONG:
451            return "Filename too long";
452    }
[eac4514]453#endif
[f4e4b56]454    return "Unknown error";
[091069f]455}
[0aaa578]456
457#else
458
459#include "moviemaker-legacy.cc"
460
461#endif
Note: See TracBrowser for help on using the repository browser.