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)
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";
75 _player->set_always_burn_captions (CAPTION_OPEN);
76 _player->set_play_referenced ();
78 int const ch = film->audio_channels ();
81 if (mixdown_to_stereo) {
82 _output_audio_channels = 2;
83 map = AudioMapping (ch, 2);
84 float const overall_gain = 2 / (4 + sqrt(2));
85 float const minus_3dB = 1 / sqrt(2);
86 map.set (dcp::LEFT, 0, overall_gain);
87 map.set (dcp::RIGHT, 1, overall_gain);
88 map.set (dcp::CENTRE, 0, overall_gain * minus_3dB);
89 map.set (dcp::CENTRE, 1, overall_gain * minus_3dB);
90 map.set (dcp::LS, 0, overall_gain);
91 map.set (dcp::RS, 1, overall_gain);
92 _pending_audio.reset (new AudioBuffers (2, 0));
94 _output_audio_channels = ch;
95 map = AudioMapping (ch, ch);
96 _pending_audio.reset (new AudioBuffers (ch, 0));
97 for (int i = 0; i < ch; ++i) {
102 _butler.reset (new Butler (_player, film->log(), map, _output_audio_channels));
106 FFmpegEncoder::setup_video ()
108 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
110 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
113 _video_codec_context = avcodec_alloc_context3 (_video_codec);
114 if (!_video_codec_context) {
115 throw runtime_error ("could not allocate FFmpeg video context");
118 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
120 /* Variable quantisation */
121 _video_codec_context->global_quality = 0;
122 _video_codec_context->width = _film->frame_size().width;
123 _video_codec_context->height = _film->frame_size().height;
124 _video_codec_context->time_base = (AVRational) { 1, _film->video_frame_rate() };
125 _video_codec_context->pix_fmt = _pixel_format;
126 _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
130 FFmpegEncoder::setup_audio ()
132 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
134 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
137 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
138 if (!_audio_codec_context) {
139 throw runtime_error ("could not allocate FFmpeg audio context");
142 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
144 /* XXX: configurable */
145 _audio_codec_context->bit_rate = 256 * 1024;
146 _audio_codec_context->sample_fmt = _sample_format;
147 _audio_codec_context->sample_rate = _film->audio_frame_rate ();
148 _audio_codec_context->channel_layout = av_get_default_channel_layout (_output_audio_channels);
149 _audio_codec_context->channels = _output_audio_channels;
158 avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
159 if (!_format_context) {
160 throw runtime_error ("could not allocate FFmpeg format context");
163 _video_stream = avformat_new_stream (_format_context, _video_codec);
164 if (!_video_stream) {
165 throw runtime_error ("could not create FFmpeg output video stream");
168 _audio_stream = avformat_new_stream (_format_context, _audio_codec);
169 if (!_audio_stream) {
170 throw runtime_error ("could not create FFmpeg output audio stream");
173 _video_stream->id = _video_stream_index;
174 _video_stream->codec = _video_codec_context;
176 _audio_stream->id = _audio_stream_index;
177 _audio_stream->codec = _audio_codec_context;
179 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
180 throw runtime_error ("could not open FFmpeg video codec");
183 int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
186 av_strerror (r, buffer, sizeof(buffer));
187 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
190 if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
191 throw runtime_error ("could not open FFmpeg output file");
194 if (avformat_write_header (_format_context, 0) < 0) {
195 throw runtime_error ("could not write header to FFmpeg output file");
199 shared_ptr<Job> job = _job.lock ();
200 DCPOMATIC_ASSERT (job);
201 job->sub (_("Encoding"));
204 DCPTime const video_frame = DCPTime::from_frames (1, _film->video_frame_rate ());
205 int const audio_frames = video_frame.frames_round(_film->audio_frame_rate());
206 float* interleaved = new float[_output_audio_channels * audio_frames];
207 shared_ptr<AudioBuffers> deinterleaved (new AudioBuffers (_output_audio_channels, audio_frames));
208 for (DCPTime i; i < _film->length(); i += video_frame) {
209 pair<shared_ptr<PlayerVideo>, DCPTime> v = _butler->get_video ();
210 video (v.first, v.second);
211 _butler->get_audio (interleaved, audio_frames);
212 /* XXX: inefficient; butler interleaves and we deinterleave again */
213 float* p = interleaved;
214 for (int j = 0; j < audio_frames; ++j) {
215 for (int k = 0; k < _output_audio_channels; ++k) {
216 deinterleaved->data(k)[j] = *p++;
219 audio (deinterleaved);
221 delete[] interleaved;
223 if (_pending_audio->frames() > 0) {
224 audio_frame (_pending_audio->frames ());
229 bool flushed_video = false;
230 bool flushed_audio = false;
232 while (!flushed_video || !flushed_audio) {
234 av_init_packet (&packet);
239 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
241 packet.stream_index = 0;
242 av_interleaved_write_frame (_format_context, &packet);
244 flushed_video = true;
246 av_packet_unref (&packet);
248 av_init_packet (&packet);
252 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
254 packet.stream_index = 0;
255 av_interleaved_write_frame (_format_context, &packet);
257 flushed_audio = true;
259 av_packet_unref (&packet);
262 av_write_trailer (_format_context);
264 avcodec_close (_video_codec_context);
265 avcodec_close (_audio_codec_context);
266 avio_close (_format_context->pb);
267 avformat_free_context (_format_context);
271 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
273 shared_ptr<Image> image = video->image (
274 bind (&Log::dcp_log, _film->log().get(), _1, _2),
275 bind (&force_pixel_format, _1, _pixel_format),
280 AVFrame* frame = av_frame_alloc ();
281 DCPOMATIC_ASSERT (frame);
283 _pending_images[image->data()[0]] = image;
284 for (int i = 0; i < 3; ++i) {
285 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
286 frame->buf[i] = av_buffer_ref (buffer);
287 frame->data[i] = buffer->data;
288 frame->linesize[i] = image->stride()[i];
289 av_buffer_unref (&buffer);
292 frame->width = image->size().width;
293 frame->height = image->size().height;
294 frame->format = _pixel_format;
295 frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
298 av_init_packet (&packet);
303 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
304 throw EncodeError ("FFmpeg video encode failed");
307 if (got_packet && packet.size) {
308 packet.stream_index = _video_stream_index;
309 av_interleaved_write_frame (_format_context, &packet);
310 av_packet_unref (&packet);
313 av_frame_free (&frame);
318 boost::mutex::scoped_lock lm (_mutex);
322 shared_ptr<Job> job = _job.lock ();
324 job->set_progress (float(time.get()) / _film->length().get());
328 /** Called when the player gives us some audio */
330 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio)
332 _pending_audio->append (audio);
334 int frame_size = _audio_codec_context->frame_size;
335 if (frame_size == 0) {
336 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
337 frame_size = _film->audio_frame_rate() / _film->video_frame_rate();
340 while (_pending_audio->frames() >= frame_size) {
341 audio_frame (frame_size);
346 FFmpegEncoder::audio_frame (int size)
348 DCPOMATIC_ASSERT (size);
350 AVFrame* frame = av_frame_alloc ();
351 DCPOMATIC_ASSERT (frame);
353 int const channels = _pending_audio->channels();
354 DCPOMATIC_ASSERT (channels);
356 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
357 DCPOMATIC_ASSERT (buffer_size >= 0);
359 void* samples = av_malloc (buffer_size);
360 DCPOMATIC_ASSERT (samples);
362 frame->nb_samples = size;
363 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
364 DCPOMATIC_ASSERT (r >= 0);
366 float** p = _pending_audio->data ();
367 switch (_audio_codec_context->sample_fmt) {
368 case AV_SAMPLE_FMT_S16:
370 int16_t* q = reinterpret_cast<int16_t*> (samples);
371 for (int i = 0; i < size; ++i) {
372 for (int j = 0; j < channels; ++j) {
373 *q++ = p[j][i] * 32767;
378 case AV_SAMPLE_FMT_FLTP:
380 float* q = reinterpret_cast<float*> (samples);
381 for (int i = 0; i < channels; ++i) {
382 memcpy (q, p[i], sizeof(float) * size);
388 DCPOMATIC_ASSERT (false);
392 av_init_packet (&packet);
397 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
398 throw EncodeError ("FFmpeg audio encode failed");
401 if (got_packet && packet.size) {
402 packet.stream_index = _audio_stream_index;
403 av_interleaved_write_frame (_format_context, &packet);
404 av_packet_unref (&packet);
408 av_frame_free (&frame);
410 _pending_audio->trim_start (size);
414 FFmpegEncoder::subtitle (PlayerCaption, DCPTimePeriod)
420 FFmpegEncoder::current_rate () const
422 return _history.rate ();
426 FFmpegEncoder::frames_done () const
428 boost::mutex::scoped_lock lm (_mutex);
429 return _last_time.frames_round (_film->video_frame_rate ());
433 FFmpegEncoder::buffer_free (void* opaque, uint8_t* data)
435 reinterpret_cast<FFmpegEncoder*>(opaque)->buffer_free2(data);
439 FFmpegEncoder::buffer_free2 (uint8_t* data)
441 _pending_images.erase (data);