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 "compose.hpp"
24 #include "ffmpeg_encoder.h"
25 #include "ffmpeg_wrapper.h"
31 #include "player_video.h"
33 #include <libavutil/channel_layout.h>
41 using std::make_shared;
42 using std::shared_ptr;
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 EncodeError (String::compose("avcodec_find_encoder_by_name failed for %1", codec_name));
67 _codec_context = avcodec_alloc_context3 (_codec);
68 if (!_codec_context) {
69 throw std::bad_alloc ();
72 /* XXX: configurable */
73 _codec_context->bit_rate = channels * 128 * 1024;
74 _codec_context->sample_fmt = sample_format;
75 _codec_context->sample_rate = frame_rate;
76 _codec_context->channel_layout = av_get_default_channel_layout (channels);
77 _codec_context->channels = channels;
79 int r = avcodec_open2 (_codec_context, _codec, 0);
81 throw EncodeError (N_("avcodec_open2"), N_("ExportAudioStream::ExportAudioStream"), r);
84 _stream = avformat_new_stream (format_context, _codec);
86 throw EncodeError (N_("avformat_new_stream"), N_("ExportAudioStream::ExportAudioStream"));
89 _stream->id = stream_index;
90 _stream->disposition |= AV_DISPOSITION_DEFAULT;
91 r = avcodec_parameters_from_context (_stream->codecpar, _codec_context);
93 throw EncodeError (N_("avcodec_parameters_from_context"), N_("ExportAudioStream::ExportAudioStream"), r);
99 avcodec_close (_codec_context);
102 ExportAudioStream (ExportAudioStream const&) = delete;
103 ExportAudioStream& operator= (ExportAudioStream const&) = delete;
105 int frame_size () const {
106 return _codec_context->frame_size;
111 int r = avcodec_send_frame (_codec_context, nullptr);
112 if (r < 0 && r != AVERROR_EOF) {
113 /* We get EOF if we've already flushed the stream once */
114 throw EncodeError (N_("avcodec_send_frame"), N_("ExportAudioStream::flush"), r);
117 ffmpeg::Packet packet;
118 r = avcodec_receive_packet (_codec_context, packet.get());
119 if (r == AVERROR_EOF) {
122 throw EncodeError (N_("avcodec_receive_packet"), N_("ExportAudioStream::flush"), r);
125 packet->stream_index = _stream_index;
126 av_interleaved_write_frame (_format_context, packet.get());
130 void write (int size, int channel_offset, int channels, float* const* data, int64_t sample_offset)
132 DCPOMATIC_ASSERT (size);
134 auto frame = av_frame_alloc ();
135 DCPOMATIC_ASSERT (frame);
138 int const buffer_size = av_samples_get_buffer_size (&line_size, channels, size, _codec_context->sample_fmt, 0);
139 DCPOMATIC_ASSERT (buffer_size >= 0);
141 auto samples = av_malloc (buffer_size);
142 DCPOMATIC_ASSERT (samples);
144 frame->nb_samples = size;
145 frame->format = _codec_context->sample_fmt;
146 frame->channels = channels;
147 int r = avcodec_fill_audio_frame (frame, channels, _codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
148 DCPOMATIC_ASSERT (r >= 0);
150 switch (_codec_context->sample_fmt) {
151 case AV_SAMPLE_FMT_S16:
153 int16_t* q = reinterpret_cast<int16_t*> (samples);
154 for (int i = 0; i < size; ++i) {
155 for (int j = 0; j < channels; ++j) {
156 *q++ = data[j + channel_offset][i] * 32767;
161 case AV_SAMPLE_FMT_S32:
163 int32_t* q = reinterpret_cast<int32_t*> (samples);
164 for (int i = 0; i < size; ++i) {
165 for (int j = 0; j < channels; ++j) {
166 *q++ = data[j + channel_offset][i] * 2147483647;
171 case AV_SAMPLE_FMT_FLTP:
173 for (int i = 0; i < channels; ++i) {
174 memcpy (reinterpret_cast<float*>(static_cast<uint8_t*>(samples) + i * line_size), data[i + channel_offset], sizeof(float) * size);
179 DCPOMATIC_ASSERT (false);
182 DCPOMATIC_ASSERT (_codec_context->time_base.num == 1);
183 frame->pts = sample_offset * _codec_context->time_base.den / _codec_context->sample_rate;
185 r = avcodec_send_frame (_codec_context, frame);
187 av_frame_free (&frame);
189 throw EncodeError (N_("avcodec_send_frame"), N_("ExportAudioStream::write"), r);
192 ffmpeg::Packet packet;
193 r = avcodec_receive_packet (_codec_context, packet.get());
194 if (r < 0 && r != AVERROR(EAGAIN)) {
195 throw EncodeError (N_("avcodec_receive_packet"), N_("ExportAudioStream::write"), r);
197 packet->stream_index = _stream_index;
198 av_interleaved_write_frame (_format_context, packet.get());
203 AVFormatContext* _format_context;
204 AVCodec const * _codec;
205 AVCodecContext* _codec_context;
211 FFmpegFileEncoder::FFmpegFileEncoder (
212 dcp::Size video_frame_size,
213 int video_frame_rate,
214 int audio_frame_rate,
217 bool audio_stream_per_channel,
219 boost::filesystem::path output
221 : _audio_stream_per_channel (audio_stream_per_channel)
222 , _audio_channels (channels)
224 , _video_frame_size (video_frame_size)
225 , _video_frame_rate (video_frame_rate)
226 , _audio_frame_rate (audio_frame_rate)
228 _pixel_format = pixel_format (format);
231 case ExportFormat::PRORES_4444:
232 _sample_format = AV_SAMPLE_FMT_S32;
233 _video_codec_name = "prores_ks";
234 _audio_codec_name = "pcm_s24le";
235 av_dict_set(&_video_options, "profile", "4", 0);
236 av_dict_set(&_video_options, "threads", "auto", 0);
238 case ExportFormat::PRORES_HQ:
239 _sample_format = AV_SAMPLE_FMT_S32;
240 _video_codec_name = "prores_ks";
241 _audio_codec_name = "pcm_s24le";
242 av_dict_set (&_video_options, "profile", "3", 0);
243 av_dict_set (&_video_options, "threads", "auto", 0);
245 case ExportFormat::H264_AAC:
246 _sample_format = AV_SAMPLE_FMT_FLTP;
247 _video_codec_name = "libx264";
248 _audio_codec_name = "aac";
249 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
252 DCPOMATIC_ASSERT (false);
255 int r = avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
256 if (!_format_context) {
257 throw EncodeError (N_("avformat_alloc_output_context2"), "FFmpegFileEncoder::FFmpegFileEncoder", r);
263 r = avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE);
265 throw EncodeError (String::compose(_("Could not open output file %1 (%2)"), _output.string(), r));
268 AVDictionary* options = nullptr;
270 r = avformat_write_header (_format_context, &options);
272 throw EncodeError (N_("avformat_write_header"), N_("FFmpegFileEncoder::FFmpegFileEncoder"), r);
275 _pending_audio = make_shared<AudioBuffers>(channels, 0);
279 FFmpegFileEncoder::~FFmpegFileEncoder ()
281 _audio_streams.clear ();
282 avcodec_close (_video_codec_context);
283 avio_close (_format_context->pb);
284 _format_context->pb = nullptr;
285 avformat_free_context (_format_context);
290 FFmpegFileEncoder::pixel_format (ExportFormat format)
293 case ExportFormat::PRORES_4444:
294 return AV_PIX_FMT_YUV444P10;
295 case ExportFormat::PRORES_HQ:
296 return AV_PIX_FMT_YUV422P10;
297 case ExportFormat::H264_AAC:
298 return AV_PIX_FMT_YUV420P;
300 DCPOMATIC_ASSERT (false);
303 return AV_PIX_FMT_YUV422P10;
308 FFmpegFileEncoder::setup_video ()
310 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
312 throw EncodeError (String::compose("avcodec_find_encoder_by_name failed for %1", _video_codec_name));
315 _video_codec_context = avcodec_alloc_context3 (_video_codec);
316 if (!_video_codec_context) {
317 throw std::bad_alloc ();
320 /* Variable quantisation */
321 _video_codec_context->global_quality = 0;
322 _video_codec_context->width = _video_frame_size.width;
323 _video_codec_context->height = _video_frame_size.height;
324 _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
325 _video_codec_context->pix_fmt = _pixel_format;
326 _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
328 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
329 throw EncodeError(N_("avcodec_open2"), N_("FFmpegFileEncoder::setup_video"));
332 _video_stream = avformat_new_stream (_format_context, _video_codec);
333 if (!_video_stream) {
334 throw EncodeError (N_("avformat_new_stream"), N_("FFmpegFileEncoder::setup_video"));
337 _video_stream->id = _video_stream_index;
338 int r = avcodec_parameters_from_context (_video_stream->codecpar, _video_codec_context);
340 throw EncodeError (N_("avcodec_parameters_from_context"), N_("FFmpegFileEncoder::setup_video"), r);
346 FFmpegFileEncoder::setup_audio ()
348 int const streams = _audio_stream_per_channel ? _audio_channels : 1;
349 int const channels_per_stream = _audio_stream_per_channel ? 1 : _audio_channels;
351 for (int i = 0; i < streams; ++i) {
352 _audio_streams.push_back(
353 make_shared<ExportAudioStream>(
354 _audio_codec_name, channels_per_stream, _audio_frame_rate, _sample_format, _format_context, _audio_stream_index_base + i
362 FFmpegFileEncoder::flush ()
364 if (_pending_audio->frames() > 0) {
365 audio_frame (_pending_audio->frames ());
368 bool flushed_video = false;
369 bool flushed_audio = false;
371 while (!flushed_video || !flushed_audio) {
372 int r = avcodec_send_frame (_video_codec_context, nullptr);
373 if (r < 0 && r != AVERROR_EOF) {
374 /* We get EOF if we've already flushed the stream once */
375 throw EncodeError (N_("avcodec_send_frame"), N_("FFmpegFileEncoder::flush"), r);
378 ffmpeg::Packet packet;
379 r = avcodec_receive_packet (_video_codec_context, packet.get());
380 if (r == AVERROR_EOF) {
381 flushed_video = true;
383 throw EncodeError (N_("avcodec_receive_packet"), N_("FFmpegFileEncoder::flush"), r);
385 packet->stream_index = _video_stream_index;
386 packet->duration = _video_stream->time_base.den / _video_frame_rate;
387 av_interleaved_write_frame (_format_context, packet.get());
390 flushed_audio = true;
391 for (auto i: _audio_streams) {
393 flushed_audio = false;
398 auto const r = av_write_trailer(_format_context);
399 DCPOMATIC_ASSERT(r == 0);
404 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
406 /* All our output formats are video range at the moment */
407 auto image = video->image (
408 bind (&PlayerVideo::force, _pixel_format),
413 auto frame = av_frame_alloc ();
414 DCPOMATIC_ASSERT (frame);
416 for (int i = 0; i < 3; ++i) {
417 auto buffer = _pending_images.create_buffer(image, i);
418 frame->buf[i] = av_buffer_ref (buffer);
419 frame->data[i] = buffer->data;
420 frame->linesize[i] = image->stride()[i];
421 av_buffer_unref (&buffer);
424 frame->width = image->size().width;
425 frame->height = image->size().height;
426 frame->format = _pixel_format;
427 DCPOMATIC_ASSERT (_video_stream->time_base.num == 1);
428 frame->pts = time.get() * _video_stream->time_base.den / DCPTime::HZ;
430 int r = avcodec_send_frame (_video_codec_context, frame);
431 av_frame_free (&frame);
433 throw EncodeError (N_("avcodec_send_frame"), N_("FFmpegFileEncoder::video"), r);
436 ffmpeg::Packet packet;
437 r = avcodec_receive_packet (_video_codec_context, packet.get());
438 if (r < 0 && r != AVERROR(EAGAIN)) {
439 throw EncodeError (N_("avcodec_receive_packet"), N_("FFmpegFileEncoder::video"), r);
441 packet->stream_index = _video_stream_index;
442 packet->duration = _video_stream->time_base.den / _video_frame_rate;
443 av_interleaved_write_frame (_format_context, packet.get());
448 /** Called when the player gives us some audio */
450 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
452 _pending_audio->append (audio);
454 DCPOMATIC_ASSERT (!_audio_streams.empty());
455 int frame_size = _audio_streams[0]->frame_size();
456 if (frame_size == 0) {
457 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
458 frame_size = _audio_frame_rate / _video_frame_rate;
461 while (_pending_audio->frames() >= frame_size) {
462 audio_frame (frame_size);
468 FFmpegFileEncoder::audio_frame (int size)
470 if (_audio_stream_per_channel) {
472 for (auto i: _audio_streams) {
473 i->write (size, offset, 1, _pending_audio->data(), _audio_frames);
477 DCPOMATIC_ASSERT (!_audio_streams.empty());
478 DCPOMATIC_ASSERT (_pending_audio->channels());
479 _audio_streams[0]->write (size, 0, _pending_audio->channels(), _pending_audio->data(), _audio_frames);
482 _pending_audio->trim_start (size);
483 _audio_frames += size;
488 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)