source: git/src/moviemaker.cc @ 76cf7f1

RELEASE/1.2debug-cidebug-ci-sanitiserswalls-datawalls-data-hanging-as-warning
Last change on this file since 76cf7f1 was 0482978, checked in by Olly Betts <olly@…>, 5 years ago

Stop calling functions deprecated in ffmpeg 4.0

There's apparently no need to call these any more.

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