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 _video_stream->id = _video_stream_index;
117 _video_stream->codec = _video_codec_context;
119 _audio_stream->id = _audio_stream_index;
120 _audio_stream->codec = _audio_codec_context;
122 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
123 throw runtime_error ("could not open FFmpeg video codec");
126 r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
129 av_strerror (r, buffer, sizeof(buffer));
130 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
133 if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
134 throw runtime_error ("could not open FFmpeg output file");
137 AVDictionary* options = 0;
139 #ifdef DCPOMATIC_VARIANT_SWAROOP
141 av_dict_set (&options, "encryption_key", key->hex().c_str(), 0);
142 /* XXX: is this OK? */
143 av_dict_set (&options, "encryption_kid", "00000000000000000000000000000000", 0);
144 av_dict_set (&options, "encryption_scheme", "cenc-aes-ctr", 0);
148 if (av_dict_set(&_format_context->metadata, SWAROOP_ID_TAG, id->c_str(), 0) < 0) {
149 throw runtime_error ("Could not write ID to output");
154 if (avformat_write_header (_format_context, &options) < 0) {
155 throw runtime_error ("could not write header to FFmpeg output file");
158 _pending_audio.reset (new AudioBuffers(channels, 0));
162 FFmpegFileEncoder::pixel_format (ExportFormat format)
165 case EXPORT_FORMAT_PRORES:
166 return AV_PIX_FMT_YUV422P10;
167 case EXPORT_FORMAT_H264_AAC:
168 case EXPORT_FORMAT_H264_PCM:
169 return AV_PIX_FMT_YUV420P;
171 DCPOMATIC_ASSERT (false);
174 return AV_PIX_FMT_YUV422P10;
178 FFmpegFileEncoder::setup_video ()
180 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
182 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
185 _video_codec_context = avcodec_alloc_context3 (_video_codec);
186 if (!_video_codec_context) {
187 throw runtime_error ("could not allocate FFmpeg video context");
190 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
192 /* Variable quantisation */
193 _video_codec_context->global_quality = 0;
194 _video_codec_context->width = _video_frame_size.width;
195 _video_codec_context->height = _video_frame_size.height;
196 _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
197 _video_codec_context->pix_fmt = _pixel_format;
198 _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
202 FFmpegFileEncoder::setup_audio ()
204 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
206 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
209 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
210 if (!_audio_codec_context) {
211 throw runtime_error ("could not allocate FFmpeg audio context");
214 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
216 /* XXX: configurable */
217 _audio_codec_context->bit_rate = _audio_channels * 128 * 1024;
218 _audio_codec_context->sample_fmt = _sample_format;
219 _audio_codec_context->sample_rate = _audio_frame_rate;
220 _audio_codec_context->channel_layout = av_get_default_channel_layout (_audio_channels);
221 _audio_codec_context->channels = _audio_channels;
225 FFmpegFileEncoder::flush ()
227 if (_pending_audio->frames() > 0) {
228 audio_frame (_pending_audio->frames ());
231 bool flushed_video = false;
232 bool flushed_audio = false;
234 while (!flushed_video || !flushed_audio) {
236 av_init_packet (&packet);
241 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
243 packet.stream_index = 0;
244 av_interleaved_write_frame (_format_context, &packet);
246 flushed_video = true;
248 av_packet_unref (&packet);
250 av_init_packet (&packet);
254 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
256 packet.stream_index = 0;
257 av_interleaved_write_frame (_format_context, &packet);
259 flushed_audio = true;
261 av_packet_unref (&packet);
264 av_write_trailer (_format_context);
266 avcodec_close (_video_codec_context);
267 avcodec_close (_audio_codec_context);
268 avio_close (_format_context->pb);
269 avformat_free_context (_format_context);
273 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
275 shared_ptr<Image> image = video->image (
276 bind (&PlayerVideo::force, _1, _pixel_format),
281 AVFrame* frame = av_frame_alloc ();
282 DCPOMATIC_ASSERT (frame);
285 boost::mutex::scoped_lock lm (_pending_images_mutex);
286 _pending_images[image->data()[0]] = image;
289 for (int i = 0; i < 3; ++i) {
290 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
291 frame->buf[i] = av_buffer_ref (buffer);
292 frame->data[i] = buffer->data;
293 frame->linesize[i] = image->stride()[i];
294 av_buffer_unref (&buffer);
297 frame->width = image->size().width;
298 frame->height = image->size().height;
299 frame->format = _pixel_format;
300 DCPOMATIC_ASSERT (_video_stream->time_base.num == 1);
301 frame->pts = time.get() * _video_stream->time_base.den / DCPTime::HZ;
304 av_init_packet (&packet);
309 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
310 throw EncodeError ("FFmpeg video encode failed");
313 if (got_packet && packet.size) {
314 packet.stream_index = _video_stream_index;
315 av_interleaved_write_frame (_format_context, &packet);
316 av_packet_unref (&packet);
319 av_frame_free (&frame);
323 /** Called when the player gives us some audio */
325 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
327 _pending_audio->append (audio);
329 int frame_size = _audio_codec_context->frame_size;
330 if (frame_size == 0) {
331 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
332 frame_size = _audio_frame_rate / _video_frame_rate;
335 while (_pending_audio->frames() >= frame_size) {
336 audio_frame (frame_size);
341 FFmpegFileEncoder::audio_frame (int size)
343 DCPOMATIC_ASSERT (size);
345 AVFrame* frame = av_frame_alloc ();
346 DCPOMATIC_ASSERT (frame);
348 int const channels = _pending_audio->channels();
349 DCPOMATIC_ASSERT (channels);
351 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
352 DCPOMATIC_ASSERT (buffer_size >= 0);
354 void* samples = av_malloc (buffer_size);
355 DCPOMATIC_ASSERT (samples);
357 frame->nb_samples = size;
358 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
359 DCPOMATIC_ASSERT (r >= 0);
361 float** p = _pending_audio->data ();
362 switch (_audio_codec_context->sample_fmt) {
363 case AV_SAMPLE_FMT_S16:
365 int16_t* q = reinterpret_cast<int16_t*> (samples);
366 for (int i = 0; i < size; ++i) {
367 for (int j = 0; j < channels; ++j) {
368 *q++ = p[j][i] * 32767;
373 case AV_SAMPLE_FMT_S32:
375 int32_t* q = reinterpret_cast<int32_t*> (samples);
376 for (int i = 0; i < size; ++i) {
377 for (int j = 0; j < channels; ++j) {
378 *q++ = p[j][i] * 2147483647;
383 case AV_SAMPLE_FMT_FLTP:
385 float* q = reinterpret_cast<float*> (samples);
386 for (int i = 0; i < channels; ++i) {
387 memcpy (q, p[i], sizeof(float) * size);
393 DCPOMATIC_ASSERT (false);
396 DCPOMATIC_ASSERT (_audio_stream->time_base.num == 1);
397 frame->pts = _audio_frames * _audio_stream->time_base.den / _audio_frame_rate;
400 av_init_packet (&packet);
405 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
406 throw EncodeError ("FFmpeg audio encode failed");
409 if (got_packet && packet.size) {
410 packet.stream_index = _audio_stream_index;
411 av_interleaved_write_frame (_format_context, &packet);
412 av_packet_unref (&packet);
416 av_frame_free (&frame);
418 _pending_audio->trim_start (size);
419 _audio_frames += size;
423 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)
429 FFmpegFileEncoder::buffer_free (void* opaque, uint8_t* data)
431 reinterpret_cast<FFmpegFileEncoder*>(opaque)->buffer_free2(data);
435 FFmpegFileEncoder::buffer_free2 (uint8_t* data)
437 boost::mutex::scoped_lock lm (_pending_images_mutex);
438 if (_pending_images.find(data) != _pending_images.end()) {
439 _pending_images.erase (data);