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"
29 #include "compose.hpp"
35 using std::runtime_error;
38 using boost::shared_ptr;
40 using boost::weak_ptr;
41 using boost::optional;
42 using namespace dcpomatic;
44 int FFmpegFileEncoder::_video_stream_index = 0;
45 int FFmpegFileEncoder::_audio_stream_index = 1;
47 FFmpegFileEncoder::FFmpegFileEncoder (
48 dcp::Size video_frame_size,
54 boost::filesystem::path output
55 #ifdef DCPOMATIC_VARIANT_SWAROOP
56 , optional<dcp::Key> key
61 , _audio_channels (channels)
63 , _video_frame_size (video_frame_size)
64 , _video_frame_rate (video_frame_rate)
65 , _audio_frame_rate (audio_frame_rate)
68 _pixel_format = pixel_format (format);
71 case EXPORT_FORMAT_PRORES:
72 _sample_format = AV_SAMPLE_FMT_S16;
73 _video_codec_name = "prores_ks";
74 _audio_codec_name = "pcm_s16le";
75 av_dict_set (&_video_options, "profile", "3", 0);
76 av_dict_set (&_video_options, "threads", "auto", 0);
78 case EXPORT_FORMAT_H264_AAC:
79 _sample_format = AV_SAMPLE_FMT_FLTP;
80 _video_codec_name = "libx264";
81 _audio_codec_name = "aac";
82 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
84 case EXPORT_FORMAT_H264_PCM:
85 _sample_format = AV_SAMPLE_FMT_S32;
86 _video_codec_name = "libx264";
87 _audio_codec_name = "pcm_s24le";
88 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
91 DCPOMATIC_ASSERT (false);
97 #ifdef DCPOMATIC_VARIANT_SWAROOP
98 int r = avformat_alloc_output_context2 (&_format_context, av_guess_format("mov", 0, 0), 0, 0);
100 int r = avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
102 if (!_format_context) {
103 throw runtime_error (String::compose("could not allocate FFmpeg format context (%1)", r));
106 _video_stream = avformat_new_stream (_format_context, _video_codec);
107 if (!_video_stream) {
108 throw runtime_error ("could not create FFmpeg output video stream");
111 _audio_stream = avformat_new_stream (_format_context, _audio_codec);
112 if (!_audio_stream) {
113 throw runtime_error ("could not create FFmpeg output audio stream");
116 DCPOMATIC_DISABLE_WARNINGS
117 _video_stream->id = _video_stream_index;
118 _video_stream->codec = _video_codec_context;
120 _audio_stream->id = _audio_stream_index;
121 _audio_stream->codec = _audio_codec_context;
122 DCPOMATIC_ENABLE_WARNINGS
124 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
125 throw runtime_error ("could not open FFmpeg video codec");
128 r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
131 av_strerror (r, buffer, sizeof(buffer));
132 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
135 r = avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE);
137 throw runtime_error (String::compose("could not open FFmpeg output file %1 (%2)", _output.string(), r));
140 AVDictionary* options = 0;
142 #ifdef DCPOMATIC_VARIANT_SWAROOP
144 av_dict_set (&options, "encryption_key", key->hex().c_str(), 0);
145 /* XXX: is this OK? */
146 av_dict_set (&options, "encryption_kid", "00000000000000000000000000000000", 0);
147 av_dict_set (&options, "encryption_scheme", "cenc-aes-ctr", 0);
151 if (av_dict_set(&_format_context->metadata, SWAROOP_ID_TAG, id->c_str(), 0) < 0) {
152 throw runtime_error ("Could not write ID to output");
157 if (avformat_write_header (_format_context, &options) < 0) {
158 throw runtime_error ("could not write header to FFmpeg output file");
161 _pending_audio.reset (new AudioBuffers(channels, 0));
165 FFmpegFileEncoder::pixel_format (ExportFormat format)
168 case EXPORT_FORMAT_PRORES:
169 return AV_PIX_FMT_YUV422P10;
170 case EXPORT_FORMAT_H264_AAC:
171 case EXPORT_FORMAT_H264_PCM:
172 return AV_PIX_FMT_YUV420P;
174 DCPOMATIC_ASSERT (false);
177 return AV_PIX_FMT_YUV422P10;
181 FFmpegFileEncoder::setup_video ()
183 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
185 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
188 _video_codec_context = avcodec_alloc_context3 (_video_codec);
189 if (!_video_codec_context) {
190 throw runtime_error ("could not allocate FFmpeg video context");
193 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
195 /* Variable quantisation */
196 _video_codec_context->global_quality = 0;
197 _video_codec_context->width = _video_frame_size.width;
198 _video_codec_context->height = _video_frame_size.height;
199 _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
200 _video_codec_context->pix_fmt = _pixel_format;
201 _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
205 FFmpegFileEncoder::setup_audio ()
207 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
209 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
212 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
213 if (!_audio_codec_context) {
214 throw runtime_error ("could not allocate FFmpeg audio context");
217 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
219 /* XXX: configurable */
220 _audio_codec_context->bit_rate = _audio_channels * 128 * 1024;
221 _audio_codec_context->sample_fmt = _sample_format;
222 _audio_codec_context->sample_rate = _audio_frame_rate;
223 _audio_codec_context->channel_layout = av_get_default_channel_layout (_audio_channels);
224 _audio_codec_context->channels = _audio_channels;
228 FFmpegFileEncoder::flush ()
230 if (_pending_audio->frames() > 0) {
231 audio_frame (_pending_audio->frames ());
234 bool flushed_video = false;
235 bool flushed_audio = false;
237 while (!flushed_video || !flushed_audio) {
239 av_init_packet (&packet);
244 DCPOMATIC_DISABLE_WARNINGS
245 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
246 DCPOMATIC_ENABLE_WARNINGS
248 packet.stream_index = 0;
249 av_interleaved_write_frame (_format_context, &packet);
251 flushed_video = true;
253 av_packet_unref (&packet);
255 av_init_packet (&packet);
259 DCPOMATIC_DISABLE_WARNINGS
260 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
261 DCPOMATIC_ENABLE_WARNINGS
263 packet.stream_index = 0;
264 av_interleaved_write_frame (_format_context, &packet);
266 flushed_audio = true;
268 av_packet_unref (&packet);
271 av_write_trailer (_format_context);
273 avcodec_close (_video_codec_context);
274 avcodec_close (_audio_codec_context);
275 avio_close (_format_context->pb);
276 avformat_free_context (_format_context);
280 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
282 shared_ptr<Image> image = video->image (
283 bind (&PlayerVideo::force, _1, _pixel_format),
288 AVFrame* frame = av_frame_alloc ();
289 DCPOMATIC_ASSERT (frame);
292 boost::mutex::scoped_lock lm (_pending_images_mutex);
293 _pending_images[image->data()[0]] = image;
296 for (int i = 0; i < 3; ++i) {
297 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
298 frame->buf[i] = av_buffer_ref (buffer);
299 frame->data[i] = buffer->data;
300 frame->linesize[i] = image->stride()[i];
301 av_buffer_unref (&buffer);
304 frame->width = image->size().width;
305 frame->height = image->size().height;
306 frame->format = _pixel_format;
307 DCPOMATIC_ASSERT (_video_stream->time_base.num == 1);
308 frame->pts = time.get() * _video_stream->time_base.den / DCPTime::HZ;
311 av_init_packet (&packet);
316 DCPOMATIC_DISABLE_WARNINGS
317 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
318 throw EncodeError ("FFmpeg video encode failed");
320 DCPOMATIC_ENABLE_WARNINGS
322 if (got_packet && packet.size) {
323 packet.stream_index = _video_stream_index;
324 av_interleaved_write_frame (_format_context, &packet);
325 av_packet_unref (&packet);
328 av_frame_free (&frame);
332 /** Called when the player gives us some audio */
334 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
336 _pending_audio->append (audio);
338 int frame_size = _audio_codec_context->frame_size;
339 if (frame_size == 0) {
340 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
341 frame_size = _audio_frame_rate / _video_frame_rate;
344 while (_pending_audio->frames() >= frame_size) {
345 audio_frame (frame_size);
350 FFmpegFileEncoder::audio_frame (int size)
352 DCPOMATIC_ASSERT (size);
354 AVFrame* frame = av_frame_alloc ();
355 DCPOMATIC_ASSERT (frame);
357 int const channels = _pending_audio->channels();
358 DCPOMATIC_ASSERT (channels);
360 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
361 DCPOMATIC_ASSERT (buffer_size >= 0);
363 void* samples = av_malloc (buffer_size);
364 DCPOMATIC_ASSERT (samples);
366 frame->nb_samples = size;
367 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
368 DCPOMATIC_ASSERT (r >= 0);
370 float** p = _pending_audio->data ();
371 switch (_audio_codec_context->sample_fmt) {
372 case AV_SAMPLE_FMT_S16:
374 int16_t* q = reinterpret_cast<int16_t*> (samples);
375 for (int i = 0; i < size; ++i) {
376 for (int j = 0; j < channels; ++j) {
377 *q++ = p[j][i] * 32767;
382 case AV_SAMPLE_FMT_S32:
384 int32_t* q = reinterpret_cast<int32_t*> (samples);
385 for (int i = 0; i < size; ++i) {
386 for (int j = 0; j < channels; ++j) {
387 *q++ = p[j][i] * 2147483647;
392 case AV_SAMPLE_FMT_FLTP:
394 float* q = reinterpret_cast<float*> (samples);
395 for (int i = 0; i < channels; ++i) {
396 memcpy (q, p[i], sizeof(float) * size);
402 DCPOMATIC_ASSERT (false);
405 DCPOMATIC_ASSERT (_audio_stream->time_base.num == 1);
406 frame->pts = _audio_frames * _audio_stream->time_base.den / _audio_frame_rate;
409 av_init_packet (&packet);
414 DCPOMATIC_DISABLE_WARNINGS
415 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
416 throw EncodeError ("FFmpeg audio encode failed");
418 DCPOMATIC_ENABLE_WARNINGS
420 if (got_packet && packet.size) {
421 packet.stream_index = _audio_stream_index;
422 av_interleaved_write_frame (_format_context, &packet);
423 av_packet_unref (&packet);
427 av_frame_free (&frame);
429 _pending_audio->trim_start (size);
430 _audio_frames += size;
434 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)
440 FFmpegFileEncoder::buffer_free (void* opaque, uint8_t* data)
442 reinterpret_cast<FFmpegFileEncoder*>(opaque)->buffer_free2(data);
446 FFmpegFileEncoder::buffer_free2 (uint8_t* data)
448 boost::mutex::scoped_lock lm (_pending_images_mutex);
449 if (_pending_images.find(data) != _pending_images.end()) {
450 _pending_images.erase (data);