source: git/src/moviemaker.cc @ 73f170d

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 73f170d was ad04c87, checked in by Olly Betts <olly@…>, 10 years ago

Fix to compile with FFmpeg 2.9

Reported by Andreas Cadhalpun in https://bugs.debian.org/803863

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