source: git/src/moviemaker.cc @ c01f009

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since c01f009 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
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
105static int64_t
106seek_stream(void *opaque, int64_t offset, int whence) {
107    FILE * fh = (FILE*)opaque;
108    return fseek(fh, offset, whence);
109}
110#endif
111
112#define MAX_EXTENSION_LEN 8
113
114bool MovieMaker::Open(FILE* fh, const char * ext, int width, int height)
115{
116#ifdef WITH_LIBAV
117    fh_to_close = fh;
118
119    /* Allocate the output media context. */
120    char dummy_filename[MAX_EXTENSION_LEN + 3] = "x.";
121    oc = NULL;
122    if (strlen(ext) <= MAX_EXTENSION_LEN) {
123        // Use "x." + extension for format detection to avoid having to deal
124        // with wide character filenames.
125        strcpy(dummy_filename + 2, ext);
126        avformat_alloc_output_context2(&oc, NULL, NULL, dummy_filename);
127    }
128    if (!oc) {
129        averrno = MOVIE_NO_SUITABLE_FORMAT;
130        return false;
131    }
132
133    AVOutputFormat * fmt = oc->oformat;
134    if (fmt->video_codec == AV_CODEC_ID_NONE) {
135        averrno = MOVIE_AUDIO_ONLY;
136        return false;
137    }
138
139    /* find the video encoder */
140    AVCodec *codec = avcodec_find_encoder(fmt->video_codec);
141    if (!codec) {
142        // FIXME : Erm - internal ffmpeg library problem?
143        averrno = AVERROR(ENOMEM);
144        return false;
145    }
146
147    // Add the video stream.
148    video_st = avformat_new_stream(oc, NULL);
149    if (!video_st) {
150        averrno = AVERROR(ENOMEM);
151        return false;
152    }
153
154    context = avcodec_alloc_context3(codec);
155    context->codec_id = fmt->video_codec;
156    context->width = width;
157    context->height = height;
158    video_st->time_base.den = 25; // Frames per second.
159    video_st->time_base.num = 1;
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    }
173
174    /* Some formats want stream headers to be separate. */
175    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
176        context->flags |= CODEC_FLAG_GLOBAL_HEADER;
177
178    int retval;
179    retval = avcodec_open2(context, codec, NULL);
180    if (retval < 0) {
181        averrno = retval;
182        return false;
183    }
184
185    /* Allocate the encoded raw picture. */
186    frame = av_frame_alloc();
187    if (!frame) {
188        averrno = AVERROR(ENOMEM);
189        return false;
190    }
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);
198    if (retval < 0) {
199        averrno = retval;
200        return false;
201    }
202
203    if (frame->format != AV_PIX_FMT_YUV420P) {
204        // FIXME need to allocate another frame for this case if we stop
205        // hardcoding AV_PIX_FMT_YUV420P.
206        abort();
207    }
208
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    }
215
216    pixels = (unsigned char *)av_malloc(width * height * 6);
217    if (!pixels) {
218        averrno = AVERROR(ENOMEM);
219        return false;
220    }
221
222    // Show the format we've ended up with (for debug purposes).
223    // av_dump_format(oc, 0, dummy_filename, 1);
224
225    av_free(sws_ctx);
226    sws_ctx = sws_getContext(width, height, AV_PIX_FMT_RGB24,
227                             width, height, context->pix_fmt, SWS_BICUBIC,
228                             NULL, NULL, NULL);
229    if (sws_ctx == NULL) {
230        fprintf(stderr, "Cannot initialize the conversion context!\n");
231        averrno = AVERROR(ENOMEM);
232        return false;
233    }
234
235    if (!(fmt->flags & AVFMT_NOFILE)) {
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,
239                                    fh, NULL, write_packet, seek_stream);
240        if (!oc->pb) {
241            averrno = AVERROR(ENOMEM);
242            return false;
243        }
244    }
245
246    // Write the stream header, if any.
247    retval = avformat_write_header(oc, NULL);
248    if (retval < 0) {
249        averrno = retval;
250        return false;
251    }
252
253    averrno = 0;
254    return true;
255#else
256    (void)fh;
257    (void)ext;
258    (void)width;
259    (void)height;
260    return false;
261#endif
262}
263
264unsigned char * MovieMaker::GetBuffer() const {
265#ifdef WITH_LIBAV
266    return pixels + GetWidth() * GetHeight() * 3;
267#else
268    return NULL;
269#endif
270}
271
272int MovieMaker::GetWidth() const {
273#ifdef WITH_LIBAV
274    assert(video_st);
275    return video_st->codecpar->width;
276#else
277    return 0;
278#endif
279}
280
281int MovieMaker::GetHeight() const {
282#ifdef WITH_LIBAV
283    assert(video_st);
284    return video_st->codecpar->height;
285#else
286    return 0;
287#endif
288}
289
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
318bool MovieMaker::AddFrame()
319{
320#ifdef WITH_LIBAV
321    int ret = av_frame_make_writable(frame);
322    if (ret < 0) {
323        averrno = ret;
324        return false;
325    }
326
327    enum AVPixelFormat pix_fmt = context->pix_fmt;
328
329    if (pix_fmt != AV_PIX_FMT_YUV420P) {
330        // FIXME convert...
331        abort();
332    }
333
334    int len = 3 * GetWidth();
335    {
336        // Flip image vertically
337        int h = GetHeight();
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        }
345    }
346    sws_scale(sws_ctx, &pixels, &len, 0, GetHeight(),
347              frame->data, frame->linesize);
348
349    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
350        abort();
351    }
352
353    ++frame->pts;
354
355    // Encode this frame.
356    ret = encode_frame(frame);
357    if (ret < 0) {
358        averrno = ret;
359        return false;
360    }
361#endif
362    return true;
363}
364
365bool
366MovieMaker::Close()
367{
368#ifdef WITH_LIBAV
369    if (video_st && averrno == 0) {
370        // Flush out any remaining data.
371        int ret = encode_frame(NULL);
372        if (ret < 0) {
373            averrno = ret;
374            return false;
375        }
376        av_write_trailer(oc);
377    }
378
379    release();
380#endif
381    return true;
382}
383
384#ifdef WITH_LIBAV
385void
386MovieMaker::release()
387{
388    // Close codec.
389    avcodec_free_context(&context);
390    av_frame_free(&frame);
391    av_free(pixels);
392    pixels = NULL;
393    sws_freeContext(sws_ctx);
394    sws_ctx = NULL;
395
396    // Free the stream.
397    avformat_free_context(oc);
398    oc = NULL;
399
400    if (fh_to_close) {
401        fclose(fh_to_close);
402        fh_to_close = NULL;
403    }
404}
405#endif
406
407MovieMaker::~MovieMaker()
408{
409#ifdef WITH_LIBAV
410    release();
411#endif
412}
413
414const char *
415MovieMaker::get_error_string() const
416{
417#ifdef WITH_LIBAV
418    switch (averrno) {
419        case AVERROR(EIO):
420            return "I/O error";
421        case AVERROR(EDOM):
422            return "Number syntax expected in filename";
423        case AVERROR_INVALIDDATA:
424            /* same as AVERROR_UNKNOWN: return "unknown error"; */
425            return "invalid data found";
426        case AVERROR(ENOMEM):
427            return "not enough memory";
428        case AVERROR(EILSEQ):
429            return "unknown format";
430        case AVERROR(ENOSYS):
431            return "Operation not supported";
432        case AVERROR(ENOENT):
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    }
447#endif
448    return "Unknown error";
449}
450
451#else
452
453#include "moviemaker-legacy.cc"
454
455#endif
Note: See TracBrowser for help on using the repository browser.