2 Copyright (C) 2017-2018 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
6 DCP-o-matic is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 DCP-o-matic is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>.
21 #include "ffmpeg_encoder.h"
25 #include "player_video.h"
30 #include "compose.hpp"
36 using std::runtime_error;
39 using boost::shared_ptr;
41 using boost::weak_ptr;
43 int FFmpegFileEncoder::_video_stream_index = 0;
44 int FFmpegFileEncoder::_audio_stream_index = 1;
46 FFmpegFileEncoder::FFmpegFileEncoder (
47 dcp::Size video_frame_size,
54 boost::filesystem::path output
57 , _audio_channels (channels)
59 , _video_frame_size (video_frame_size)
60 , _video_frame_rate (video_frame_rate)
61 , _audio_frame_rate (audio_frame_rate)
65 case EXPORT_FORMAT_PRORES:
66 _pixel_format = AV_PIX_FMT_YUV422P10;
67 _sample_format = AV_SAMPLE_FMT_S16;
68 _video_codec_name = "prores_ks";
69 _audio_codec_name = "pcm_s16le";
70 av_dict_set (&_video_options, "profile", "3", 0);
71 av_dict_set (&_video_options, "threads", "auto", 0);
73 case EXPORT_FORMAT_H264:
74 _pixel_format = AV_PIX_FMT_YUV420P;
75 _sample_format = AV_SAMPLE_FMT_FLTP;
76 _video_codec_name = "libx264";
77 _audio_codec_name = "aac";
78 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
85 avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
86 if (!_format_context) {
87 throw runtime_error ("could not allocate FFmpeg format context");
90 _video_stream = avformat_new_stream (_format_context, _video_codec);
92 throw runtime_error ("could not create FFmpeg output video stream");
95 _audio_stream = avformat_new_stream (_format_context, _audio_codec);
97 throw runtime_error ("could not create FFmpeg output audio stream");
100 _video_stream->id = _video_stream_index;
101 _video_stream->codec = _video_codec_context;
103 _audio_stream->id = _audio_stream_index;
104 _audio_stream->codec = _audio_codec_context;
106 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
107 throw runtime_error ("could not open FFmpeg video codec");
110 int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
113 av_strerror (r, buffer, sizeof(buffer));
114 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
117 if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
118 throw runtime_error ("could not open FFmpeg output file");
121 if (avformat_write_header (_format_context, 0) < 0) {
122 throw runtime_error ("could not write header to FFmpeg output file");
125 _pending_audio.reset (new AudioBuffers(channels, 0));
129 FFmpegFileEncoder::setup_video ()
131 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
133 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
136 _video_codec_context = avcodec_alloc_context3 (_video_codec);
137 if (!_video_codec_context) {
138 throw runtime_error ("could not allocate FFmpeg video context");
141 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
143 /* Variable quantisation */
144 _video_codec_context->global_quality = 0;
145 _video_codec_context->width = _video_frame_size.width;
146 _video_codec_context->height = _video_frame_size.height;
147 _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
148 _video_codec_context->pix_fmt = _pixel_format;
149 _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
153 FFmpegFileEncoder::setup_audio ()
155 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
157 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
160 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
161 if (!_audio_codec_context) {
162 throw runtime_error ("could not allocate FFmpeg audio context");
165 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
167 /* XXX: configurable */
168 _audio_codec_context->bit_rate = 256 * 1024;
169 _audio_codec_context->sample_fmt = _sample_format;
170 _audio_codec_context->sample_rate = _audio_frame_rate;
171 _audio_codec_context->channel_layout = av_get_default_channel_layout (_audio_channels);
172 _audio_codec_context->channels = _audio_channels;
176 FFmpegFileEncoder::flush ()
178 if (_pending_audio->frames() > 0) {
179 audio_frame (_pending_audio->frames ());
182 bool flushed_video = false;
183 bool flushed_audio = false;
185 while (!flushed_video || !flushed_audio) {
187 av_init_packet (&packet);
192 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
194 packet.stream_index = 0;
195 av_interleaved_write_frame (_format_context, &packet);
197 flushed_video = true;
199 av_packet_unref (&packet);
201 av_init_packet (&packet);
205 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
207 packet.stream_index = 0;
208 av_interleaved_write_frame (_format_context, &packet);
210 flushed_audio = true;
212 av_packet_unref (&packet);
215 av_write_trailer (_format_context);
217 avcodec_close (_video_codec_context);
218 avcodec_close (_audio_codec_context);
219 avio_close (_format_context->pb);
220 avformat_free_context (_format_context);
224 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
226 shared_ptr<Image> image = video->image (
227 bind (&PlayerVideo::force, _1, _pixel_format),
232 AVFrame* frame = av_frame_alloc ();
233 DCPOMATIC_ASSERT (frame);
235 _pending_images[image->data()[0]] = image;
236 for (int i = 0; i < 3; ++i) {
237 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
238 frame->buf[i] = av_buffer_ref (buffer);
239 frame->data[i] = buffer->data;
240 frame->linesize[i] = image->stride()[i];
241 av_buffer_unref (&buffer);
244 frame->width = image->size().width;
245 frame->height = image->size().height;
246 frame->format = _pixel_format;
247 frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
250 av_init_packet (&packet);
255 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
256 throw EncodeError ("FFmpeg video encode failed");
259 if (got_packet && packet.size) {
260 packet.stream_index = _video_stream_index;
261 av_interleaved_write_frame (_format_context, &packet);
262 av_packet_unref (&packet);
265 av_frame_free (&frame);
269 /** Called when the player gives us some audio */
271 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
273 _pending_audio->append (audio);
275 int frame_size = _audio_codec_context->frame_size;
276 if (frame_size == 0) {
277 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
278 frame_size = _audio_frame_rate / _video_frame_rate;
281 while (_pending_audio->frames() >= frame_size) {
282 audio_frame (frame_size);
287 FFmpegFileEncoder::audio_frame (int size)
289 DCPOMATIC_ASSERT (size);
291 AVFrame* frame = av_frame_alloc ();
292 DCPOMATIC_ASSERT (frame);
294 int const channels = _pending_audio->channels();
295 DCPOMATIC_ASSERT (channels);
297 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
298 DCPOMATIC_ASSERT (buffer_size >= 0);
300 void* samples = av_malloc (buffer_size);
301 DCPOMATIC_ASSERT (samples);
303 frame->nb_samples = size;
304 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
305 DCPOMATIC_ASSERT (r >= 0);
307 float** p = _pending_audio->data ();
308 switch (_audio_codec_context->sample_fmt) {
309 case AV_SAMPLE_FMT_S16:
311 int16_t* q = reinterpret_cast<int16_t*> (samples);
312 for (int i = 0; i < size; ++i) {
313 for (int j = 0; j < channels; ++j) {
314 *q++ = p[j][i] * 32767;
319 case AV_SAMPLE_FMT_FLTP:
321 float* q = reinterpret_cast<float*> (samples);
322 for (int i = 0; i < channels; ++i) {
323 memcpy (q, p[i], sizeof(float) * size);
329 DCPOMATIC_ASSERT (false);
333 av_init_packet (&packet);
338 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
339 throw EncodeError ("FFmpeg audio encode failed");
342 if (got_packet && packet.size) {
343 packet.stream_index = _audio_stream_index;
344 av_interleaved_write_frame (_format_context, &packet);
345 av_packet_unref (&packet);
349 av_frame_free (&frame);
351 _pending_audio->trim_start (size);
355 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)
361 FFmpegFileEncoder::buffer_free (void* opaque, uint8_t* data)
363 reinterpret_cast<FFmpegFileEncoder*>(opaque)->buffer_free2(data);
367 FFmpegFileEncoder::buffer_free2 (uint8_t* data)
369 _pending_images.erase (data);