source: git/src/moviemaker.cc @ 1dfd718

stereo-2025
Last change on this file since 1dfd718 was bf063be, checked in by Olly Betts <olly@…>, 5 months ago

Move word read/write functions to img.c

They are not used anywhere else in the codebase.

Now external users of the img library can benefit from optimised
versions on little-endian machines too.

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