source: git/src/moviemaker.cc @ 4b1e5a4

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

Chase the ever shifting libav/ffmpeg API

AVPicture and related functions now deprecated.

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