2 Copyright (C) 2017-2021 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/>.
22 #include "ffmpeg_encoder.h"
26 #include "player_video.h"
30 #include "compose.hpp"
37 using std::make_shared;
39 using std::runtime_error;
40 using std::shared_ptr;
44 using boost::optional;
45 using namespace dcpomatic;
46 #if BOOST_VERSION >= 106100
47 using namespace boost::placeholders;
51 int FFmpegFileEncoder::_video_stream_index = 0;
52 int FFmpegFileEncoder::_audio_stream_index_base = 1;
55 class ExportAudioStream
58 ExportAudioStream (string codec_name, int channels, int frame_rate, AVSampleFormat sample_format, AVFormatContext* format_context, int stream_index)
59 : _format_context (format_context)
60 , _stream_index (stream_index)
62 _codec = avcodec_find_encoder_by_name (codec_name.c_str());
64 throw runtime_error (String::compose("could not find FFmpeg encoder %1", codec_name));
67 _codec_context = avcodec_alloc_context3 (_codec);
68 if (!_codec_context) {
69 throw runtime_error ("could not allocate FFmpeg audio context");
72 avcodec_get_context_defaults3 (_codec_context, _codec);
74 /* XXX: configurable */
75 _codec_context->bit_rate = channels * 128 * 1024;
76 _codec_context->sample_fmt = sample_format;
77 _codec_context->sample_rate = frame_rate;
78 _codec_context->channel_layout = av_get_default_channel_layout (channels);
79 _codec_context->channels = channels;
81 _stream = avformat_new_stream (format_context, _codec);
83 throw runtime_error ("could not create FFmpeg output audio stream");
86 _stream->id = stream_index;
87 _stream->disposition |= AV_DISPOSITION_DEFAULT;
88 DCPOMATIC_DISABLE_WARNINGS
89 _stream->codec = _codec_context;
90 DCPOMATIC_ENABLE_WARNINGS
92 int r = avcodec_open2 (_codec_context, _codec, 0);
95 av_strerror (r, buffer, sizeof(buffer));
96 throw runtime_error (String::compose("could not open FFmpeg audio codec (%1)", buffer));
100 ~ExportAudioStream ()
102 avcodec_close (_codec_context);
105 ExportAudioStream (ExportAudioStream const&) = delete;
106 ExportAudioStream& operator= (ExportAudioStream const&) = delete;
108 int frame_size () const {
109 return _codec_context->frame_size;
115 av_init_packet (&packet);
118 bool flushed = false;
121 DCPOMATIC_DISABLE_WARNINGS
122 avcodec_encode_audio2 (_codec_context, &packet, 0, &got_packet);
123 DCPOMATIC_ENABLE_WARNINGS
125 packet.stream_index = 0;
126 av_interleaved_write_frame (_format_context, &packet);
130 av_packet_unref (&packet);
134 void write (int size, int channel_offset, int channels, float** data, int64_t sample_offset)
136 DCPOMATIC_ASSERT (size);
138 auto frame = av_frame_alloc ();
139 DCPOMATIC_ASSERT (frame);
141 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _codec_context->sample_fmt, 0);
142 DCPOMATIC_ASSERT (buffer_size >= 0);
144 auto samples = av_malloc (buffer_size);
145 DCPOMATIC_ASSERT (samples);
147 frame->nb_samples = size;
148 int r = avcodec_fill_audio_frame (frame, channels, _codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
149 DCPOMATIC_ASSERT (r >= 0);
151 switch (_codec_context->sample_fmt) {
152 case AV_SAMPLE_FMT_S16:
154 int16_t* q = reinterpret_cast<int16_t*> (samples);
155 for (int i = 0; i < size; ++i) {
156 for (int j = 0; j < channels; ++j) {
157 *q++ = data[j + channel_offset][i] * 32767;
162 case AV_SAMPLE_FMT_S32:
164 int32_t* q = reinterpret_cast<int32_t*> (samples);
165 for (int i = 0; i < size; ++i) {
166 for (int j = 0; j < channels; ++j) {
167 *q++ = data[j + channel_offset][i] * 2147483647;
172 case AV_SAMPLE_FMT_FLTP:
174 float* q = reinterpret_cast<float*> (samples);
175 for (int i = 0; i < channels; ++i) {
176 memcpy (q, data[i + channel_offset], sizeof(float) * size);
182 DCPOMATIC_ASSERT (false);
185 DCPOMATIC_ASSERT (_codec_context->time_base.num == 1);
186 frame->pts = sample_offset * _codec_context->time_base.den / _codec_context->sample_rate;
189 av_init_packet (&packet);
194 DCPOMATIC_DISABLE_WARNINGS
195 if (avcodec_encode_audio2 (_codec_context, &packet, frame, &got_packet) < 0) {
196 throw EncodeError ("FFmpeg audio encode failed");
198 DCPOMATIC_ENABLE_WARNINGS
200 if (got_packet && packet.size) {
201 packet.stream_index = _stream_index;
202 av_interleaved_write_frame (_format_context, &packet);
203 av_packet_unref (&packet);
207 av_frame_free (&frame);
211 AVFormatContext* _format_context;
213 AVCodecContext* _codec_context;
219 FFmpegFileEncoder::FFmpegFileEncoder (
220 dcp::Size video_frame_size,
221 int video_frame_rate,
222 int audio_frame_rate,
225 bool audio_stream_per_channel,
227 boost::filesystem::path output
229 : _audio_stream_per_channel (audio_stream_per_channel)
230 , _audio_channels (channels)
232 , _video_frame_size (video_frame_size)
233 , _video_frame_rate (video_frame_rate)
234 , _audio_frame_rate (audio_frame_rate)
236 _pixel_format = pixel_format (format);
239 case ExportFormat::PRORES:
240 _sample_format = AV_SAMPLE_FMT_S16;
241 _video_codec_name = "prores_ks";
242 _audio_codec_name = "pcm_s16le";
243 av_dict_set (&_video_options, "profile", "3", 0);
244 av_dict_set (&_video_options, "threads", "auto", 0);
246 case ExportFormat::H264_AAC:
247 _sample_format = AV_SAMPLE_FMT_FLTP;
248 _video_codec_name = "libx264";
249 _audio_codec_name = "aac";
250 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
252 case ExportFormat::H264_PCM:
253 _sample_format = AV_SAMPLE_FMT_S32;
254 _video_codec_name = "libx264";
255 _audio_codec_name = "pcm_s24le";
256 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
259 DCPOMATIC_ASSERT (false);
262 int r = avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
263 if (!_format_context) {
264 throw runtime_error (String::compose("could not allocate FFmpeg format context (%1)", r));
270 r = avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE);
272 throw runtime_error (String::compose("could not open FFmpeg output file %1 (%2)", _output.string(), r));
275 AVDictionary* options = nullptr;
277 if (avformat_write_header (_format_context, &options) < 0) {
278 throw runtime_error ("could not write header to FFmpeg output file");
281 _pending_audio.reset (new AudioBuffers(channels, 0));
285 FFmpegFileEncoder::~FFmpegFileEncoder ()
287 _audio_streams.clear ();
288 avcodec_close (_video_codec_context);
289 avformat_free_context (_format_context);
294 FFmpegFileEncoder::pixel_format (ExportFormat format)
297 case ExportFormat::PRORES:
298 return AV_PIX_FMT_YUV422P10;
299 case ExportFormat::H264_AAC:
300 case ExportFormat::H264_PCM:
301 return AV_PIX_FMT_YUV420P;
303 DCPOMATIC_ASSERT (false);
306 return AV_PIX_FMT_YUV422P10;
311 FFmpegFileEncoder::setup_video ()
313 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
315 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
318 _video_codec_context = avcodec_alloc_context3 (_video_codec);
319 if (!_video_codec_context) {
320 throw runtime_error ("could not allocate FFmpeg video context");
323 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
325 /* Variable quantisation */
326 _video_codec_context->global_quality = 0;
327 _video_codec_context->width = _video_frame_size.width;
328 _video_codec_context->height = _video_frame_size.height;
329 _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
330 _video_codec_context->pix_fmt = _pixel_format;
331 _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
333 _video_stream = avformat_new_stream (_format_context, _video_codec);
334 if (!_video_stream) {
335 throw runtime_error ("could not create FFmpeg output video stream");
338 DCPOMATIC_DISABLE_WARNINGS
339 _video_stream->id = _video_stream_index;
340 _video_stream->codec = _video_codec_context;
341 DCPOMATIC_ENABLE_WARNINGS
343 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
344 throw runtime_error ("could not open FFmpeg video codec");
350 FFmpegFileEncoder::setup_audio ()
352 int const streams = _audio_stream_per_channel ? _audio_channels : 1;
353 int const channels_per_stream = _audio_stream_per_channel ? 1 : _audio_channels;
355 for (int i = 0; i < streams; ++i) {
356 _audio_streams.push_back(
357 make_shared<ExportAudioStream>(
358 _audio_codec_name, channels_per_stream, _audio_frame_rate, _sample_format, _format_context, _audio_stream_index_base + i
366 FFmpegFileEncoder::flush ()
368 if (_pending_audio->frames() > 0) {
369 audio_frame (_pending_audio->frames ());
372 bool flushed_video = false;
373 bool flushed_audio = false;
375 while (!flushed_video || !flushed_audio) {
377 av_init_packet (&packet);
382 DCPOMATIC_DISABLE_WARNINGS
383 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
384 DCPOMATIC_ENABLE_WARNINGS
386 packet.stream_index = 0;
387 av_interleaved_write_frame (_format_context, &packet);
389 flushed_video = true;
391 av_packet_unref (&packet);
393 flushed_audio = true;
394 for (auto i: _audio_streams) {
396 flushed_audio = false;
401 av_write_trailer (_format_context);
406 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
408 /* All our output formats are video range at the moment */
409 auto image = video->image (
410 bind (&PlayerVideo::force, _1, _pixel_format),
416 auto frame = av_frame_alloc ();
417 DCPOMATIC_ASSERT (frame);
420 boost::mutex::scoped_lock lm (_pending_images_mutex);
421 _pending_images[image->data()[0]] = image;
424 for (int i = 0; i < 3; ++i) {
425 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
426 frame->buf[i] = av_buffer_ref (buffer);
427 frame->data[i] = buffer->data;
428 frame->linesize[i] = image->stride()[i];
429 av_buffer_unref (&buffer);
432 frame->width = image->size().width;
433 frame->height = image->size().height;
434 frame->format = _pixel_format;
435 DCPOMATIC_ASSERT (_video_stream->time_base.num == 1);
436 frame->pts = time.get() * _video_stream->time_base.den / DCPTime::HZ;
439 av_init_packet (&packet);
444 DCPOMATIC_DISABLE_WARNINGS
445 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
446 throw EncodeError ("FFmpeg video encode failed");
448 DCPOMATIC_ENABLE_WARNINGS
450 if (got_packet && packet.size) {
451 packet.stream_index = _video_stream_index;
452 av_interleaved_write_frame (_format_context, &packet);
453 av_packet_unref (&packet);
456 av_frame_free (&frame);
461 /** Called when the player gives us some audio */
463 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
465 _pending_audio->append (audio);
467 DCPOMATIC_ASSERT (!_audio_streams.empty());
468 int frame_size = _audio_streams[0]->frame_size();
469 if (frame_size == 0) {
470 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
471 frame_size = _audio_frame_rate / _video_frame_rate;
474 while (_pending_audio->frames() >= frame_size) {
475 audio_frame (frame_size);
481 FFmpegFileEncoder::audio_frame (int size)
483 if (_audio_stream_per_channel) {
485 for (auto i: _audio_streams) {
486 i->write (size, offset, 1, _pending_audio->data(), _audio_frames);
490 DCPOMATIC_ASSERT (!_audio_streams.empty());
491 DCPOMATIC_ASSERT (_pending_audio->channels());
492 _audio_streams[0]->write (size, 0, _pending_audio->channels(), _pending_audio->data(), _audio_frames);
495 _pending_audio->trim_start (size);
496 _audio_frames += size;
501 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)
508 FFmpegFileEncoder::buffer_free (void* opaque, uint8_t* data)
510 reinterpret_cast<FFmpegFileEncoder*>(opaque)->buffer_free2(data);
515 FFmpegFileEncoder::buffer_free2 (uint8_t* data)
517 boost::mutex::scoped_lock lm (_pending_images_mutex);
518 if (_pending_images.find(data) != _pending_images.end()) {
519 _pending_images.erase (data);