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

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
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
Line 
1//
2//  moviemaker.cc
3//
4//  Class for writing movies from Aven.
5//
6//  Copyright (C) 2004,2011,2012,2013 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 <libavutil/mathematics.h>
64# include <libavformat/avformat.h>
65# include <libswscale/swscale.h>
66}
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
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
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
93# if !HAVE_DECL_AVMEDIA_TYPE_VIDEO
94#  define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
95# endif
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
105#endif
106
107enum {
108    MOVIE_NO_SUITABLE_FORMAT = 1,
109    MOVIE_AUDIO_ONLY,
110    MOVIE_FILENAME_TOO_LONG,
111    MOVIE_NOT_ENABLED
112};
113
114const int OUTBUF_SIZE = 200000;
115
116MovieMaker::MovieMaker()
117    : oc(0), video_st(0), frame(0), outbuf(0), pixels(0), sws_ctx(0), averrno(0)
118{
119#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
120    static bool initialised_ffmpeg = false;
121    if (initialised_ffmpeg) return;
122
123    // FIXME: register only the codec(s) we want to use...
124    avcodec_register_all();
125    av_register_all();
126
127    initialised_ffmpeg = true;
128#endif
129}
130
131bool MovieMaker::Open(const char *fnm, int width, int height)
132{
133#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
134    AVOutputFormat * fmt = av_guess_format(NULL, fnm, NULL);
135    if (!fmt) {
136        // We couldn't deduce the output format from file extension so default
137        // to MPEG.
138        fmt = av_guess_format("mpeg", NULL, NULL);
139        if (!fmt) {
140            averrno = MOVIE_NO_SUITABLE_FORMAT;
141            return false;
142        }
143    }
144    if (fmt->video_codec == AVCODEC_ID_NONE) {
145        averrno = MOVIE_AUDIO_ONLY;
146        return false;
147    }
148
149    /* Allocate the output media context. */
150    oc = avformat_alloc_context();
151    if (!oc) {
152        averrno = AVERROR(ENOMEM);
153        return false;
154    }
155    oc->oformat = fmt;
156    if (strlen(fnm) >= sizeof(oc->filename)) {
157        averrno = MOVIE_FILENAME_TOO_LONG;
158        return false;
159    }
160    strcpy(oc->filename, fnm);
161
162    /* find the video encoder */
163    AVCodec *codec = avcodec_find_encoder(fmt->video_codec);
164    if (!codec) {
165        // FIXME : Erm - internal ffmpeg library problem?
166        averrno = AVERROR(ENOMEM);
167        return false;
168    }
169
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    }
176
177    // Set sample parameters.
178    AVCodecContext *c = video_st->codec;
179    c->bit_rate = 400000;
180    /* Resolution must be a multiple of two. */
181    c->width = width;
182    c->height = height;
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. */
187    c->time_base.den = 25; // Frames per second.
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;
191    // B frames are backwards predicted - they can improve compression,
192    // but may slow encoding and decoding.
193    // if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
194    //     c->max_b_frames = 2;
195    // }
196
197    /* Some formats want stream headers to be separate. */
198    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
199        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
200
201    int retval;
202#ifndef HAVE_AVFORMAT_WRITE_HEADER
203    // Set the output parameters (must be done even if no parameters).
204    retval = av_set_parameters(oc, NULL);
205    if (retval < 0) {
206        averrno = retval;
207        return false;
208    }
209#endif
210
211    retval = avcodec_open2(c, NULL, NULL);
212    if (retval < 0) {
213        averrno = retval;
214        return false;
215    }
216
217#ifndef HAVE_AVCODEC_ENCODE_VIDEO2
218    outbuf = NULL;
219    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
220        outbuf = (unsigned char *)malloc(OUTBUF_SIZE);
221        if (!outbuf) {
222            averrno = AVERROR(ENOMEM);
223            return false;
224        }
225    }
226#endif
227
228    /* Allocate the encoded raw picture. */
229    frame = avcodec_alloc_frame();
230    if (!frame) {
231        averrno = AVERROR(ENOMEM);
232        return false;
233    }
234    retval = avpicture_alloc((AVPicture *)frame, c->pix_fmt, c->width, c->height);
235    if (retval < 0) {
236        averrno = retval;
237        return false;
238    }
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    }
245
246    pixels = (unsigned char *)malloc(width * height * 6);
247    if (!pixels) {
248        averrno = AVERROR(ENOMEM);
249        return false;
250    }
251
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);
262        return false;
263    }
264
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
273    // Write the stream header, if any.
274#ifdef HAVE_AVFORMAT_WRITE_HEADER
275    retval = avformat_write_header(oc, NULL);
276#else
277    retval = av_write_header(oc);
278#endif
279    if (retval < 0) {
280        averrno = retval;
281        return false;
282    }
283
284    averrno = 0;
285    return true;
286#else
287    (void)fnm;
288    (void)width;
289    (void)height;
290    averrno = MOVIE_NOT_ENABLED;
291    return false;
292#endif
293}
294
295unsigned char * MovieMaker::GetBuffer() const {
296#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
297    AVCodecContext * c = video_st->codec;
298    return pixels + c->height * c->width * 3;
299#else
300    return NULL;
301#endif
302}
303
304int MovieMaker::GetWidth() const {
305    assert(video_st);
306#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
307    AVCodecContext *c = video_st->codec;
308    return c->width;
309#else
310    return 0;
311#endif
312}
313
314int MovieMaker::GetHeight() const {
315    assert(video_st);
316#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
317    AVCodecContext *c = video_st->codec;
318    return c->height;
319#else
320    return 0;
321#endif
322}
323
324bool MovieMaker::AddFrame()
325{
326#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
327    AVCodecContext * c = video_st->codec;
328
329    if (c->pix_fmt != PIX_FMT_YUV420P) {
330        // FIXME convert...
331        abort();
332    }
333
334    int len = 3 * c->width;
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        }
345    }
346    sws_scale(sws_ctx, &pixels, &len, 0, c->height, frame->data, frame->linesize);
347
348    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
349        abort();
350    }
351
352    // Encode this frame.
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) {
360        averrno = ret;
361        return false;
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. */
376        ret = av_interleaved_write_frame(oc, &pkt);
377        if (ret < 0) {
378            averrno = ret;
379            return false;
380        }
381    }
382#else
383    out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, frame);
384    // outsize == 0 means that this frame has been buffered, so there's nothing
385    // to write yet.
386    if (out_size) {
387        // Write the compressed frame to the media file.
388        AVPacket pkt;
389        av_init_packet(&pkt);
390
391        if (c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
392            pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
393        if (c->coded_frame->key_frame)
394            pkt.flags |= AV_PKT_FLAG_KEY;
395        pkt.stream_index = video_st->index;
396        pkt.data = outbuf;
397        pkt.size = out_size;
398
399        /* Write the compressed frame to the media file. */
400        int ret = av_interleaved_write_frame(oc, &pkt);
401        if (ret < 0) {
402            averrno = ret;
403            return false;
404        }
405    }
406#endif
407#endif
408    return true;
409}
410
411bool
412MovieMaker::Close()
413{
414#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
415    if (video_st && averrno == 0) {
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.
418        AVCodecContext * c = video_st->codec;
419
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) {
428                release();
429                averrno = ret;
430                return false;
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. */
447            ret = av_interleaved_write_frame(oc, &pkt);
448            if (ret < 0) {
449                release();
450                averrno = ret;
451                return false;
452            }
453        }
454#else
455        while (out_size) {
456            out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, NULL);
457            if (out_size) {
458                // Write the compressed frame to the media file.
459                AVPacket pkt;
460                av_init_packet(&pkt);
461
462                if (c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
463                    pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
464                if (c->coded_frame->key_frame)
465                    pkt.flags |= AV_PKT_FLAG_KEY;
466                pkt.stream_index = video_st->index;
467                pkt.data = outbuf;
468                pkt.size = out_size;
469
470                /* write the compressed frame in the media file */
471                int ret = av_interleaved_write_frame(oc, &pkt);
472                if (ret < 0) {
473                    release();
474                    averrno = ret;
475                    return false;
476                }
477            }
478        }
479#endif
480
481        av_write_trailer(oc);
482    }
483
484    release();
485#endif
486    return true;
487}
488
489void
490MovieMaker::release()
491{
492#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
493    if (video_st) {
494        // Close codec.
495        avcodec_close(video_st->codec);
496        video_st = NULL;
497    }
498
499    if (frame) {
500        avcodec_free_frame(frame);
501        frame = NULL;
502    }
503    free(pixels);
504    pixels = NULL;
505    free(outbuf);
506    outbuf = NULL;
507    av_free(sws_ctx);
508    sws_ctx = NULL;
509
510    if (oc) {
511        // Free the streams.
512        for (size_t i = 0; i < oc->nb_streams; ++i) {
513            av_freep(&oc->streams[i]->codec);
514            av_freep(&oc->streams[i]);
515        }
516
517        if (!(oc->oformat->flags & AVFMT_NOFILE)) {
518            // Close the output file.
519            avio_close(oc->pb);
520        }
521
522        // Free the stream.
523        av_free(oc);
524        oc = NULL;
525    }
526#endif
527}
528
529MovieMaker::~MovieMaker()
530{
531    release();
532}
533
534const char *
535MovieMaker::get_error_string() const
536{
537#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
538    switch (averrno) {
539        case AVERROR(EIO):
540            return "I/O error";
541        case AVERROR(EDOM):
542            return "Number syntax expected in filename";
543        case AVERROR_INVALIDDATA:
544            /* same as AVERROR_UNKNOWN: return "unknown error"; */
545            return "invalid data found";
546        case AVERROR(ENOMEM):
547            return "not enough memory";
548        case AVERROR(EILSEQ):
549            return "unknown format";
550        case AVERROR(ENOSYS):
551            return "Operation not supported";
552        case AVERROR(ENOENT):
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";
570#else
571    return "Movie generation support code not present";
572#endif
573}
Note: See TracBrowser for help on using the repository browser.