source: git/src/moviemaker.cc @ d13aea6

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

Use av_malloc()/av_free() instead of malloc()/free()

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