source: git/src/moviemaker.cc @ 9e516d0d

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 9e516d0d was 9e516d0d, checked in by Olly Betts <olly@…>, 13 years ago

configure.in,src/moviemaker.cc,src/moviemaker.h: Use libswscale to
convert images to add to the video. Movie export now working
again!

git-svn-id: file:///home/survex-svn/survex/trunk@3619 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 9.7 KB
RevLine 
[6a4cdcb6]1//
2//  moviemaker.cc
3//
4//  Class for writing movies from Aven.
5//
6//  Copyright (C) 2004 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
[ecbc6c18]20//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
[6a4cdcb6]21//
22
[cc9e7a06]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
[6a4cdcb6]49#ifdef HAVE_CONFIG_H
50#include <config.h>
51#endif
52
[cc9e7a06]53#define __STDC_CONSTANT_MACROS
54
[1805274]55#include <assert.h>
[6a4cdcb6]56#include <stdlib.h>
57#include <string.h>
58
59#include "moviemaker.h"
60
[cc9e7a06]61#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
62extern "C" {
63#include "libavformat/avformat.h"
[9e516d0d]64#include "libswscale/swscale.h"
[cc9e7a06]65}
66#ifndef AV_PKT_FLAG_KEY
67# define AV_PKT_FLAG_KEY PKT_FLAG_KEY
68#endif
[6a4cdcb6]69#endif
70
[fe60f41]71// ffmpeg CVS has added av_alloc_format_context() - we're ready for it!
72#define av_alloc_format_context() \
73    ((AVFormatContext*)av_mallocz(sizeof(AVFormatContext)))
74
[1805274]75const int OUTBUF_SIZE = 200000;
[6a4cdcb6]76
[1805274]77MovieMaker::MovieMaker()
[9e516d0d]78    : oc(0), st(0), frame(0), outbuf(0), pixels(0), sws_ctx(0)
[6a4cdcb6]79{
[cc9e7a06]80#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[6a4cdcb6]81    static bool initialised_ffmpeg = false;
[1805274]82    if (initialised_ffmpeg) return;
[6a4cdcb6]83
[1805274]84    // FIXME: register only the codec(s) we want to use...
85    av_register_all();
[6a4cdcb6]86
[1805274]87    initialised_ffmpeg = true;
88#endif
89}
90
91bool MovieMaker::Open(const char *fnm, int width, int height)
92{
[cc9e7a06]93#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[1805274]94    AVOutputFormat * fmt = guess_format(NULL, fnm, NULL);
95    if (!fmt) {
96        // We couldn't deduce the output format from file extension so default
97        // to MPEG.
98        fmt = guess_format("mpeg", NULL, NULL);
99        if (!fmt) {
100            // FIXME : error finding a format...
101            return false;
102        }
103    }
104    if (fmt->video_codec == CODEC_ID_NONE) {
105        // FIXME : The user asked for a format which is audio-only!
106        return false;
[6a4cdcb6]107    }
108
[1805274]109    // Allocate the output media context.
[fe60f41]110    oc = av_alloc_format_context();
[1805274]111    if (!oc) {
112        // FIXME : out of memory
113        return false;
[6a4cdcb6]114    }
[1805274]115    oc->oformat = fmt;
116    if (strlen(fnm) >= sizeof(oc->filename)) {
117        // FIXME : filename too long
118        return false;
119    }
120    strcpy(oc->filename, fnm);
[6a4cdcb6]121
[1805274]122    // Add the video stream using the default format codec.
123    st = av_new_stream(oc, 0);
124    if (!st) {
125        // FIXME : possible errors are "too many streams" (can't be - we only
126        // ask for one) and "out of memory"
127        return false;
[6a4cdcb6]128    }
129
[1805274]130    // Initialise the code.
[cc9e7a06]131    AVCodecContext *c = st->codec;
[1805274]132    c->codec_id = fmt->video_codec;
133    c->codec_type = CODEC_TYPE_VIDEO;
[6a4cdcb6]134
135    // Set sample parameters.
136    c->bit_rate = 400000;
[1805274]137    c->width = width;
138    c->height = height;
[cc9e7a06]139    c->time_base.num = 1;
140    c->time_base.den = 25; // Frames per second.
[1805274]141    c->gop_size = 12; // One intra frame every twelve frames.
[6a4cdcb6]142    c->pix_fmt = PIX_FMT_YUV420P;
[1805274]143    // B frames are backwards predicted - they can improve compression,
144    // but may slow encoding and decoding.
145    // c->max_b_frames = 2;
[6a4cdcb6]146
[cc9e7a06]147    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
148        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
149
[1805274]150    // Set the output parameters (must be done even if no parameters).
151    if (av_set_parameters(oc, NULL) < 0) {
152        // FIXME : return value is an AVERROR_* value - probably
153        // AVERROR_NOMEM or AVERROR_UNKNOWN.
154        return false;
155    }
156
157    // Show the format we've ended up with (for debug purposes).
158    // dump_format(oc, 0, fnm, 1);
159
160    // Open the video codec and allocate the necessary encode buffers.
161    AVCodec * codec = avcodec_find_encoder(c->codec_id);
162    if (!codec) {
163        // FIXME : Erm - internal ffmpeg library problem?
164        return false;
165    }
[6a4cdcb6]166    if (avcodec_open(c, codec) < 0) {
[1805274]167        // FIXME : return value is an AVERROR_* value - probably
168        // AVERROR_NOMEM or AVERROR_UNKNOWN.
169        return false;
[6a4cdcb6]170    }
[1805274]171
[cc9e7a06]172    if ((oc->oformat->flags & AVFMT_RAWPICTURE)) {
173        outbuf = NULL;
174    } else {
175        outbuf = (unsigned char *)malloc(OUTBUF_SIZE);
176        if (!outbuf) {
177            // FIXME : out of memory
178            return false;
179        }
[6a4cdcb6]180    }
[1805274]181
[6a4cdcb6]182    frame = avcodec_alloc_frame();
[cc9e7a06]183    if (!frame) {
[1805274]184        // FIXME : out of memory
185        return false;
[6a4cdcb6]186    }
[cc9e7a06]187    int size = avpicture_get_size(c->pix_fmt, width, height);
[9e516d0d]188    uint8_t * picture_buf = (uint8_t*)av_malloc(size);
189    if (!picture_buf) {
[cc9e7a06]190        av_free(frame);
[1805274]191        // FIXME : out of memory
192        return false;
[6a4cdcb6]193    }
[9e516d0d]194    avpicture_fill((AVPicture *)frame, picture_buf, c->pix_fmt, width, height);
[cc9e7a06]195
196    if (c->pix_fmt != PIX_FMT_YUV420P) {
197        // FIXME need to allocate another frame for this case if we stop
198        // hardcoding PIX_FMT_YUV420P.
199        abort();
200    }
[6a4cdcb6]201
202    pixels = (unsigned char *)malloc(width * height * 6);
203    if (!pixels) {
[1805274]204        // FIXME : out of memory
205        return false;
[6a4cdcb6]206    }
[1805274]207
208    if (url_fopen(&oc->pb, fnm, URL_WRONLY) < 0) {
209        // FIXME : return value is -E* (e.g. -EIO).
210        return false;
211    }
212
213    // Write the stream header, if any.
214    if (av_write_header(oc) < 0) {
215        // FIXME : return value is an AVERROR_* value.
216        return false;
217    }
[9e516d0d]218
219    av_free(sws_ctx);
220    sws_ctx = sws_getContext(width, height, PIX_FMT_RGB24,
221                             width, height, c->pix_fmt, SWS_BICUBIC,
222                             NULL, NULL, NULL);
223    if (sws_ctx == NULL) {
224        fprintf(stderr, "Cannot initialize the conversion context!\n");
225        return false;
226    }
227
[1805274]228    return true;
[6a4cdcb6]229#else
230    return false;
231#endif
232}
233
234unsigned char * MovieMaker::GetBuffer() const {
[9e516d0d]235    AVCodecContext * c = st->codec;
236    return pixels + c->height * c->width * 3;
[6a4cdcb6]237}
238
239int MovieMaker::GetWidth() const {
[1805274]240    assert(st);
[cc9e7a06]241#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
242    AVCodecContext *c = st->codec;
[6a4cdcb6]243    return c->width;
[1805274]244#else
245    return 0;
246#endif
[6a4cdcb6]247}
248
249int MovieMaker::GetHeight() const {
[1805274]250    assert(st);
[cc9e7a06]251#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
252    AVCodecContext *c = st->codec;
[6a4cdcb6]253    return c->height;
[1805274]254#else
255    return 0;
256#endif
[6a4cdcb6]257}
258
259void MovieMaker::AddFrame()
260{
[cc9e7a06]261#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
262    AVCodecContext * c = st->codec;
263
264    if (c->pix_fmt != PIX_FMT_YUV420P) {
265        // FIXME convert...
266        abort();
267    }
[1805274]268
[9e516d0d]269    int len = 3 * c->width;
[6a4cdcb6]270    const int h = c->height;
271    // Flip image vertically
[9e516d0d]272    unsigned char * src = pixels + h * len;
273    unsigned char * dest = src - len;
[6a4cdcb6]274    for (int y = 0; y < h; ++y) {
[9e516d0d]275        memcpy(dest, src, len);
276        src += len;
277        dest -= len;
[6a4cdcb6]278    }
[9e516d0d]279    sws_scale(sws_ctx, &pixels, &len, 0, c->height, frame->data, frame->linesize);
[6a4cdcb6]280
[cc9e7a06]281    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
282        abort();
283    }
[6a4cdcb6]284
[1805274]285    // Encode this frame.
[6a4cdcb6]286    out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, frame);
[1805274]287    // outsize == 0 means that this frame has been buffered, so there's nothing
288    // to write yet.
[cc9e7a06]289    if (out_size) {
[1805274]290        // Write the compressed frame to the media file.
[cc9e7a06]291        AVPacket pkt;
292        av_init_packet(&pkt);
293
294        if (c->coded_frame->pts != AV_NOPTS_VALUE)
295            pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
296        if (c->coded_frame->key_frame)
297            pkt.flags |= AV_PKT_FLAG_KEY;
298        pkt.stream_index = st->index;
299        pkt.data = outbuf;
300        pkt.size = out_size;
301
302        /* write the compressed frame in the media file */
303        if (av_interleaved_write_frame(oc, &pkt) != 0) {
304            abort();
[1805274]305        }
[6a4cdcb6]306    }
307#endif
308}
309
310MovieMaker::~MovieMaker()
311{
[cc9e7a06]312#ifdef HAVE_LIBAVFORMAT_AVFORMAT_H
[1805274]313    if (st) {
314        // No more frames to compress.  The codec may have a few frames
315        // buffered if we're using B frames, so write those too.
[cc9e7a06]316        AVCodecContext * c = st->codec;
[1805274]317
318        while (out_size) {
319            out_size = avcodec_encode_video(c, outbuf, OUTBUF_SIZE, NULL);
320            if (out_size) {
[cc9e7a06]321                // Write the compressed frame to the media file.
322                AVPacket pkt;
323                av_init_packet(&pkt);
324
325                if (c->coded_frame->pts != AV_NOPTS_VALUE)
326                    pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
327                if (c->coded_frame->key_frame)
328                    pkt.flags |= AV_PKT_FLAG_KEY;
329                pkt.stream_index = st->index;
330                pkt.data = outbuf;
331                pkt.size = out_size;
332
333                /* write the compressed frame in the media file */
334                if (av_interleaved_write_frame(oc, &pkt) != 0) {
335                    abort();
[1805274]336                }
337            }
[6a4cdcb6]338        }
339
[cc9e7a06]340        av_write_trailer(oc);
341
[1805274]342        // Close codec.
343        avcodec_close(c);
[6a4cdcb6]344    }
345
[cc9e7a06]346    if (frame) {
347        free(frame->data[0]);
348        free(frame);
349    }
[1805274]350    free(outbuf);
[6a4cdcb6]351    free(pixels);
[9e516d0d]352    av_free(sws_ctx);
[1805274]353
354    if (oc) {
355        // Free the streams.
[cc9e7a06]356        for (size_t i = 0; i < oc->nb_streams; ++i) {
357            av_freep(&oc->streams[i]->codec);
[1805274]358            av_freep(&oc->streams[i]);
359        }
360
[cc9e7a06]361        if (!(oc->oformat->flags & AVFMT_NOFILE)) {
362            // Close the output file.
363            url_fclose(oc->pb);
364        }
[1805274]365
366        // Free the stream.
367        free(oc);
368    }
[6a4cdcb6]369#endif
370}
Note: See TracBrowser for help on using the repository browser.