source: git/src/moviemaker.cc @ eac4514

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

src/moviemaker.cc: Fix disabling of libavcodec-using code when
libavcodec isn't present.

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

  • Property mode set to 100644
File size: 10.7 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" {
63#include "libavformat/avformat.h"
[9e516d0d]64#include "libswscale/swscale.h"
[cc9e7a06]65}
66#ifndef AV_PKT_FLAG_KEY
67# define AV_PKT_FLAG_KEY PKT_FLAG_KEY
68#endif
[6a4cdcb6]69#endif
70
[091069f]71enum {
72    MOVIE_NO_SUITABLE_FORMAT = 1,
73    MOVIE_AUDIO_ONLY,
74    MOVIE_FILENAME_TOO_LONG,
75    MOVIE_NOT_ENABLED
76};
77
[1805274]78const int OUTBUF_SIZE = 200000;
[6a4cdcb6]79
[1805274]80MovieMaker::MovieMaker()
[091069f]81    : oc(0), st(0), frame(0), outbuf(0), pixels(0), sws_ctx(0), averrno(0)
[6a4cdcb6]82{
[cc9e7a06]83#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[6a4cdcb6]84    static bool initialised_ffmpeg = false;
[1805274]85    if (initialised_ffmpeg) return;
[6a4cdcb6]86
[1805274]87    // FIXME: register only the codec(s) we want to use...
88    av_register_all();
[6a4cdcb6]89
[1805274]90    initialised_ffmpeg = true;
91#endif
92}
93
94bool MovieMaker::Open(const char *fnm, int width, int height)
95{
[cc9e7a06]96#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[1805274]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) {
[091069f]103            averrno = MOVIE_NO_SUITABLE_FORMAT;
[1805274]104            return false;
105        }
106    }
107    if (fmt->video_codec == CODEC_ID_NONE) {
[091069f]108        averrno = MOVIE_AUDIO_ONLY;
[1805274]109        return false;
[6a4cdcb6]110    }
111
[1805274]112    // Allocate the output media context.
[6ed625e]113    oc = avformat_alloc_context();
[1805274]114    if (!oc) {
[091069f]115        averrno = AVERROR_NOMEM;
[1805274]116        return false;
[6a4cdcb6]117    }
[1805274]118    oc->oformat = fmt;
119    if (strlen(fnm) >= sizeof(oc->filename)) {
[091069f]120        averrno = MOVIE_FILENAME_TOO_LONG;
[1805274]121        return false;
122    }
123    strcpy(oc->filename, fnm);
[6a4cdcb6]124
[1805274]125    // Add the video stream using the default format codec.
126    st = av_new_stream(oc, 0);
127    if (!st) {
[091069f]128        averrno = AVERROR_NOMEM;
[1805274]129        return false;
[6a4cdcb6]130    }
131
[1805274]132    // Initialise the code.
[cc9e7a06]133    AVCodecContext *c = st->codec;
[1805274]134    c->codec_id = fmt->video_codec;
135    c->codec_type = CODEC_TYPE_VIDEO;
[6a4cdcb6]136
137    // Set sample parameters.
138    c->bit_rate = 400000;
[1805274]139    c->width = width;
140    c->height = height;
[cc9e7a06]141    c->time_base.num = 1;
142    c->time_base.den = 25; // Frames per second.
[1805274]143    c->gop_size = 12; // One intra frame every twelve frames.
[6a4cdcb6]144    c->pix_fmt = PIX_FMT_YUV420P;
[1805274]145    // B frames are backwards predicted - they can improve compression,
146    // but may slow encoding and decoding.
147    // c->max_b_frames = 2;
[6a4cdcb6]148
[cc9e7a06]149    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
150        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
151
[1805274]152    // Set the output parameters (must be done even if no parameters).
[091069f]153    int retval = av_set_parameters(oc, NULL);
154    if (retval < 0) {
155        averrno = retval;
[1805274]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    }
[091069f]168
169    retval = avcodec_open(c, codec);
170    if (retval < 0) {
171        averrno = retval;
[1805274]172        return false;
[6a4cdcb6]173    }
[1805274]174
[cc9e7a06]175    if ((oc->oformat->flags & AVFMT_RAWPICTURE)) {
176        outbuf = NULL;
177    } else {
178        outbuf = (unsigned char *)malloc(OUTBUF_SIZE);
179        if (!outbuf) {
[091069f]180            averrno = AVERROR_NOMEM;
[cc9e7a06]181            return false;
182        }
[6a4cdcb6]183    }
[1805274]184
[6a4cdcb6]185    frame = avcodec_alloc_frame();
[cc9e7a06]186    if (!frame) {
[091069f]187        averrno = AVERROR_NOMEM;
[1805274]188        return false;
[6a4cdcb6]189    }
[cc9e7a06]190    int size = avpicture_get_size(c->pix_fmt, width, height);
[9e516d0d]191    uint8_t * picture_buf = (uint8_t*)av_malloc(size);
192    if (!picture_buf) {
[cc9e7a06]193        av_free(frame);
[091069f]194        averrno = AVERROR_NOMEM;
[1805274]195        return false;
[6a4cdcb6]196    }
[9e516d0d]197    avpicture_fill((AVPicture *)frame, picture_buf, c->pix_fmt, width, height);
[cc9e7a06]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    }
[6a4cdcb6]204
205    pixels = (unsigned char *)malloc(width * height * 6);
206    if (!pixels) {
[091069f]207        averrno = AVERROR_NOMEM;
[1805274]208        return false;
[6a4cdcb6]209    }
[1805274]210
[091069f]211    retval = url_fopen(&oc->pb, fnm, URL_WRONLY);
212    if (retval < 0) {
213        averrno = retval;
[1805274]214        return false;
215    }
216
217    // Write the stream header, if any.
[091069f]218    retval = av_write_header(oc);
219    if (retval < 0) {
220        averrno = retval;
[1805274]221        return false;
222    }
[9e516d0d]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
[091069f]233    averrno = 0;
[1805274]234    return true;
[6a4cdcb6]235#else
[091069f]236    averrno = MOVIE_NOT_ENABLED;
[6a4cdcb6]237    return false;
238#endif
239}
240
241unsigned char * MovieMaker::GetBuffer() const {
[eac4514]242#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[9e516d0d]243    AVCodecContext * c = st->codec;
244    return pixels + c->height * c->width * 3;
[eac4514]245#else
246    return NULL;
247#endif
[6a4cdcb6]248}
249
250int MovieMaker::GetWidth() const {
[1805274]251    assert(st);
[cc9e7a06]252#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
253    AVCodecContext *c = st->codec;
[6a4cdcb6]254    return c->width;
[1805274]255#else
256    return 0;
257#endif
[6a4cdcb6]258}
259
260int MovieMaker::GetHeight() const {
[1805274]261    assert(st);
[cc9e7a06]262#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
263    AVCodecContext *c = st->codec;
[6a4cdcb6]264    return c->height;
[1805274]265#else
266    return 0;
267#endif
[6a4cdcb6]268}
269
270void MovieMaker::AddFrame()
271{
[cc9e7a06]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    }
[1805274]279
[9e516d0d]280    int len = 3 * c->width;
[fed3713]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        }
[6a4cdcb6]291    }
[9e516d0d]292    sws_scale(sws_ctx, &pixels, &len, 0, c->height, frame->data, frame->linesize);
[6a4cdcb6]293
[cc9e7a06]294    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
295        abort();
296    }
[6a4cdcb6]297
[1805274]298    // Encode this frame.
[6a4cdcb6]299    out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, frame);
[1805274]300    // outsize == 0 means that this frame has been buffered, so there's nothing
301    // to write yet.
[cc9e7a06]302    if (out_size) {
[1805274]303        // Write the compressed frame to the media file.
[cc9e7a06]304        AVPacket pkt;
305        av_init_packet(&pkt);
306
307        if (c->coded_frame->pts != 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();
[1805274]318        }
[6a4cdcb6]319    }
320#endif
321}
322
323MovieMaker::~MovieMaker()
324{
[cc9e7a06]325#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[091069f]326    if (st && averrno == 0) {
[1805274]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.
[cc9e7a06]329        AVCodecContext * c = st->codec;
[1805274]330
331        while (out_size) {
332            out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, NULL);
333            if (out_size) {
[cc9e7a06]334                // Write the compressed frame to the media file.
335                AVPacket pkt;
336                av_init_packet(&pkt);
337
338                if (c->coded_frame->pts != 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();
[1805274]349                }
350            }
[6a4cdcb6]351        }
352
[cc9e7a06]353        av_write_trailer(oc);
[091069f]354    }
[cc9e7a06]355
[091069f]356    if (st) {
[1805274]357        // Close codec.
[091069f]358        avcodec_close(st->codec);
[6a4cdcb6]359    }
360
[cc9e7a06]361    if (frame) {
362        free(frame->data[0]);
363        free(frame);
364    }
[1805274]365    free(outbuf);
[6a4cdcb6]366    free(pixels);
[9e516d0d]367    av_free(sws_ctx);
[1805274]368
369    if (oc) {
370        // Free the streams.
[cc9e7a06]371        for (size_t i = 0; i < oc->nb_streams; ++i) {
372            av_freep(&oc->streams[i]->codec);
[1805274]373            av_freep(&oc->streams[i]);
374        }
375
[cc9e7a06]376        if (!(oc->oformat->flags & AVFMT_NOFILE)) {
377            // Close the output file.
378            url_fclose(oc->pb);
379        }
[1805274]380
381        // Free the stream.
[6ed625e]382        av_free(oc);
[1805274]383    }
[6a4cdcb6]384#endif
385}
[091069f]386
387const char *
388MovieMaker::get_error_string() const
389{
[eac4514]390#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[091069f]391    switch (averrno) {
392        case AVERROR_IO:
393            return "I/O error";
394        case AVERROR_NUMEXPECTED:
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_NOMEM:
400            return "not enough memory";
401        case AVERROR_NOFMT:
402            return "unknown format";
403        case AVERROR_NOTSUPP:
404            return "Operation not supported";
405        case AVERROR_NOENT:
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";
[eac4514]423#else
424    return "Movie generation support code not present";
425#endif
[091069f]426}
Note: See TracBrowser for help on using the repository browser.