source: git/src/moviemaker.cc @ 63621a7

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 63621a7 was 63621a7, checked in by Olly Betts <olly@…>, 13 years ago

src/moviemaker.cc: Updates towards compatibility with newer FFmpeg
libraries without breaking build with those in Debian stable.

git-svn-id: file:///home/survex-svn/survex/trunk@3668 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 10.7 KB
Line 
1//
2//  moviemaker.cc
3//
4//  Class for writing movies from Aven.
5//
6//  Copyright (C) 2004,2011 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 HAVE_LIBAVFORMAT_AVFORMAT_H
62extern "C" {
63#include "libavformat/avformat.h"
64#include "libswscale/swscale.h"
65}
66#ifndef AV_PKT_FLAG_KEY
67# define AV_PKT_FLAG_KEY PKT_FLAG_KEY
68#endif
69#endif
70
71enum {
72    MOVIE_NO_SUITABLE_FORMAT = 1,
73    MOVIE_AUDIO_ONLY,
74    MOVIE_FILENAME_TOO_LONG,
75    MOVIE_NOT_ENABLED
76};
77
78const int OUTBUF_SIZE = 200000;
79
80MovieMaker::MovieMaker()
81    : oc(0), st(0), frame(0), outbuf(0), pixels(0), sws_ctx(0), averrno(0)
82{
83#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
84    static bool initialised_ffmpeg = false;
85    if (initialised_ffmpeg) return;
86
87    // FIXME: register only the codec(s) we want to use...
88    av_register_all();
89
90    initialised_ffmpeg = true;
91#endif
92}
93
94bool MovieMaker::Open(const char *fnm, int width, int height)
95{
96#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
97    AVOutputFormat * fmt = guess_format(NULL, fnm, NULL);
98    if (!fmt) {
99        // We couldn't deduce the output format from file extension so default
100        // to MPEG.
101        fmt = guess_format("mpeg", NULL, NULL);
102        if (!fmt) {
103            averrno = MOVIE_NO_SUITABLE_FORMAT;
104            return false;
105        }
106    }
107    if (fmt->video_codec == CODEC_ID_NONE) {
108        averrno = MOVIE_AUDIO_ONLY;
109        return false;
110    }
111
112    // Allocate the output media context.
113    oc = avformat_alloc_context();
114    if (!oc) {
115        averrno = AVERROR(ENOMEM);
116        return false;
117    }
118    oc->oformat = fmt;
119    if (strlen(fnm) >= sizeof(oc->filename)) {
120        averrno = MOVIE_FILENAME_TOO_LONG;
121        return false;
122    }
123    strcpy(oc->filename, fnm);
124
125    // Add the video stream using the default format codec.
126    st = av_new_stream(oc, 0);
127    if (!st) {
128        averrno = AVERROR(ENOMEM);
129        return false;
130    }
131
132    // Initialise the code.
133    AVCodecContext *c = st->codec;
134    c->codec_id = fmt->video_codec;
135    c->codec_type = CODEC_TYPE_VIDEO;
136
137    // Set sample parameters.
138    c->bit_rate = 400000;
139    c->width = width;
140    c->height = height;
141    c->time_base.num = 1;
142    c->time_base.den = 25; // Frames per second.
143    c->gop_size = 12; // One intra frame every twelve frames.
144    c->pix_fmt = PIX_FMT_YUV420P;
145    // B frames are backwards predicted - they can improve compression,
146    // but may slow encoding and decoding.
147    // c->max_b_frames = 2;
148
149    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
150        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
151
152    // Set the output parameters (must be done even if no parameters).
153    int retval = av_set_parameters(oc, NULL);
154    if (retval < 0) {
155        averrno = retval;
156        return false;
157    }
158
159    // Show the format we've ended up with (for debug purposes).
160    // dump_format(oc, 0, fnm, 1);
161
162    // Open the video codec and allocate the necessary encode buffers.
163    AVCodec * codec = avcodec_find_encoder(c->codec_id);
164    if (!codec) {
165        // FIXME : Erm - internal ffmpeg library problem?
166        return false;
167    }
168
169    retval = avcodec_open(c, codec);
170    if (retval < 0) {
171        averrno = retval;
172        return false;
173    }
174
175    if ((oc->oformat->flags & AVFMT_RAWPICTURE)) {
176        outbuf = NULL;
177    } else {
178        outbuf = (unsigned char *)malloc(OUTBUF_SIZE);
179        if (!outbuf) {
180            averrno = AVERROR(ENOMEM);
181            return false;
182        }
183    }
184
185    frame = avcodec_alloc_frame();
186    if (!frame) {
187        averrno = AVERROR(ENOMEM);
188        return false;
189    }
190    int size = avpicture_get_size(c->pix_fmt, width, height);
191    uint8_t * picture_buf = (uint8_t*)av_malloc(size);
192    if (!picture_buf) {
193        av_free(frame);
194        averrno = AVERROR(ENOMEM);
195        return false;
196    }
197    avpicture_fill((AVPicture *)frame, picture_buf, c->pix_fmt, width, height);
198
199    if (c->pix_fmt != PIX_FMT_YUV420P) {
200        // FIXME need to allocate another frame for this case if we stop
201        // hardcoding PIX_FMT_YUV420P.
202        abort();
203    }
204
205    pixels = (unsigned char *)malloc(width * height * 6);
206    if (!pixels) {
207        averrno = AVERROR(ENOMEM);
208        return false;
209    }
210
211    retval = url_fopen(&oc->pb, fnm, URL_WRONLY);
212    if (retval < 0) {
213        averrno = retval;
214        return false;
215    }
216
217    // Write the stream header, if any.
218    retval = av_write_header(oc);
219    if (retval < 0) {
220        averrno = retval;
221        return false;
222    }
223
224    av_free(sws_ctx);
225    sws_ctx = sws_getContext(width, height, PIX_FMT_RGB24,
226                             width, height, c->pix_fmt, SWS_BICUBIC,
227                             NULL, NULL, NULL);
228    if (sws_ctx == NULL) {
229        fprintf(stderr, "Cannot initialize the conversion context!\n");
230        return false;
231    }
232
233    averrno = 0;
234    return true;
235#else
236    averrno = MOVIE_NOT_ENABLED;
237    return false;
238#endif
239}
240
241unsigned char * MovieMaker::GetBuffer() const {
242#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
243    AVCodecContext * c = st->codec;
244    return pixels + c->height * c->width * 3;
245#else
246    return NULL;
247#endif
248}
249
250int MovieMaker::GetWidth() const {
251    assert(st);
252#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
253    AVCodecContext *c = st->codec;
254    return c->width;
255#else
256    return 0;
257#endif
258}
259
260int MovieMaker::GetHeight() const {
261    assert(st);
262#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
263    AVCodecContext *c = st->codec;
264    return c->height;
265#else
266    return 0;
267#endif
268}
269
270void MovieMaker::AddFrame()
271{
272#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
273    AVCodecContext * c = st->codec;
274
275    if (c->pix_fmt != PIX_FMT_YUV420P) {
276        // FIXME convert...
277        abort();
278    }
279
280    int len = 3 * c->width;
281    {
282        // Flip image vertically
283        int h = c->height;
284        unsigned char * src = pixels + h * len;
285        unsigned char * dest = src - len;
286        while (h--) {
287            memcpy(dest, src, len);
288            src += len;
289            dest -= len;
290        }
291    }
292    sws_scale(sws_ctx, &pixels, &len, 0, c->height, frame->data, frame->linesize);
293
294    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
295        abort();
296    }
297
298    // Encode this frame.
299    out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, frame);
300    // outsize == 0 means that this frame has been buffered, so there's nothing
301    // to write yet.
302    if (out_size) {
303        // Write the compressed frame to the media file.
304        AVPacket pkt;
305        av_init_packet(&pkt);
306
307        if (c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
308            pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
309        if (c->coded_frame->key_frame)
310            pkt.flags |= AV_PKT_FLAG_KEY;
311        pkt.stream_index = st->index;
312        pkt.data = outbuf;
313        pkt.size = out_size;
314
315        /* write the compressed frame in the media file */
316        if (av_interleaved_write_frame(oc, &pkt) != 0) {
317            abort();
318        }
319    }
320#endif
321}
322
323MovieMaker::~MovieMaker()
324{
325#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
326    if (st && averrno == 0) {
327        // No more frames to compress.  The codec may have a few frames
328        // buffered if we're using B frames, so write those too.
329        AVCodecContext * c = st->codec;
330
331        while (out_size) {
332            out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, NULL);
333            if (out_size) {
334                // Write the compressed frame to the media file.
335                AVPacket pkt;
336                av_init_packet(&pkt);
337
338                if (c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
339                    pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
340                if (c->coded_frame->key_frame)
341                    pkt.flags |= AV_PKT_FLAG_KEY;
342                pkt.stream_index = st->index;
343                pkt.data = outbuf;
344                pkt.size = out_size;
345
346                /* write the compressed frame in the media file */
347                if (av_interleaved_write_frame(oc, &pkt) != 0) {
348                    abort();
349                }
350            }
351        }
352
353        av_write_trailer(oc);
354    }
355
356    if (st) {
357        // Close codec.
358        avcodec_close(st->codec);
359    }
360
361    if (frame) {
362        free(frame->data[0]);
363        free(frame);
364    }
365    free(outbuf);
366    free(pixels);
367    av_free(sws_ctx);
368
369    if (oc) {
370        // Free the streams.
371        for (size_t i = 0; i < oc->nb_streams; ++i) {
372            av_freep(&oc->streams[i]->codec);
373            av_freep(&oc->streams[i]);
374        }
375
376        if (!(oc->oformat->flags & AVFMT_NOFILE)) {
377            // Close the output file.
378            url_fclose(oc->pb);
379        }
380
381        // Free the stream.
382        av_free(oc);
383    }
384#endif
385}
386
387const char *
388MovieMaker::get_error_string() const
389{
390#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
391    switch (averrno) {
392        case AVERROR(EIO):
393            return "I/O error";
394        case AVERROR(EDOM):
395            return "Number syntax expected in filename";
396        case AVERROR_INVALIDDATA:
397            /* same as AVERROR_UNKNOWN: return "unknown error"; */
398            return "invalid data found";
399        case AVERROR(ENOMEM):
400            return "not enough memory";
401        case AVERROR(EILSEQ):
402            return "unknown format";
403        case AVERROR(ENOSYS):
404            return "Operation not supported";
405        case AVERROR(ENOENT):
406            return "No such file or directory";
407        case AVERROR_EOF:
408            return "End of file";
409        case AVERROR_PATCHWELCOME:
410            return "Not implemented in FFmpeg";
411        case 0:
412            return "No error";
413        case MOVIE_NO_SUITABLE_FORMAT:
414            return "Couldn't find a suitable output format";
415        case MOVIE_AUDIO_ONLY:
416            return "Audio-only format specified";
417        case MOVIE_FILENAME_TOO_LONG:
418            return "Filename too long";
419        case MOVIE_NOT_ENABLED:
420            return "Movie export support not included";
421    }
422    return "Unknown error";
423#else
424    return "Movie generation support code not present";
425#endif
426}
Note: See TracBrowser for help on using the repository browser.