source: git/src/moviemaker.cc @ 1d6ac30

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

configure.ac,src/moviemaker.cc: Use avcodec_free_frame() if it's
available.

  • Property mode set to 100644
File size: 14.3 KB
RevLine 
[6a4cdcb6]1//
2//  moviemaker.cc
3//
4//  Class for writing movies from Aven.
5//
[64d06c0]6//  Copyright (C) 2004,2011,2012,2013 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" {
[008f2f3]63# include <libavutil/mathematics.h>
[64d06c0]64# include <libavformat/avformat.h>
[86d8ee5]65# include <libswscale/swscale.h>
[cc9e7a06]66}
[7831cef]67# ifndef AV_PKT_FLAG_KEY
68#  define AV_PKT_FLAG_KEY PKT_FLAG_KEY
69# endif
70# ifndef HAVE_AV_GUESS_FORMAT
71#  define av_guess_format guess_format
72# endif
73# ifndef HAVE_AVIO_OPEN
74#  define avio_open url_fopen
75# endif
76# ifndef HAVE_AVIO_CLOSE
77#  define avio_close url_fclose
78# endif
[cc69cf5]79# ifndef HAVE_AVCODEC_FREE_FRAME
80static inline void avcodec_free_frame(AVFrame * frame) {
81    free(frame->data[0]);
82    free(frame);
83}
84# endif
[86d8ee5]85# ifndef HAVE_AVCODEC_OPEN2
86// We always pass NULL for OPTS below.
87#  define avcodec_open2(CTX, CODEC, OPTS) avcodec_open(CTX, CODEC)
88# endif
89# ifndef HAVE_AVFORMAT_NEW_STREAM
90// We always pass NULL for CODEC below.
91#  define avformat_new_stream(S, CODEC) av_new_stream(S, 0)
92# endif
[7831cef]93# if !HAVE_DECL_AVMEDIA_TYPE_VIDEO
94#  define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
95# endif
[64d06c0]96# if !HAVE_DECL_AVCODEC_ID_NONE
97#  define AVCODEC_ID_NONE CODEC_ID_NONE
98# endif
99# if !HAVE_DECL_AV_PIX_FMT_YUV420P
100#  define AV_PIX_FMT_YUV420P PIX_FMT_YUV420P
101# endif
102# ifndef AVIO_FLAG_WRITE
103#  define AVIO_FLAG_WRITE URL_WRONLY
104# endif
[6a4cdcb6]105#endif
106
[091069f]107enum {
108    MOVIE_NO_SUITABLE_FORMAT = 1,
109    MOVIE_AUDIO_ONLY,
110    MOVIE_FILENAME_TOO_LONG,
111    MOVIE_NOT_ENABLED
112};
113
[1805274]114const int OUTBUF_SIZE = 200000;
[6a4cdcb6]115
[1805274]116MovieMaker::MovieMaker()
[64d06c0]117    : oc(0), video_st(0), frame(0), outbuf(0), pixels(0), sws_ctx(0), averrno(0)
[6a4cdcb6]118{
[cc9e7a06]119#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[6a4cdcb6]120    static bool initialised_ffmpeg = false;
[1805274]121    if (initialised_ffmpeg) return;
[6a4cdcb6]122
[1805274]123    // FIXME: register only the codec(s) we want to use...
[64d06c0]124    avcodec_register_all();
[1805274]125    av_register_all();
[6a4cdcb6]126
[1805274]127    initialised_ffmpeg = true;
128#endif
129}
130
131bool MovieMaker::Open(const char *fnm, int width, int height)
132{
[cc9e7a06]133#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[7831cef]134    AVOutputFormat * fmt = av_guess_format(NULL, fnm, NULL);
[1805274]135    if (!fmt) {
136        // We couldn't deduce the output format from file extension so default
137        // to MPEG.
[7831cef]138        fmt = av_guess_format("mpeg", NULL, NULL);
[1805274]139        if (!fmt) {
[091069f]140            averrno = MOVIE_NO_SUITABLE_FORMAT;
[1805274]141            return false;
142        }
143    }
[64d06c0]144    if (fmt->video_codec == AVCODEC_ID_NONE) {
[091069f]145        averrno = MOVIE_AUDIO_ONLY;
[1805274]146        return false;
[6a4cdcb6]147    }
148
[64d06c0]149    /* Allocate the output media context. */
[6ed625e]150    oc = avformat_alloc_context();
[1805274]151    if (!oc) {
[63621a7]152        averrno = AVERROR(ENOMEM);
[1805274]153        return false;
[6a4cdcb6]154    }
[1805274]155    oc->oformat = fmt;
156    if (strlen(fnm) >= sizeof(oc->filename)) {
[091069f]157        averrno = MOVIE_FILENAME_TOO_LONG;
[1805274]158        return false;
159    }
160    strcpy(oc->filename, fnm);
[6a4cdcb6]161
[64d06c0]162    /* find the video encoder */
163    AVCodec *codec = avcodec_find_encoder(fmt->video_codec);
164    if (!codec) {
165        // FIXME : Erm - internal ffmpeg library problem?
[63621a7]166        averrno = AVERROR(ENOMEM);
[1805274]167        return false;
[6a4cdcb6]168    }
169
[64d06c0]170    // Add the video stream.
171    video_st = avformat_new_stream(oc, codec);
172    if (!video_st) {
173        averrno = AVERROR(ENOMEM);
174        return false;
175    }
[6a4cdcb6]176
177    // Set sample parameters.
[64d06c0]178    AVCodecContext *c = video_st->codec;
[6a4cdcb6]179    c->bit_rate = 400000;
[64d06c0]180    /* Resolution must be a multiple of two. */
[1805274]181    c->width = width;
182    c->height = height;
[64d06c0]183    /* timebase: This is the fundamental unit of time (in seconds) in terms
184     * of which frame timestamps are represented. For fixed-fps content,
185     * timebase should be 1/framerate and timestamp increments should be
186     * identical to 1. */
[cc9e7a06]187    c->time_base.den = 25; // Frames per second.
[64d06c0]188    c->time_base.num = 1;
189    c->gop_size = 12; /* emit one intra frame every twelve frames at most */
190    c->pix_fmt = AV_PIX_FMT_YUV420P;
[1805274]191    // B frames are backwards predicted - they can improve compression,
192    // but may slow encoding and decoding.
[64d06c0]193    // if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
194    //     c->max_b_frames = 2;
195    // }
[6a4cdcb6]196
[64d06c0]197    /* Some formats want stream headers to be separate. */
[cc9e7a06]198    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
199        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
200
[7831cef]201    int retval;
202#ifndef HAVE_AVFORMAT_WRITE_HEADER
[1805274]203    // Set the output parameters (must be done even if no parameters).
[7831cef]204    retval = av_set_parameters(oc, NULL);
[091069f]205    if (retval < 0) {
206        averrno = retval;
[1805274]207        return false;
208    }
[7831cef]209#endif
[1805274]210
[64d06c0]211    retval = avcodec_open2(c, NULL, NULL);
[091069f]212    if (retval < 0) {
213        averrno = retval;
[1805274]214        return false;
[6a4cdcb6]215    }
[1805274]216
[64d06c0]217#ifndef HAVE_AVCODEC_ENCODE_VIDEO2
218    outbuf = NULL;
219    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
[cc9e7a06]220        outbuf = (unsigned char *)malloc(OUTBUF_SIZE);
221        if (!outbuf) {
[63621a7]222            averrno = AVERROR(ENOMEM);
[cc9e7a06]223            return false;
224        }
[6a4cdcb6]225    }
[64d06c0]226#endif
[1805274]227
[64d06c0]228    /* Allocate the encoded raw picture. */
[6a4cdcb6]229    frame = avcodec_alloc_frame();
[cc9e7a06]230    if (!frame) {
[63621a7]231        averrno = AVERROR(ENOMEM);
[1805274]232        return false;
[6a4cdcb6]233    }
[64d06c0]234    retval = avpicture_alloc((AVPicture *)frame, c->pix_fmt, c->width, c->height);
235    if (retval < 0) {
236        averrno = retval;
[1805274]237        return false;
[6a4cdcb6]238    }
[cc9e7a06]239
240    if (c->pix_fmt != PIX_FMT_YUV420P) {
241        // FIXME need to allocate another frame for this case if we stop
242        // hardcoding PIX_FMT_YUV420P.
243        abort();
244    }
[6a4cdcb6]245
246    pixels = (unsigned char *)malloc(width * height * 6);
247    if (!pixels) {
[63621a7]248        averrno = AVERROR(ENOMEM);
[1805274]249        return false;
[6a4cdcb6]250    }
[1805274]251
[64d06c0]252    // Show the format we've ended up with (for debug purposes).
253    // av_dump_format(oc, 0, fnm, 1);
254
255    av_free(sws_ctx);
256    sws_ctx = sws_getContext(width, height, PIX_FMT_RGB24,
257                             width, height, c->pix_fmt, SWS_BICUBIC,
258                             NULL, NULL, NULL);
259    if (sws_ctx == NULL) {
260        fprintf(stderr, "Cannot initialize the conversion context!\n");
261        averrno = AVERROR(ENOMEM);
[1805274]262        return false;
263    }
264
[64d06c0]265    if (!(fmt->flags & AVFMT_NOFILE)) {
266        retval = avio_open(&oc->pb, fnm, AVIO_FLAG_WRITE);
267        if (retval < 0) {
268            averrno = retval;
269            return false;
270        }
271    }
272
[1805274]273    // Write the stream header, if any.
[7831cef]274#ifdef HAVE_AVFORMAT_WRITE_HEADER
275    retval = avformat_write_header(oc, NULL);
276#else
[091069f]277    retval = av_write_header(oc);
[7831cef]278#endif
[091069f]279    if (retval < 0) {
280        averrno = retval;
[1805274]281        return false;
282    }
[9e516d0d]283
[091069f]284    averrno = 0;
[1805274]285    return true;
[6a4cdcb6]286#else
[6e22f11]287    (void)fnm;
288    (void)width;
289    (void)height;
[091069f]290    averrno = MOVIE_NOT_ENABLED;
[6a4cdcb6]291    return false;
292#endif
293}
294
295unsigned char * MovieMaker::GetBuffer() const {
[eac4514]296#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[64d06c0]297    AVCodecContext * c = video_st->codec;
[9e516d0d]298    return pixels + c->height * c->width * 3;
[eac4514]299#else
300    return NULL;
301#endif
[6a4cdcb6]302}
303
304int MovieMaker::GetWidth() const {
[64d06c0]305    assert(video_st);
[cc9e7a06]306#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[64d06c0]307    AVCodecContext *c = video_st->codec;
[6a4cdcb6]308    return c->width;
[1805274]309#else
310    return 0;
311#endif
[6a4cdcb6]312}
313
314int MovieMaker::GetHeight() const {
[64d06c0]315    assert(video_st);
[cc9e7a06]316#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[64d06c0]317    AVCodecContext *c = video_st->codec;
[6a4cdcb6]318    return c->height;
[1805274]319#else
320    return 0;
321#endif
[6a4cdcb6]322}
323
[98fd937]324bool MovieMaker::AddFrame()
[6a4cdcb6]325{
[cc9e7a06]326#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[64d06c0]327    AVCodecContext * c = video_st->codec;
[cc9e7a06]328
329    if (c->pix_fmt != PIX_FMT_YUV420P) {
330        // FIXME convert...
331        abort();
332    }
[1805274]333
[9e516d0d]334    int len = 3 * c->width;
[fed3713]335    {
336        // Flip image vertically
337        int h = c->height;
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        }
[6a4cdcb6]345    }
[9e516d0d]346    sws_scale(sws_ctx, &pixels, &len, 0, c->height, frame->data, frame->linesize);
[6a4cdcb6]347
[cc9e7a06]348    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
349        abort();
350    }
[6a4cdcb6]351
[1805274]352    // Encode this frame.
[64d06c0]353#ifdef HAVE_AVCODEC_ENCODE_VIDEO2
354    AVPacket pkt = { 0 };
355    int got_packet;
356    av_init_packet(&pkt);
357
358    int ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
359    if (ret < 0) {
[98fd937]360        averrno = ret;
361        return false;
[64d06c0]362    }
363    if (got_packet && pkt.size) {
364        // Write the compressed frame to the media file.
365        if (pkt.pts != AV_NOPTS_VALUE) {
366            pkt.pts = av_rescale_q(pkt.pts,
367                                   c->time_base, video_st->time_base);
368        }
369        if (pkt.dts != AV_NOPTS_VALUE) {
370            pkt.dts = av_rescale_q(pkt.dts,
371                                   c->time_base, video_st->time_base);
372        }
373        pkt.stream_index = video_st->index;
374
375        /* Write the compressed frame to the media file. */
[98fd937]376        ret = av_interleaved_write_frame(oc, &pkt);
377        if (ret < 0) {
378            averrno = ret;
379            return false;
[64d06c0]380        }
381    }
382#else
[6a4cdcb6]383    out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, frame);
[1805274]384    // outsize == 0 means that this frame has been buffered, so there's nothing
385    // to write yet.
[cc9e7a06]386    if (out_size) {
[1805274]387        // Write the compressed frame to the media file.
[cc9e7a06]388        AVPacket pkt;
389        av_init_packet(&pkt);
390
[63621a7]391        if (c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
[64d06c0]392            pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
[cc9e7a06]393        if (c->coded_frame->key_frame)
394            pkt.flags |= AV_PKT_FLAG_KEY;
[64d06c0]395        pkt.stream_index = video_st->index;
[cc9e7a06]396        pkt.data = outbuf;
397        pkt.size = out_size;
398
[64d06c0]399        /* Write the compressed frame to the media file. */
[98fd937]400        int ret = av_interleaved_write_frame(oc, &pkt);
401        if (ret < 0) {
402            averrno = ret;
403            return false;
[1805274]404        }
[6a4cdcb6]405    }
406#endif
[64d06c0]407#endif
[98fd937]408    return true;
[6a4cdcb6]409}
410
[98fd937]411bool
412MovieMaker::Close()
[6a4cdcb6]413{
[cc9e7a06]414#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[64d06c0]415    if (video_st && averrno == 0) {
[1805274]416        // No more frames to compress.  The codec may have a few frames
417        // buffered if we're using B frames, so write those too.
[64d06c0]418        AVCodecContext * c = video_st->codec;
[1805274]419
[64d06c0]420#ifdef HAVE_AVCODEC_ENCODE_VIDEO2
421        while (1) {
422            AVPacket pkt = { 0 };
423            int got_packet;
424            av_init_packet(&pkt);
425
426            int ret = avcodec_encode_video2(c, &pkt, NULL, &got_packet);
427            if (ret < 0) {
[98fd937]428                release();
429                averrno = ret;
430                return false;
[64d06c0]431            }
432            if (!got_packet) break;
433            if (!pkt.size) continue;
434
435            // Write the compressed frame to the media file.
436            if (pkt.pts != AV_NOPTS_VALUE) {
437                pkt.pts = av_rescale_q(pkt.pts,
438                                       c->time_base, video_st->time_base);
439            }
440            if (pkt.dts != AV_NOPTS_VALUE) {
441                pkt.dts = av_rescale_q(pkt.dts,
442                                       c->time_base, video_st->time_base);
443            }
444            pkt.stream_index = video_st->index;
445
446            /* Write the compressed frame to the media file. */
[98fd937]447            ret = av_interleaved_write_frame(oc, &pkt);
448            if (ret < 0) {
449                release();
450                averrno = ret;
451                return false;
[64d06c0]452            }
453        }
454#else
[1805274]455        while (out_size) {
456            out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, NULL);
457            if (out_size) {
[cc9e7a06]458                // Write the compressed frame to the media file.
459                AVPacket pkt;
460                av_init_packet(&pkt);
461
[63621a7]462                if (c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
[64d06c0]463                    pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
[cc9e7a06]464                if (c->coded_frame->key_frame)
465                    pkt.flags |= AV_PKT_FLAG_KEY;
[64d06c0]466                pkt.stream_index = video_st->index;
[cc9e7a06]467                pkt.data = outbuf;
468                pkt.size = out_size;
469
470                /* write the compressed frame in the media file */
[98fd937]471                int ret = av_interleaved_write_frame(oc, &pkt);
472                if (ret < 0) {
473                    release();
474                    averrno = ret;
475                    return false;
[1805274]476                }
477            }
[6a4cdcb6]478        }
[64d06c0]479#endif
[6a4cdcb6]480
[cc9e7a06]481        av_write_trailer(oc);
[091069f]482    }
[cc9e7a06]483
[98fd937]484    release();
485#endif
486    return true;
487}
488
489void
490MovieMaker::release()
491{
492#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[64d06c0]493    if (video_st) {
[1805274]494        // Close codec.
[64d06c0]495        avcodec_close(video_st->codec);
[98fd937]496        video_st = NULL;
[6a4cdcb6]497    }
498
[cc9e7a06]499    if (frame) {
[cc69cf5]500        avcodec_free_frame(frame);
[98fd937]501        frame = NULL;
[cc9e7a06]502    }
[6a4cdcb6]503    free(pixels);
[98fd937]504    pixels = NULL;
[64d06c0]505    free(outbuf);
[98fd937]506    outbuf = NULL;
[9e516d0d]507    av_free(sws_ctx);
[98fd937]508    sws_ctx = NULL;
[1805274]509
510    if (oc) {
511        // Free the streams.
[cc9e7a06]512        for (size_t i = 0; i < oc->nb_streams; ++i) {
513            av_freep(&oc->streams[i]->codec);
[1805274]514            av_freep(&oc->streams[i]);
515        }
516
[cc9e7a06]517        if (!(oc->oformat->flags & AVFMT_NOFILE)) {
518            // Close the output file.
[7831cef]519            avio_close(oc->pb);
[cc9e7a06]520        }
[1805274]521
522        // Free the stream.
[6ed625e]523        av_free(oc);
[98fd937]524        oc = NULL;
[1805274]525    }
[6a4cdcb6]526#endif
527}
[091069f]528
[98fd937]529MovieMaker::~MovieMaker()
530{
531    release();
532}
533
[091069f]534const char *
535MovieMaker::get_error_string() const
536{
[eac4514]537#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[091069f]538    switch (averrno) {
[63621a7]539        case AVERROR(EIO):
[091069f]540            return "I/O error";
[63621a7]541        case AVERROR(EDOM):
[091069f]542            return "Number syntax expected in filename";
543        case AVERROR_INVALIDDATA:
544            /* same as AVERROR_UNKNOWN: return "unknown error"; */
545            return "invalid data found";
[63621a7]546        case AVERROR(ENOMEM):
[091069f]547            return "not enough memory";
[63621a7]548        case AVERROR(EILSEQ):
[091069f]549            return "unknown format";
[63621a7]550        case AVERROR(ENOSYS):
[091069f]551            return "Operation not supported";
[63621a7]552        case AVERROR(ENOENT):
[091069f]553            return "No such file or directory";
554        case AVERROR_EOF:
555            return "End of file";
556        case AVERROR_PATCHWELCOME:
557            return "Not implemented in FFmpeg";
558        case 0:
559            return "No error";
560        case MOVIE_NO_SUITABLE_FORMAT:
561            return "Couldn't find a suitable output format";
562        case MOVIE_AUDIO_ONLY:
563            return "Audio-only format specified";
564        case MOVIE_FILENAME_TOO_LONG:
565            return "Filename too long";
566        case MOVIE_NOT_ENABLED:
567            return "Movie export support not included";
568    }
569    return "Unknown error";
[eac4514]570#else
571    return "Movie generation support code not present";
572#endif
[091069f]573}
Note: See TracBrowser for help on using the repository browser.