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"
30 #include "compose.hpp"
36 using std::runtime_error;
39 using boost::shared_ptr;
41 using boost::weak_ptr;
43 int FFmpegEncoder::_video_stream_index = 0;
44 int FFmpegEncoder::_audio_stream_index = 1;
47 force_pixel_format (AVPixelFormat, AVPixelFormat out)
52 FFmpegEncoder::FFmpegEncoder (shared_ptr<const Film> film, weak_ptr<Job> job, boost::filesystem::path output, Format format, bool mixdown_to_stereo, int x264_crf)
60 _pixel_format = AV_PIX_FMT_YUV422P10;
61 _sample_format = AV_SAMPLE_FMT_S16;
62 _video_codec_name = "prores_ks";
63 _audio_codec_name = "pcm_s16le";
64 av_dict_set (&_video_options, "profile", "3", 0);
65 av_dict_set (&_video_options, "threads", "auto", 0);
68 _pixel_format = AV_PIX_FMT_YUV420P;
69 _sample_format = AV_SAMPLE_FMT_FLTP;
70 _video_codec_name = "libx264";
71 _audio_codec_name = "aac";
72 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
76 _player->set_always_burn_open_subtitles ();
77 _player->set_play_referenced ();
79 int const ch = film->audio_channels ();
82 if (mixdown_to_stereo) {
83 _output_audio_channels = 2;
84 map = AudioMapping (ch, 2);
85 float const overall_gain = 2 / (4 + sqrt(2));
86 float const minus_3dB = 1 / sqrt(2);
87 map.set (dcp::LEFT, 0, overall_gain);
88 map.set (dcp::RIGHT, 1, overall_gain);
89 map.set (dcp::CENTRE, 0, overall_gain * minus_3dB);
90 map.set (dcp::CENTRE, 1, overall_gain * minus_3dB);
91 map.set (dcp::LS, 0, overall_gain);
92 map.set (dcp::RS, 1, overall_gain);
93 _pending_audio.reset (new AudioBuffers (2, 0));
95 _output_audio_channels = ch;
96 map = AudioMapping (ch, ch);
97 _pending_audio.reset (new AudioBuffers (ch, 0));
98 for (int i = 0; i < ch; ++i) {
103 _butler.reset (new Butler (_player, film->log(), map, _output_audio_channels));
107 FFmpegEncoder::setup_video ()
109 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
111 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
114 _video_codec_context = avcodec_alloc_context3 (_video_codec);
115 if (!_video_codec_context) {
116 throw runtime_error ("could not allocate FFmpeg video context");
119 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
121 /* Variable quantisation */
122 _video_codec_context->global_quality = 0;
123 _video_codec_context->width = _film->frame_size().width;
124 _video_codec_context->height = _film->frame_size().height;
125 _video_codec_context->time_base = (AVRational) { 1, _film->video_frame_rate() };
126 _video_codec_context->pix_fmt = _pixel_format;
127 _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
131 FFmpegEncoder::setup_audio ()
133 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
135 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
138 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
139 if (!_audio_codec_context) {
140 throw runtime_error ("could not allocate FFmpeg audio context");
143 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
145 /* XXX: configurable */
146 _audio_codec_context->bit_rate = 256 * 1024;
147 _audio_codec_context->sample_fmt = _sample_format;
148 _audio_codec_context->sample_rate = _film->audio_frame_rate ();
149 _audio_codec_context->channel_layout = av_get_default_channel_layout (_output_audio_channels);
150 _audio_codec_context->channels = _output_audio_channels;
159 avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
160 if (!_format_context) {
161 throw runtime_error ("could not allocate FFmpeg format context");
164 _video_stream = avformat_new_stream (_format_context, _video_codec);
165 if (!_video_stream) {
166 throw runtime_error ("could not create FFmpeg output video stream");
169 _audio_stream = avformat_new_stream (_format_context, _audio_codec);
170 if (!_audio_stream) {
171 throw runtime_error ("could not create FFmpeg output audio stream");
174 _video_stream->id = _video_stream_index;
175 _video_stream->codec = _video_codec_context;
177 _audio_stream->id = _audio_stream_index;
178 _audio_stream->codec = _audio_codec_context;
180 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
181 throw runtime_error ("could not open FFmpeg video codec");
184 int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
187 av_strerror (r, buffer, sizeof(buffer));
188 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
191 if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
192 throw runtime_error ("could not open FFmpeg output file");
195 if (avformat_write_header (_format_context, 0) < 0) {
196 throw runtime_error ("could not write header to FFmpeg output file");
200 shared_ptr<Job> job = _job.lock ();
201 DCPOMATIC_ASSERT (job);
202 job->sub (_("Encoding"));
205 DCPTime const video_frame = DCPTime::from_frames (1, _film->video_frame_rate ());
206 int const audio_frames = video_frame.frames_round(_film->audio_frame_rate());
207 float* interleaved = new float[_output_audio_channels * audio_frames];
208 shared_ptr<AudioBuffers> deinterleaved (new AudioBuffers (_output_audio_channels, audio_frames));
209 for (DCPTime i; i < _film->length(); i += video_frame) {
210 pair<shared_ptr<PlayerVideo>, DCPTime> v = _butler->get_video ();
211 video (v.first, v.second);
212 _butler->get_audio (interleaved, audio_frames);
213 /* XXX: inefficient; butler interleaves and we deinterleave again */
214 float* p = interleaved;
215 for (int j = 0; j < audio_frames; ++j) {
216 for (int k = 0; k < _output_audio_channels; ++k) {
217 deinterleaved->data(k)[j] = *p++;
220 audio (deinterleaved);
222 delete[] interleaved;
224 if (_pending_audio->frames() > 0) {
225 audio_frame (_pending_audio->frames ());
230 bool flushed_video = false;
231 bool flushed_audio = false;
233 while (!flushed_video || !flushed_audio) {
235 av_init_packet (&packet);
240 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
242 packet.stream_index = 0;
243 av_interleaved_write_frame (_format_context, &packet);
245 flushed_video = true;
247 av_packet_unref (&packet);
249 av_init_packet (&packet);
253 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
255 packet.stream_index = 0;
256 av_interleaved_write_frame (_format_context, &packet);
258 flushed_audio = true;
260 av_packet_unref (&packet);
263 av_write_trailer (_format_context);
265 avcodec_close (_video_codec_context);
266 avcodec_close (_audio_codec_context);
267 avio_close (_format_context->pb);
268 avformat_free_context (_format_context);
272 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
274 shared_ptr<Image> image = video->image (
275 bind (&Log::dcp_log, _film->log().get(), _1, _2),
276 bind (&force_pixel_format, _1, _pixel_format),
281 AVFrame* frame = av_frame_alloc ();
282 DCPOMATIC_ASSERT (frame);
284 _pending_images[image->data()[0]] = image;
285 for (int i = 0; i < 3; ++i) {
286 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
287 frame->buf[i] = av_buffer_ref (buffer);
288 frame->data[i] = buffer->data;
289 frame->linesize[i] = image->stride()[i];
290 av_buffer_unref (&buffer);
293 frame->width = image->size().width;
294 frame->height = image->size().height;
295 frame->format = _pixel_format;
296 frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
299 av_init_packet (&packet);
304 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
305 throw EncodeError ("FFmpeg video encode failed");
308 if (got_packet && packet.size) {
309 packet.stream_index = _video_stream_index;
310 av_interleaved_write_frame (_format_context, &packet);
311 av_packet_unref (&packet);
314 av_frame_free (&frame);
319 boost::mutex::scoped_lock lm (_mutex);
323 shared_ptr<Job> job = _job.lock ();
325 job->set_progress (float(time.get()) / _film->length().get());
329 /** Called when the player gives us some audio */
331 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio)
333 _pending_audio->append (audio);
335 int frame_size = _audio_codec_context->frame_size;
336 if (frame_size == 0) {
337 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
338 frame_size = _film->audio_frame_rate() / _film->video_frame_rate();
341 while (_pending_audio->frames() >= frame_size) {
342 audio_frame (frame_size);
347 FFmpegEncoder::audio_frame (int size)
349 DCPOMATIC_ASSERT (size);
351 AVFrame* frame = av_frame_alloc ();
352 DCPOMATIC_ASSERT (frame);
354 int const channels = _pending_audio->channels();
355 DCPOMATIC_ASSERT (channels);
357 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
358 DCPOMATIC_ASSERT (buffer_size >= 0);
360 void* samples = av_malloc (buffer_size);
361 DCPOMATIC_ASSERT (samples);
363 frame->nb_samples = size;
364 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
365 DCPOMATIC_ASSERT (r >= 0);
367 float** p = _pending_audio->data ();
368 switch (_audio_codec_context->sample_fmt) {
369 case AV_SAMPLE_FMT_S16:
371 int16_t* q = reinterpret_cast<int16_t*> (samples);
372 for (int i = 0; i < size; ++i) {
373 for (int j = 0; j < channels; ++j) {
374 *q++ = p[j][i] * 32767;
379 case AV_SAMPLE_FMT_FLTP:
381 float* q = reinterpret_cast<float*> (samples);
382 for (int i = 0; i < channels; ++i) {
383 memcpy (q, p[i], sizeof(float) * size);
389 DCPOMATIC_ASSERT (false);
393 av_init_packet (&packet);
398 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
399 throw EncodeError ("FFmpeg audio encode failed");
402 if (got_packet && packet.size) {
403 packet.stream_index = _audio_stream_index;
404 av_interleaved_write_frame (_format_context, &packet);
405 av_packet_unref (&packet);
409 av_frame_free (&frame);
411 _pending_audio->trim_start (size);
415 FFmpegEncoder::subtitle (PlayerText, DCPTimePeriod)
421 FFmpegEncoder::current_rate () const
423 return _history.rate ();
427 FFmpegEncoder::frames_done () const
429 boost::mutex::scoped_lock lm (_mutex);
430 return _last_time.frames_round (_film->video_frame_rate ());
434 FFmpegEncoder::buffer_free (void* opaque, uint8_t* data)
436 reinterpret_cast<FFmpegEncoder*>(opaque)->buffer_free2(data);
440 FFmpegEncoder::buffer_free2 (uint8_t* data)
442 _pending_images.erase (data);