4 // Class for writing movies from Aven for old FFmpeg
6 // Copyright (C) 2004,2011,2012,2013,2014,2015,2016 Olly Betts
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.
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.
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
23 /* Based on output-example.c:
25 * Libavformat API example: Output a media file in any supported
26 * libavformat format. The default codecs are used.
28 * Copyright (c) 2003 Fabrice Bellard
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:
37 * The above copyright notice and this permission notice shall be included in
38 * all copies or substantial portions of the Software.
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
51 #define __STDC_CONSTANT_MACROS
57 #include "moviemaker.h"
61 # include <libavutil/imgutils.h>
62 # include <libavutil/mathematics.h>
63 # include <libavformat/avformat.h>
64 # include <libswscale/swscale.h>
66 # ifndef AV_PKT_FLAG_KEY
67 # define AV_PKT_FLAG_KEY PKT_FLAG_KEY
69 # ifndef HAVE_AV_GUESS_FORMAT
70 # define av_guess_format guess_format
72 # ifndef HAVE_AVIO_OPEN
73 # define avio_open url_fopen
75 # ifndef HAVE_AVIO_CLOSE
76 # define avio_close url_fclose
78 # ifndef HAVE_AV_FRAME_ALLOC
79 static inline AVFrame
* av_frame_alloc() {
80 return avcodec_alloc_frame();
83 # ifndef HAVE_AV_FRAME_FREE
84 # ifdef HAVE_AVCODEC_FREE_FRAME
85 static inline void av_frame_free(AVFrame
** frame
) {
86 avcodec_free_frame(frame
);
89 static inline void av_frame_free(AVFrame
** frame
) {
90 free((*frame
)->data
[0]);
96 # ifndef HAVE_AVCODEC_OPEN2
97 // We always pass NULL for OPTS below.
98 # define avcodec_open2(CTX, CODEC, OPTS) avcodec_open(CTX, CODEC)
100 # ifndef HAVE_AVFORMAT_NEW_STREAM
101 // We always pass NULL for CODEC below.
102 # define avformat_new_stream(S, CODEC) av_new_stream(S, 0)
104 # if !HAVE_DECL_AVMEDIA_TYPE_VIDEO
105 # define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
107 # if !HAVE_DECL_AV_CODEC_ID_NONE
108 # define AV_CODEC_ID_NONE CODEC_ID_NONE
110 # if !HAVE_DECL_AV_PIX_FMT_RGB24
111 # define AV_PIX_FMT_RGB24 PIX_FMT_RGB24
113 # if !HAVE_DECL_AV_PIX_FMT_YUV420P
114 # define AV_PIX_FMT_YUV420P PIX_FMT_YUV420P
116 # ifndef AVIO_FLAG_WRITE
117 # define AVIO_FLAG_WRITE URL_WRONLY
121 MOVIE_NO_SUITABLE_FORMAT
= 1,
123 MOVIE_FILENAME_TOO_LONG
126 # ifndef HAVE_AVCODEC_ENCODE_VIDEO2
127 const int OUTBUF_SIZE
= 200000;
131 MovieMaker::MovieMaker()
133 : oc(0), video_st(0), frame(0), outbuf(0), pixels(0), sws_ctx(0), averrno(0)
137 static bool initialised_ffmpeg
= false;
138 if (initialised_ffmpeg
) return;
140 // FIXME: register only the codec(s) we want to use...
141 avcodec_register_all();
144 initialised_ffmpeg
= true;
150 write_packet(void *opaque
, uint8_t *buf
, int buf_size
) {
151 FILE * fh
= (FILE*)opaque
;
152 size_t res
= fwrite(buf
, 1, buf_size
, fh
);
153 return res
> 0 ? res
: -1;
157 seek_stream(void *opaque
, int64_t offset
, int whence
) {
158 FILE * fh
= (FILE*)opaque
;
159 return fseek(fh
, offset
, whence
);
163 #define MAX_EXTENSION_LEN 8
165 bool MovieMaker::Open(FILE* fh
, const char * ext
, int width
, int height
)
170 AVOutputFormat
* fmt
= NULL
;
171 char dummy_filename
[MAX_EXTENSION_LEN
+ 3] = "x.";
172 if (strlen(ext
) <= MAX_EXTENSION_LEN
) {
173 strcpy(dummy_filename
+ 2, ext
);
174 // Pass "x." + extension to av_guess_format() to avoid having to deal
175 // with wide character filenames.
176 fmt
= av_guess_format(NULL
, dummy_filename
, NULL
);
179 // We couldn't deduce the output format from file extension so default
181 fmt
= av_guess_format("mpeg", NULL
, NULL
);
183 averrno
= MOVIE_NO_SUITABLE_FORMAT
;
186 strcpy(dummy_filename
+ 2, "mpg");
188 if (fmt
->video_codec
== AV_CODEC_ID_NONE
) {
189 averrno
= MOVIE_AUDIO_ONLY
;
193 /* Allocate the output media context. */
194 oc
= avformat_alloc_context();
196 averrno
= AVERROR(ENOMEM
);
200 strcpy(oc
->filename
, dummy_filename
);
202 /* find the video encoder */
203 AVCodec
*codec
= avcodec_find_encoder(fmt
->video_codec
);
205 // FIXME : Erm - internal ffmpeg library problem?
206 averrno
= AVERROR(ENOMEM
);
210 // Add the video stream.
211 video_st
= avformat_new_stream(oc
, codec
);
213 averrno
= AVERROR(ENOMEM
);
217 // Set sample parameters.
218 AVCodecContext
*c
= video_st
->codec
;
219 c
->bit_rate
= 400000;
220 /* Resolution must be a multiple of two. */
223 /* timebase: This is the fundamental unit of time (in seconds) in terms
224 * of which frame timestamps are represented. For fixed-fps content,
225 * timebase should be 1/framerate and timestamp increments should be
227 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(55, 44, 0)
228 // Old way, which now causes deprecation warnings.
229 c
->time_base
.den
= 25; // Frames per second.
230 c
->time_base
.num
= 1;
232 video_st
->time_base
.den
= 25; // Frames per second.
233 video_st
->time_base
.num
= 1;
234 c
->time_base
= video_st
->time_base
;
236 c
->gop_size
= 12; /* emit one intra frame every twelve frames at most */
237 c
->pix_fmt
= AV_PIX_FMT_YUV420P
;
238 c
->rc_buffer_size
= c
->bit_rate
* 4; // Enough for 4 seconds
239 c
->rc_max_rate
= c
->bit_rate
* 2;
240 // B frames are backwards predicted - they can improve compression,
241 // but may slow encoding and decoding.
242 // if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
243 // c->max_b_frames = 2;
246 /* Some formats want stream headers to be separate. */
247 if (oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
248 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
251 #ifndef HAVE_AVFORMAT_WRITE_HEADER
252 // Set the output parameters (must be done even if no parameters).
253 retval
= av_set_parameters(oc
, NULL
);
260 retval
= avcodec_open2(c
, NULL
, NULL
);
266 #ifndef HAVE_AVCODEC_ENCODE_VIDEO2
268 if (!(oc
->oformat
->flags
& AVFMT_RAWPICTURE
)) {
269 outbuf
= (unsigned char *)av_malloc(OUTBUF_SIZE
);
271 averrno
= AVERROR(ENOMEM
);
277 /* Allocate the encoded raw picture. */
278 frame
= av_frame_alloc();
280 averrno
= AVERROR(ENOMEM
);
283 retval
= av_image_alloc(frame
->data
, frame
->linesize
,
284 c
->width
, c
->height
, c
->pix_fmt
, 1);
290 if (c
->pix_fmt
!= AV_PIX_FMT_YUV420P
) {
291 // FIXME need to allocate another frame for this case if we stop
292 // hardcoding AV_PIX_FMT_YUV420P.
296 frame
->format
= c
->pix_fmt
;
297 frame
->width
= c
->width
;
298 frame
->height
= c
->height
;
300 pixels
= (unsigned char *)av_malloc(width
* height
* 6);
302 averrno
= AVERROR(ENOMEM
);
306 // Show the format we've ended up with (for debug purposes).
307 // av_dump_format(oc, 0, fnm, 1);
310 sws_ctx
= sws_getContext(width
, height
, AV_PIX_FMT_RGB24
,
311 width
, height
, c
->pix_fmt
, SWS_BICUBIC
,
313 if (sws_ctx
== NULL
) {
314 fprintf(stderr
, "Cannot initialize the conversion context!\n");
315 averrno
= AVERROR(ENOMEM
);
319 if (!(fmt
->flags
& AVFMT_NOFILE
)) {
320 const int buf_size
= 8192;
321 void * buf
= av_malloc(buf_size
);
322 oc
->pb
= avio_alloc_context(static_cast<uint8_t*>(buf
), buf_size
, 1,
323 fh
, NULL
, write_packet
, seek_stream
);
325 averrno
= AVERROR(ENOMEM
);
330 // Write the stream header, if any.
331 #ifdef HAVE_AVFORMAT_WRITE_HEADER
332 retval
= avformat_write_header(oc
, NULL
);
334 retval
= av_write_header(oc
);
352 unsigned char * MovieMaker::GetBuffer() const {
354 return pixels
+ GetWidth() * GetHeight() * 3;
360 int MovieMaker::GetWidth() const {
363 AVCodecContext
*c
= video_st
->codec
;
370 int MovieMaker::GetHeight() const {
373 AVCodecContext
*c
= video_st
->codec
;
380 bool MovieMaker::AddFrame()
383 AVCodecContext
* c
= video_st
->codec
;
385 if (c
->pix_fmt
!= AV_PIX_FMT_YUV420P
) {
390 int len
= 3 * c
->width
;
392 // Flip image vertically
394 unsigned char * src
= pixels
+ h
* len
;
395 unsigned char * dest
= src
- len
;
397 memcpy(dest
, src
, len
);
402 sws_scale(sws_ctx
, &pixels
, &len
, 0, c
->height
, frame
->data
, frame
->linesize
);
404 if (oc
->oformat
->flags
& AVFMT_RAWPICTURE
) {
408 // Encode this frame.
409 #ifdef HAVE_AVCODEC_ENCODE_VIDEO2
412 av_init_packet(&pkt
);
415 int ret
= avcodec_encode_video2(c
, &pkt
, frame
, &got_packet
);
420 if (got_packet
&& pkt
.size
) {
421 // Write the compressed frame to the media file.
422 if (pkt
.pts
!= int64_t(AV_NOPTS_VALUE
)) {
423 pkt
.pts
= av_rescale_q(pkt
.pts
,
424 c
->time_base
, video_st
->time_base
);
426 if (pkt
.dts
!= int64_t(AV_NOPTS_VALUE
)) {
427 pkt
.dts
= av_rescale_q(pkt
.dts
,
428 c
->time_base
, video_st
->time_base
);
430 pkt
.stream_index
= video_st
->index
;
432 /* Write the compressed frame to the media file. */
433 ret
= av_interleaved_write_frame(oc
, &pkt
);
440 out_size
= avcodec_encode_video(c
, outbuf
, OUTBUF_SIZE
, frame
);
441 // outsize == 0 means that this frame has been buffered, so there's nothing
444 // Write the compressed frame to the media file.
446 av_init_packet(&pkt
);
448 if (c
->coded_frame
->pts
!= (int64_t)AV_NOPTS_VALUE
)
449 pkt
.pts
= av_rescale_q(c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
450 if (c
->coded_frame
->key_frame
)
451 pkt
.flags
|= AV_PKT_FLAG_KEY
;
452 pkt
.stream_index
= video_st
->index
;
456 /* Write the compressed frame to the media file. */
457 int ret
= av_interleaved_write_frame(oc
, &pkt
);
472 if (video_st
&& averrno
== 0) {
473 // No more frames to compress. The codec may have a few frames
474 // buffered if we're using B frames, so write those too.
475 AVCodecContext
* c
= video_st
->codec
;
477 #ifdef HAVE_AVCODEC_ENCODE_VIDEO2
481 av_init_packet(&pkt
);
485 int ret
= avcodec_encode_video2(c
, &pkt
, NULL
, &got_packet
);
491 if (!got_packet
) break;
492 if (!pkt
.size
) continue;
494 // Write the compressed frame to the media file.
495 if (pkt
.pts
!= int64_t(AV_NOPTS_VALUE
)) {
496 pkt
.pts
= av_rescale_q(pkt
.pts
,
497 c
->time_base
, video_st
->time_base
);
499 if (pkt
.dts
!= int64_t(AV_NOPTS_VALUE
)) {
500 pkt
.dts
= av_rescale_q(pkt
.dts
,
501 c
->time_base
, video_st
->time_base
);
503 pkt
.stream_index
= video_st
->index
;
505 /* Write the compressed frame to the media file. */
506 ret
= av_interleaved_write_frame(oc
, &pkt
);
515 out_size
= avcodec_encode_video(c
, outbuf
, OUTBUF_SIZE
, NULL
);
517 // Write the compressed frame to the media file.
519 av_init_packet(&pkt
);
521 if (c
->coded_frame
->pts
!= (int64_t)AV_NOPTS_VALUE
)
522 pkt
.pts
= av_rescale_q(c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
523 if (c
->coded_frame
->key_frame
)
524 pkt
.flags
|= AV_PKT_FLAG_KEY
;
525 pkt
.stream_index
= video_st
->index
;
529 /* write the compressed frame in the media file */
530 int ret
= av_interleaved_write_frame(oc
, &pkt
);
540 av_write_trailer(oc
);
550 MovieMaker::release()
554 avcodec_close(video_st
->codec
);
559 av_frame_free(&frame
);
570 for (size_t i
= 0; i
< oc
->nb_streams
; ++i
) {
571 av_freep(&oc
->streams
[i
]->codec
);
572 av_freep(&oc
->streams
[i
]);
575 if (!(oc
->oformat
->flags
& AVFMT_NOFILE
)) {
576 // Release the AVIOContext.
591 MovieMaker::~MovieMaker()
599 MovieMaker::get_error_string() const
606 return "Number syntax expected in filename";
607 case AVERROR_INVALIDDATA
:
608 /* same as AVERROR_UNKNOWN: return "unknown error"; */
609 return "invalid data found";
610 case AVERROR(ENOMEM
):
611 return "not enough memory";
612 case AVERROR(EILSEQ
):
613 return "unknown format";
614 case AVERROR(ENOSYS
):
615 return "Operation not supported";
616 case AVERROR(ENOENT
):
617 return "No such file or directory";
619 return "End of file";
620 case AVERROR_PATCHWELCOME
:
621 return "Not implemented in FFmpeg";
624 case MOVIE_NO_SUITABLE_FORMAT
:
625 return "Couldn't find a suitable output format";
626 case MOVIE_AUDIO_ONLY
:
627 return "Audio-only format specified";
628 case MOVIE_FILENAME_TOO_LONG
:
629 return "Filename too long";
632 return "Unknown error";