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
Line 
1//
2//  moviemaker.cc
3//
4//  Class for writing movies from Aven.
5//
6//  Copyright (C) 2004,2011,2012,2013,2014,2015,2016 Olly Betts
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
20//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21//
22
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
49#ifdef HAVE_CONFIG_H
50#include <config.h>
51#endif
52
53#define __STDC_CONSTANT_MACROS
54
55#include <assert.h>
56#include <stdlib.h>
57#include <string.h>
58
59#include "moviemaker.h"
60
61#ifdef WITH_LIBAV
62extern "C" {
63# include <libavutil/imgutils.h>
64# include <libavutil/mathematics.h>
65# include <libavformat/avformat.h>
66# include <libswscale/swscale.h>
67}
68#endif
69
70#if defined WITH_LIBAV && LIBAVCODEC_VERSION_MAJOR >= 57
71
72#ifdef WITH_LIBAV
73enum {
74    MOVIE_NO_SUITABLE_FORMAT = 1,
75    MOVIE_AUDIO_ONLY,
76    MOVIE_FILENAME_TOO_LONG
77};
78#endif
79
80MovieMaker::MovieMaker()
81#ifdef WITH_LIBAV
82    : oc(0), video_st(0), context(0), frame(0), pixels(0), sws_ctx(0), averrno(0)
83#endif
84{
85#ifdef WITH_LIBAV
86    static bool initialised_ffmpeg = false;
87    if (initialised_ffmpeg) return;
88
89    // FIXME: register only the codec(s) we want to use...
90    avcodec_register_all();
91    av_register_all();
92
93    initialised_ffmpeg = true;
94#endif
95}
96
97#ifdef WITH_LIBAV
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}
104#endif
105
106#define MAX_EXTENSION_LEN 8
107
108bool MovieMaker::Open(FILE* fh, const char * ext, int width, int height)
109{
110#ifdef WITH_LIBAV
111    fh_to_close = fh;
112
113    /* Allocate the output media context. */
114    char dummy_filename[MAX_EXTENSION_LEN + 3] = "x.";
115    oc = NULL;
116    if (strlen(ext) <= MAX_EXTENSION_LEN) {
117        // Use "x." + extension for format detection to avoid having to deal
118        // with wide character filenames.
119        strcpy(dummy_filename + 2, ext);
120        avformat_alloc_output_context2(&oc, NULL, NULL, dummy_filename);
121    }
122    if (!oc) {
123        averrno = MOVIE_NO_SUITABLE_FORMAT;
124        return false;
125    }
126
127    AVOutputFormat * fmt = oc->oformat;
128    if (fmt->video_codec == AV_CODEC_ID_NONE) {
129        averrno = MOVIE_AUDIO_ONLY;
130        return false;
131    }
132
133    /* find the video encoder */
134    AVCodec *codec = avcodec_find_encoder(fmt->video_codec);
135    if (!codec) {
136        // FIXME : Erm - internal ffmpeg library problem?
137        averrno = AVERROR(ENOMEM);
138        return false;
139    }
140
141    // Add the video stream.
142    video_st = avformat_new_stream(oc, NULL);
143    if (!video_st) {
144        averrno = AVERROR(ENOMEM);
145        return false;
146    }
147
148    context = avcodec_alloc_context3(codec);
149    context->codec_id = fmt->video_codec;
150    context->width = width;
151    context->height = height;
152    video_st->time_base.den = 25; // Frames per second.
153    video_st->time_base.num = 1;
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    }
167
168    /* Some formats want stream headers to be separate. */
169    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
170        context->flags |= CODEC_FLAG_GLOBAL_HEADER;
171
172    int retval;
173    retval = avcodec_open2(context, codec, NULL);
174    if (retval < 0) {
175        averrno = retval;
176        return false;
177    }
178
179    /* Allocate the encoded raw picture. */
180    frame = av_frame_alloc();
181    if (!frame) {
182        averrno = AVERROR(ENOMEM);
183        return false;
184    }
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);
192    if (retval < 0) {
193        averrno = retval;
194        return false;
195    }
196
197    if (frame->format != AV_PIX_FMT_YUV420P) {
198        // FIXME need to allocate another frame for this case if we stop
199        // hardcoding AV_PIX_FMT_YUV420P.
200        abort();
201    }
202
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    }
209
210    pixels = (unsigned char *)av_malloc(width * height * 6);
211    if (!pixels) {
212        averrno = AVERROR(ENOMEM);
213        return false;
214    }
215
216    // Show the format we've ended up with (for debug purposes).
217    // av_dump_format(oc, 0, dummy_filename, 1);
218
219    av_free(sws_ctx);
220    sws_ctx = sws_getContext(width, height, AV_PIX_FMT_RGB24,
221                             width, height, context->pix_fmt, SWS_BICUBIC,
222                             NULL, NULL, NULL);
223    if (sws_ctx == NULL) {
224        fprintf(stderr, "Cannot initialize the conversion context!\n");
225        averrno = AVERROR(ENOMEM);
226        return false;
227    }
228
229    if (!(fmt->flags & AVFMT_NOFILE)) {
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);
236            return false;
237        }
238    }
239
240    // Write the stream header, if any.
241    retval = avformat_write_header(oc, NULL);
242    if (retval < 0) {
243        averrno = retval;
244        return false;
245    }
246
247    averrno = 0;
248    return true;
249#else
250    (void)fh;
251    (void)ext;
252    (void)width;
253    (void)height;
254    return false;
255#endif
256}
257
258unsigned char * MovieMaker::GetBuffer() const {
259#ifdef WITH_LIBAV
260    return pixels + GetWidth() * GetHeight() * 3;
261#else
262    return NULL;
263#endif
264}
265
266int MovieMaker::GetWidth() const {
267#ifdef WITH_LIBAV
268    assert(video_st);
269    return video_st->codecpar->width;
270#else
271    return 0;
272#endif
273}
274
275int MovieMaker::GetHeight() const {
276#ifdef WITH_LIBAV
277    assert(video_st);
278    return video_st->codecpar->height;
279#else
280    return 0;
281#endif
282}
283
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
312bool MovieMaker::AddFrame()
313{
314#ifdef WITH_LIBAV
315    int ret = av_frame_make_writable(frame);
316    if (ret < 0) {
317        averrno = ret;
318        return false;
319    }
320
321    enum AVPixelFormat pix_fmt = context->pix_fmt;
322
323    if (pix_fmt != AV_PIX_FMT_YUV420P) {
324        // FIXME convert...
325        abort();
326    }
327
328    int len = 3 * GetWidth();
329    {
330        // Flip image vertically
331        int h = GetHeight();
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        }
339    }
340    sws_scale(sws_ctx, &pixels, &len, 0, GetHeight(),
341              frame->data, frame->linesize);
342
343    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
344        abort();
345    }
346
347    ++frame->pts;
348
349    // Encode this frame.
350    ret = encode_frame(frame);
351    if (ret < 0) {
352        averrno = ret;
353        return false;
354    }
355#endif
356    return true;
357}
358
359bool
360MovieMaker::Close()
361{
362#ifdef WITH_LIBAV
363    if (video_st && averrno == 0) {
364        // Flush out any remaining data.
365        int ret = encode_frame(NULL);
366        if (ret < 0) {
367            averrno = ret;
368            return false;
369        }
370        av_write_trailer(oc);
371    }
372
373    release();
374#endif
375    return true;
376}
377
378#ifdef WITH_LIBAV
379void
380MovieMaker::release()
381{
382    // Close codec.
383    avcodec_free_context(&context);
384    av_frame_free(&frame);
385    av_free(pixels);
386    pixels = NULL;
387    sws_freeContext(sws_ctx);
388    sws_ctx = NULL;
389
390    // Free the stream.
391    avformat_free_context(oc);
392    oc = NULL;
393
394    if (fh_to_close) {
395        fclose(fh_to_close);
396        fh_to_close = NULL;
397    }
398}
399#endif
400
401MovieMaker::~MovieMaker()
402{
403#ifdef WITH_LIBAV
404    release();
405#endif
406}
407
408const char *
409MovieMaker::get_error_string() const
410{
411#ifdef WITH_LIBAV
412    switch (averrno) {
413        case AVERROR(EIO):
414            return "I/O error";
415        case AVERROR(EDOM):
416            return "Number syntax expected in filename";
417        case AVERROR_INVALIDDATA:
418            /* same as AVERROR_UNKNOWN: return "unknown error"; */
419            return "invalid data found";
420        case AVERROR(ENOMEM):
421            return "not enough memory";
422        case AVERROR(EILSEQ):
423            return "unknown format";
424        case AVERROR(ENOSYS):
425            return "Operation not supported";
426        case AVERROR(ENOENT):
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    }
441#endif
442    return "Unknown error";
443}
444
445#else
446
447#include "moviemaker-legacy.cc"
448
449#endif
Note: See TracBrowser for help on using the repository browser.