source: git/src/moviemaker.cc @ 0aaa578

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 0aaa578 was 0aaa578, checked in by Olly Betts <olly@…>, 9 years ago

Overhaul movie export for current FFmpeg API

The code in moviemaker.cc now only handles the current API, and I've
split out moviemaker-legacy.cc for older versions - once those versions
are all obsolete, we can just remove that file.

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