source: git/src/moviemaker.cc @ 242cb07

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

configure.ac,src/moviemaker.cc: Fix to work with libav 10. Reported
by Moritz Muehlenhoff in <http://bugs.debian.org/739332>.

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