source: git/src/moviemaker.cc @ 7831cef

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 7831cef was 7831cef, checked in by Olly Betts <olly@…>, 13 years ago

configure.in,src/moviemaker.cc: Fix to build with FFmpeg library
versions in Debian unstable, as well as those in Debian stable.

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

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