2 Copyright (C) 2017 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;
37 using boost::shared_ptr;
39 using boost::weak_ptr;
41 int FFmpegEncoder::_video_stream_index = 0;
42 int FFmpegEncoder::_audio_stream_index = 1;
45 force_pixel_format (AVPixelFormat, AVPixelFormat out)
50 FFmpegEncoder::FFmpegEncoder (shared_ptr<const Film> film, weak_ptr<Job> job, boost::filesystem::path output, Format format, bool mixdown_to_stereo)
58 _pixel_format = AV_PIX_FMT_YUV422P10;
59 _sample_format = AV_SAMPLE_FMT_S16;
60 _video_codec_name = "prores_ks";
61 _audio_codec_name = "pcm_s16le";
62 av_dict_set (&_video_options, "profile", "3", 0);
63 av_dict_set (&_video_options, "threads", "auto", 0);
66 _pixel_format = AV_PIX_FMT_YUV420P;
67 _sample_format = AV_SAMPLE_FMT_FLTP;
68 _video_codec_name = "libx264";
69 _audio_codec_name = "aac";
73 _player->set_always_burn_subtitles (true);
74 _player->set_play_referenced ();
76 int const ch = film->audio_channels ();
78 if (mixdown_to_stereo) {
79 _audio_mapping = AudioMapping (ch, 2);
80 float const overall_gain = 2 / (4 + sqrt(2));
81 float const minus_3dB = 1 / sqrt(2);
82 _audio_mapping.set (dcp::LEFT, 0, overall_gain);
83 _audio_mapping.set (dcp::RIGHT, 1, overall_gain);
84 _audio_mapping.set (dcp::CENTRE, 0, overall_gain * minus_3dB);
85 _audio_mapping.set (dcp::CENTRE, 1, overall_gain * minus_3dB);
86 _audio_mapping.set (dcp::LS, 0, overall_gain);
87 _audio_mapping.set (dcp::RS, 1, overall_gain);
88 _pending_audio.reset (new AudioBuffers (2, 0));
90 _audio_mapping = AudioMapping (ch, ch);
91 _pending_audio.reset (new AudioBuffers (ch, 0));
92 for (int i = 0; i < ch; ++i) {
93 _audio_mapping.set (i, i, 1);
99 FFmpegEncoder::setup_video ()
101 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
103 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
106 _video_codec_context = avcodec_alloc_context3 (_video_codec);
107 if (!_video_codec_context) {
108 throw runtime_error ("could not allocate FFmpeg video context");
111 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
113 /* Variable quantisation */
114 _video_codec_context->global_quality = 0;
115 _video_codec_context->width = _film->frame_size().width;
116 _video_codec_context->height = _film->frame_size().height;
117 _video_codec_context->time_base = (AVRational) { 1, _film->video_frame_rate() };
118 _video_codec_context->pix_fmt = _pixel_format;
119 _video_codec_context->flags |= CODEC_FLAG_QSCALE | CODEC_FLAG_GLOBAL_HEADER;
123 FFmpegEncoder::setup_audio ()
125 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
127 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
130 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
131 if (!_audio_codec_context) {
132 throw runtime_error ("could not allocate FFmpeg audio context");
135 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
137 /* XXX: configurable */
138 _audio_codec_context->bit_rate = 256 * 1024;
139 _audio_codec_context->sample_fmt = _sample_format;
140 _audio_codec_context->sample_rate = _film->audio_frame_rate ();
141 _audio_codec_context->channel_layout = av_get_default_channel_layout (_audio_mapping.output_channels ());
142 _audio_codec_context->channels = _audio_mapping.output_channels ();
151 avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
152 if (!_format_context) {
153 throw runtime_error ("could not allocate FFmpeg format context");
156 _video_stream = avformat_new_stream (_format_context, _video_codec);
157 if (!_video_stream) {
158 throw runtime_error ("could not create FFmpeg output video stream");
161 _audio_stream = avformat_new_stream (_format_context, _audio_codec);
162 if (!_audio_stream) {
163 throw runtime_error ("could not create FFmpeg output audio stream");
166 _video_stream->id = _video_stream_index;
167 _video_stream->codec = _video_codec_context;
169 _audio_stream->id = _audio_stream_index;
170 _audio_stream->codec = _audio_codec_context;
172 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
173 throw runtime_error ("could not open FFmpeg video codec");
176 int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
179 av_strerror (r, buffer, sizeof(buffer));
180 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
183 if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
184 throw runtime_error ("could not open FFmpeg output file");
187 if (avformat_write_header (_format_context, 0) < 0) {
188 throw runtime_error ("could not write header to FFmpeg output file");
192 shared_ptr<Job> job = _job.lock ();
193 DCPOMATIC_ASSERT (job);
194 job->sub (_("Encoding"));
197 while (!_player->pass ()) {}
199 if (_pending_audio->frames() > 0) {
200 audio_frame (_pending_audio->frames ());
205 bool flushed_video = false;
206 bool flushed_audio = false;
208 while (!flushed_video || !flushed_audio) {
210 av_init_packet (&packet);
215 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
217 packet.stream_index = 0;
218 av_interleaved_write_frame (_format_context, &packet);
220 flushed_video = true;
222 av_packet_unref (&packet);
224 av_init_packet (&packet);
228 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
230 packet.stream_index = 0;
231 av_interleaved_write_frame (_format_context, &packet);
233 flushed_audio = true;
235 av_packet_unref (&packet);
238 av_write_trailer (_format_context);
240 avcodec_close (_video_codec_context);
241 avcodec_close (_audio_codec_context);
242 avio_close (_format_context->pb);
243 avformat_free_context (_format_context);
247 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
249 shared_ptr<Image> image = video->image (
250 bind (&Log::dcp_log, _film->log().get(), _1, _2),
251 bind (&force_pixel_format, _1, _pixel_format),
256 AVFrame* frame = av_frame_alloc ();
257 DCPOMATIC_ASSERT (frame);
259 for (int i = 0; i < 3; ++i) {
260 size_t const size = image->stride()[i] * image->sample_size(i).height;
261 AVBufferRef* buffer = av_buffer_alloc (size);
262 DCPOMATIC_ASSERT (buffer);
263 /* XXX: inefficient */
264 memcpy (buffer->data, image->data()[i], size);
265 frame->buf[i] = av_buffer_ref (buffer);
266 frame->data[i] = buffer->data;
267 frame->linesize[i] = image->stride()[i];
268 av_buffer_unref (&buffer);
271 frame->width = image->size().width;
272 frame->height = image->size().height;
273 frame->format = _pixel_format;
274 frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
277 av_init_packet (&packet);
282 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
283 throw EncodeError ("FFmpeg video encode failed");
286 if (got_packet && packet.size) {
287 packet.stream_index = _video_stream_index;
288 av_interleaved_write_frame (_format_context, &packet);
289 av_packet_unref (&packet);
292 av_frame_free (&frame);
297 boost::mutex::scoped_lock lm (_mutex);
301 shared_ptr<Job> job = _job.lock ();
303 job->set_progress (float(time.get()) / _film->length().get());
307 /** Called when the player gives us some audio */
309 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio, DCPTime)
311 _pending_audio->append (remap (audio, _audio_mapping.output_channels(), _audio_mapping));
313 int frame_size = _audio_codec_context->frame_size;
314 if (frame_size == 0) {
315 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
319 while (_pending_audio->frames() >= frame_size) {
320 audio_frame (frame_size);
325 FFmpegEncoder::audio_frame (int size)
327 DCPOMATIC_ASSERT (size);
329 AVFrame* frame = av_frame_alloc ();
330 DCPOMATIC_ASSERT (frame);
332 int const channels = _pending_audio->channels();
333 DCPOMATIC_ASSERT (channels);
335 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
336 DCPOMATIC_ASSERT (buffer_size >= 0);
338 void* samples = av_malloc (buffer_size);
339 DCPOMATIC_ASSERT (samples);
341 frame->nb_samples = size;
342 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
343 DCPOMATIC_ASSERT (r >= 0);
345 float** p = _pending_audio->data ();
346 switch (_audio_codec_context->sample_fmt) {
347 case AV_SAMPLE_FMT_S16:
349 int16_t* q = reinterpret_cast<int16_t*> (samples);
350 for (int i = 0; i < size; ++i) {
351 for (int j = 0; j < channels; ++j) {
352 *q++ = p[j][i] * 32767;
357 case AV_SAMPLE_FMT_FLTP:
359 float* q = reinterpret_cast<float*> (samples);
360 for (int i = 0; i < channels; ++i) {
361 memcpy (q, p[i], sizeof(float) * size);
367 DCPOMATIC_ASSERT (false);
371 av_init_packet (&packet);
376 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
377 throw EncodeError ("FFmpeg audio encode failed");
380 if (got_packet && packet.size) {
381 packet.stream_index = _audio_stream_index;
382 av_interleaved_write_frame (_format_context, &packet);
383 av_packet_unref (&packet);
387 av_frame_free (&frame);
389 _pending_audio->trim_start (size);
393 FFmpegEncoder::subtitle (PlayerSubtitles, DCPTimePeriod)
399 FFmpegEncoder::current_rate () const
401 return _history.rate ();
405 FFmpegEncoder::frames_done () const
407 boost::mutex::scoped_lock lm (_mutex);
408 return _last_time.frames_round (_film->video_frame_rate ());