source: git/src/moviemaker.cc @ 92cfa6ee

stereo-2025
Last change on this file since 92cfa6ee was a3f83057, checked in by Olly Betts <olly@…>, 7 months ago

Use C++11 member initialisation where sensible

  • Property mode set to 100644
File size: 10.9 KB
Line 
1//
2//  moviemaker.cc
3//
4//  Class for writing movies from Aven.
5//
6//  Copyright (C) 2004-2024 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#include <config.h>
50
51#define __STDC_CONSTANT_MACROS
52
53#include <assert.h>
54#include <stdlib.h>
55#include <string.h>
56
57#include "moviemaker.h"
58
59#ifdef WITH_FFMPEG
60extern "C" {
61# include <libavcodec/avcodec.h>
62# include <libavutil/imgutils.h>
63# include <libavutil/mathematics.h>
64# include <libavformat/avformat.h>
65# include <libswscale/swscale.h>
66}
67#endif
68
69// Handle the "no FFmpeg" case in this file.
70#if !defined WITH_FFMPEG || LIBAVCODEC_VERSION_MAJOR >= 57
71
72#ifdef WITH_FFMPEG
73enum {
74    MOVIE_NO_SUITABLE_FORMAT = 1,
75    MOVIE_AUDIO_ONLY,
76    MOVIE_FILENAME_TOO_LONG
77};
78#endif
79
80MovieMaker::MovieMaker()
81{
82#ifdef WITH_FFMPEG
83    static bool initialised_ffmpeg = false;
84    if (initialised_ffmpeg) return;
85
86#if LIBAVCODEC_VERSION_MAJOR < 58
87    avcodec_register_all();
88    av_register_all();
89#endif
90
91    initialised_ffmpeg = true;
92#endif
93}
94
95#ifdef WITH_FFMPEG
96static int
97write_packet(void *opaque,
98#if LIBAVFORMAT_VERSION_MAJOR < 61
99             uint8_t *buf,
100#else
101             const uint8_t *buf,
102#endif
103             int buf_size)
104{
105    FILE * fh = (FILE*)opaque;
106    size_t res = fwrite(buf, 1, buf_size, fh);
107    return res > 0 ? res : -1;
108}
109
110static int64_t
111seek_stream(void *opaque, int64_t offset, int whence) {
112    FILE * fh = (FILE*)opaque;
113    return fseek(fh, offset, whence);
114}
115#endif
116
117#define MAX_EXTENSION_LEN 8
118
119bool MovieMaker::Open(FILE* fh, const char * ext, int width, int height)
120{
121#ifdef WITH_FFMPEG
122    fh_to_close = fh;
123
124    /* Allocate the output media context. */
125    char dummy_filename[MAX_EXTENSION_LEN + 3] = "x.";
126    oc = NULL;
127    if (strlen(ext) <= MAX_EXTENSION_LEN) {
128        // Use "x." + extension for format detection to avoid having to deal
129        // with wide character filenames.
130        strcpy(dummy_filename + 2, ext);
131        avformat_alloc_output_context2(&oc, NULL, NULL, dummy_filename);
132    }
133    if (!oc) {
134        averrno = MOVIE_NO_SUITABLE_FORMAT;
135        return false;
136    }
137
138    auto fmt = oc->oformat;
139    if (fmt->video_codec == AV_CODEC_ID_NONE) {
140        averrno = MOVIE_AUDIO_ONLY;
141        return false;
142    }
143
144    /* find the video encoder */
145    auto codec = avcodec_find_encoder(fmt->video_codec);
146    if (!codec) {
147        // FIXME : Erm - internal ffmpeg library problem?
148        averrno = AVERROR(ENOMEM);
149        return false;
150    }
151
152    // Add the video stream.
153    video_st = avformat_new_stream(oc, NULL);
154    if (!video_st) {
155        averrno = AVERROR(ENOMEM);
156        return false;
157    }
158
159    context = avcodec_alloc_context3(codec);
160    context->codec_id = fmt->video_codec;
161    context->width = width;
162    context->height = height;
163    video_st->time_base.den = 25; // Frames per second.
164    video_st->time_base.num = 1;
165    context->time_base = video_st->time_base;
166    context->bit_rate = width * height * (4 * 0.07) * context->time_base.den / context->time_base.num;
167    context->bit_rate_tolerance = context->bit_rate;
168    context->global_quality = 4;
169    context->rc_buffer_size = 2 * 1024 * 1024;
170    context->rc_max_rate = context->bit_rate * 8;
171    context->gop_size = 50; /* Twice the framerate */
172    context->pix_fmt = AV_PIX_FMT_YUV420P;
173    if (context->has_b_frames) {
174        // B frames are backwards predicted - they can improve compression,
175        // but may slow encoding and decoding.
176        context->max_b_frames = 4;
177    }
178
179    /* Some formats want stream headers to be separate. */
180    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
181        context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
182
183    int retval;
184    retval = avcodec_open2(context, codec, NULL);
185    if (retval < 0) {
186        averrno = retval;
187        return false;
188    }
189
190    /* Allocate the encoded raw picture. */
191    frame = av_frame_alloc();
192    if (!frame) {
193        averrno = AVERROR(ENOMEM);
194        return false;
195    }
196
197    frame->format = context->pix_fmt;
198    frame->width = width;
199    frame->height = height;
200    frame->pts = 0;
201
202    retval = av_frame_get_buffer(frame, 32);
203    if (retval < 0) {
204        averrno = retval;
205        return false;
206    }
207
208    if (frame->format != AV_PIX_FMT_YUV420P) {
209        // FIXME need to allocate another frame for this case if we stop
210        // hardcoding AV_PIX_FMT_YUV420P.
211        abort();
212    }
213
214    /* copy the stream parameters to the muxer */
215    retval = avcodec_parameters_from_context(video_st->codecpar, context);
216    if (retval < 0) {
217        averrno = retval;
218        return false;
219    }
220
221    pixels = (unsigned char *)av_malloc(width * height * 6);
222    if (!pixels) {
223        averrno = AVERROR(ENOMEM);
224        return false;
225    }
226
227    // Show the format we've ended up with (for debug purposes).
228    // av_dump_format(oc, 0, dummy_filename, 1);
229
230    av_free(sws_ctx);
231    sws_ctx = sws_getContext(width, height, AV_PIX_FMT_RGB24,
232                             width, height, context->pix_fmt, SWS_BICUBIC,
233                             NULL, NULL, NULL);
234    if (sws_ctx == NULL) {
235        fprintf(stderr, "Cannot initialize the conversion context!\n");
236        averrno = AVERROR(ENOMEM);
237        return false;
238    }
239
240    if (!(fmt->flags & AVFMT_NOFILE)) {
241        const int buf_size = 8192;
242        void * buf = av_malloc(buf_size);
243        oc->pb = avio_alloc_context(static_cast<uint8_t*>(buf), buf_size, 1,
244                                    fh, NULL, write_packet, seek_stream);
245        if (!oc->pb) {
246            averrno = AVERROR(ENOMEM);
247            return false;
248        }
249    }
250
251    // Write the stream header, if any.
252    retval = avformat_write_header(oc, NULL);
253    if (retval < 0) {
254        averrno = retval;
255        return false;
256    }
257
258    averrno = 0;
259    return true;
260#else
261    (void)fh;
262    (void)ext;
263    (void)width;
264    (void)height;
265    return false;
266#endif
267}
268
269unsigned char * MovieMaker::GetBuffer() const {
270#ifdef WITH_FFMPEG
271    return pixels + GetWidth() * GetHeight() * 3;
272#else
273    return NULL;
274#endif
275}
276
277int MovieMaker::GetWidth() const {
278#ifdef WITH_FFMPEG
279    assert(video_st);
280    return video_st->codecpar->width;
281#else
282    return 0;
283#endif
284}
285
286int MovieMaker::GetHeight() const {
287#ifdef WITH_FFMPEG
288    assert(video_st);
289    return video_st->codecpar->height;
290#else
291    return 0;
292#endif
293}
294
295#ifdef WITH_FFMPEG
296// Call with frame=NULL when done.
297int
298MovieMaker::encode_frame(AVFrame* frame_or_null)
299{
300    int ret = avcodec_send_frame(context, frame_or_null);
301    if (ret < 0) return ret;
302
303    AVPacket *pkt = av_packet_alloc();
304    pkt->size = 0;
305    while ((ret = avcodec_receive_packet(context, pkt)) == 0) {
306        // Rescale output packet timestamp values from codec to stream timebase.
307        av_packet_rescale_ts(pkt, context->time_base, video_st->time_base);
308        pkt->stream_index = video_st->index;
309
310        // Write the compressed frame to the media file.
311        ret = av_interleaved_write_frame(oc, pkt);
312        if (ret < 0) {
313            av_packet_free(&pkt);
314            release();
315            return ret;
316        }
317    }
318    av_packet_free(&pkt);
319    return 0;
320}
321#endif
322
323bool MovieMaker::AddFrame()
324{
325#ifdef WITH_FFMPEG
326    int ret = av_frame_make_writable(frame);
327    if (ret < 0) {
328        averrno = ret;
329        return false;
330    }
331
332    enum AVPixelFormat pix_fmt = context->pix_fmt;
333
334    if (pix_fmt != AV_PIX_FMT_YUV420P) {
335        // FIXME convert...
336        abort();
337    }
338
339    int len = 3 * GetWidth();
340    {
341        // Flip image vertically
342        int h = GetHeight();
343        unsigned char * src = pixels + h * len;
344        unsigned char * dest = src - len;
345        while (h--) {
346            memcpy(dest, src, len);
347            src += len;
348            dest -= len;
349        }
350    }
351    sws_scale(sws_ctx, &pixels, &len, 0, GetHeight(),
352              frame->data, frame->linesize);
353
354    ++frame->pts;
355
356    // Encode this frame.
357    ret = encode_frame(frame);
358    if (ret < 0) {
359        averrno = ret;
360        return false;
361    }
362#endif
363    return true;
364}
365
366bool
367MovieMaker::Close()
368{
369#ifdef WITH_FFMPEG
370    if (video_st && averrno == 0) {
371        // Flush out any remaining data.
372        int ret = encode_frame(NULL);
373        if (ret < 0) {
374            averrno = ret;
375            return false;
376        }
377        av_write_trailer(oc);
378    }
379
380    release();
381#endif
382    return true;
383}
384
385#ifdef WITH_FFMPEG
386void
387MovieMaker::release()
388{
389    // Close codec.
390    avcodec_free_context(&context);
391    av_frame_free(&frame);
392    av_free(pixels);
393    pixels = NULL;
394    sws_freeContext(sws_ctx);
395    sws_ctx = NULL;
396
397    // Free the stream.
398    avformat_free_context(oc);
399    oc = NULL;
400
401    if (fh_to_close) {
402        fclose(fh_to_close);
403        fh_to_close = NULL;
404    }
405}
406#endif
407
408MovieMaker::~MovieMaker()
409{
410#ifdef WITH_FFMPEG
411    release();
412#endif
413}
414
415const char *
416MovieMaker::get_error_string() const
417{
418#ifdef WITH_FFMPEG
419    switch (averrno) {
420        case AVERROR(EIO):
421            return "I/O error";
422        case AVERROR(EDOM):
423            return "Number syntax expected in filename";
424        case AVERROR_INVALIDDATA:
425            /* same as AVERROR_UNKNOWN: return "unknown error"; */
426            return "invalid data found";
427        case AVERROR(ENOMEM):
428            return "not enough memory";
429        case AVERROR(EILSEQ):
430            return "unknown format";
431        case AVERROR(ENOSYS):
432            return "Operation not supported";
433        case AVERROR(ENOENT):
434            return "No such file or directory";
435        case AVERROR_EOF:
436            return "End of file";
437        case AVERROR_PATCHWELCOME:
438            return "Not implemented in FFmpeg";
439        case 0:
440            return "No error";
441        case MOVIE_NO_SUITABLE_FORMAT:
442            return "Couldn't find a suitable output format";
443        case MOVIE_AUDIO_ONLY:
444            return "Audio-only format specified";
445        case MOVIE_FILENAME_TOO_LONG:
446            return "Filename too long";
447    }
448#endif
449    return "Unknown error";
450}
451
452#else
453
454#include "moviemaker-legacy.cc"
455
456#endif
Note: See TracBrowser for help on using the repository browser.