source: git/src/moviemaker.cc @ ccb83b7

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

lib/,src/: Make all uses of unit names translatable.

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