source: git/src/moviemaker.cc @ 64fba42

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 64fba42 was 5e46ae2, checked in by Olly Betts <olly@…>, 7 years ago

Update for upcoming FFmpeg 3.5

Should still work with the older versions that currently work.

Reported by James Cowgill in https://bugs.debian.org/888334

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