source: git/src/moviemaker.cc @ df3e1a0c

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since df3e1a0c was f4e4b56, checked in by Olly Betts <olly@…>, 9 years ago

Fix movie export to Unicode out path on wxMSW

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