source: git/src/moviemaker.cc @ a72ed95

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since a72ed95 was bc6faa9, checked in by Olly Betts <olly@…>, 10 years ago

src/moviemaker.cc,src/moviemaker.h: Fix warnings from clang.
Reported by Martin Sluka.

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