source: git/src/moviemaker.cc @ 709dd14

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

Allow seek during movie export

Some file formats require this, which meant that 1.2.27 broke export to
them.

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