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)
55 , _pending_audio (new AudioBuffers (film->audio_channels(), 0))
59 _pixel_format = AV_PIX_FMT_YUV422P10;
60 _sample_format = AV_SAMPLE_FMT_S16;
61 _video_codec_name = "prores_ks";
62 _audio_codec_name = "pcm_s16le";
63 av_dict_set (&_video_options, "profile", "3", 0);
64 av_dict_set (&_video_options, "threads", "auto", 0);
67 _pixel_format = AV_PIX_FMT_YUV420P;
68 _sample_format = AV_SAMPLE_FMT_FLTP;
69 _video_codec_name = "libx264";
70 _audio_codec_name = "aac";
74 _player->set_always_burn_subtitles (true);
75 _player->set_play_referenced ();
79 FFmpegEncoder::setup_video ()
81 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
83 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
86 _video_codec_context = avcodec_alloc_context3 (_video_codec);
87 if (!_video_codec_context) {
88 throw runtime_error ("could not allocate FFmpeg video context");
91 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
93 /* Variable quantisation */
94 _video_codec_context->global_quality = 0;
95 _video_codec_context->width = _film->frame_size().width;
96 _video_codec_context->height = _film->frame_size().height;
97 _video_codec_context->time_base = (AVRational) { 1, _film->video_frame_rate() };
98 _video_codec_context->pix_fmt = _pixel_format;
99 _video_codec_context->flags |= CODEC_FLAG_QSCALE | CODEC_FLAG_GLOBAL_HEADER;
103 FFmpegEncoder::setup_audio ()
105 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
107 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
110 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
111 if (!_audio_codec_context) {
112 throw runtime_error ("could not allocate FFmpeg audio context");
115 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
117 /* XXX: configurable */
118 _audio_codec_context->bit_rate = 256 * 1024;
119 _audio_codec_context->sample_fmt = _sample_format;
120 _audio_codec_context->sample_rate = _film->audio_frame_rate ();
121 _audio_codec_context->channel_layout = av_get_default_channel_layout (_film->audio_channels ());
122 _audio_codec_context->channels = _film->audio_channels ();
131 avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
132 if (!_format_context) {
133 throw runtime_error ("could not allocate FFmpeg format context");
136 _video_stream = avformat_new_stream (_format_context, _video_codec);
137 if (!_video_stream) {
138 throw runtime_error ("could not create FFmpeg output video stream");
141 _audio_stream = avformat_new_stream (_format_context, _audio_codec);
142 if (!_audio_stream) {
143 throw runtime_error ("could not create FFmpeg output audio stream");
146 _video_stream->id = _video_stream_index;
147 _video_stream->codec = _video_codec_context;
149 _audio_stream->id = _audio_stream_index;
150 _audio_stream->codec = _audio_codec_context;
152 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
153 throw runtime_error ("could not open FFmpeg video codec");
156 int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
159 av_strerror (r, buffer, sizeof(buffer));
160 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
163 if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
164 throw runtime_error ("could not open FFmpeg output file");
167 if (avformat_write_header (_format_context, 0) < 0) {
168 throw runtime_error ("could not write header to FFmpeg output file");
172 shared_ptr<Job> job = _job.lock ();
173 DCPOMATIC_ASSERT (job);
174 job->sub (_("Encoding"));
177 while (!_player->pass ()) {}
179 if (_pending_audio->frames() > 0) {
180 audio_frame (_pending_audio->frames ());
185 bool flushed_video = false;
186 bool flushed_audio = false;
188 while (!flushed_video || !flushed_audio) {
190 av_init_packet (&packet);
195 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
197 packet.stream_index = 0;
198 av_interleaved_write_frame (_format_context, &packet);
200 flushed_video = true;
202 av_packet_unref (&packet);
204 av_init_packet (&packet);
208 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
210 packet.stream_index = 0;
211 av_interleaved_write_frame (_format_context, &packet);
213 flushed_audio = true;
215 av_packet_unref (&packet);
218 av_write_trailer (_format_context);
220 avcodec_close (_video_codec_context);
221 avcodec_close (_audio_codec_context);
222 avio_close (_format_context->pb);
223 avformat_free_context (_format_context);
227 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
229 shared_ptr<Image> image = video->image (
230 bind (&Log::dcp_log, _film->log().get(), _1, _2),
231 bind (&force_pixel_format, _1, _pixel_format),
236 AVFrame* frame = av_frame_alloc ();
237 DCPOMATIC_ASSERT (frame);
239 for (int i = 0; i < 3; ++i) {
240 size_t const size = image->stride()[i] * image->sample_size(i).height;
241 AVBufferRef* buffer = av_buffer_alloc (size);
242 DCPOMATIC_ASSERT (buffer);
243 /* XXX: inefficient */
244 memcpy (buffer->data, image->data()[i], size);
245 frame->buf[i] = av_buffer_ref (buffer);
246 frame->data[i] = buffer->data;
247 frame->linesize[i] = image->stride()[i];
248 av_buffer_unref (&buffer);
251 frame->width = image->size().width;
252 frame->height = image->size().height;
253 frame->format = _pixel_format;
254 frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
257 av_init_packet (&packet);
262 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
263 throw EncodeError ("FFmpeg video encode failed");
266 if (got_packet && packet.size) {
267 packet.stream_index = _video_stream_index;
268 av_interleaved_write_frame (_format_context, &packet);
269 av_packet_unref (&packet);
272 av_frame_free (&frame);
277 boost::mutex::scoped_lock lm (_mutex);
281 shared_ptr<Job> job = _job.lock ();
283 job->set_progress (float(time.get()) / _film->length().get());
287 /** Called when the player gives us some audio */
289 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio, DCPTime)
291 _pending_audio->append (audio);
293 int frame_size = _audio_codec_context->frame_size;
294 if (frame_size == 0) {
295 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
299 while (_pending_audio->frames() >= frame_size) {
300 audio_frame (frame_size);
305 FFmpegEncoder::audio_frame (int size)
307 DCPOMATIC_ASSERT (size);
309 AVFrame* frame = av_frame_alloc ();
310 DCPOMATIC_ASSERT (frame);
312 int const channels = _audio_codec_context->channels;
313 DCPOMATIC_ASSERT (channels);
315 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
316 DCPOMATIC_ASSERT (buffer_size >= 0);
318 void* samples = av_malloc (buffer_size);
319 DCPOMATIC_ASSERT (samples);
321 frame->nb_samples = size;
322 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
323 DCPOMATIC_ASSERT (r >= 0);
325 float** p = _pending_audio->data ();
326 switch (_audio_codec_context->sample_fmt) {
327 case AV_SAMPLE_FMT_S16:
329 int16_t* q = reinterpret_cast<int16_t*> (samples);
330 for (int i = 0; i < size; ++i) {
331 for (int j = 0; j < channels; ++j) {
332 *q++ = p[j][i] * 32767;
337 case AV_SAMPLE_FMT_FLTP:
339 float* q = reinterpret_cast<float*> (samples);
340 for (int i = 0; i < channels; ++i) {
341 memcpy (q, p[i], sizeof(float) * size);
347 DCPOMATIC_ASSERT (false);
351 av_init_packet (&packet);
356 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
357 throw EncodeError ("FFmpeg audio encode failed");
360 if (got_packet && packet.size) {
361 packet.stream_index = _audio_stream_index;
362 av_interleaved_write_frame (_format_context, &packet);
363 av_packet_unref (&packet);
367 av_frame_free (&frame);
369 _pending_audio->trim_start (size);
373 FFmpegEncoder::subtitle (PlayerSubtitles, DCPTimePeriod)
379 FFmpegEncoder::current_rate () const
381 return _history.rate ();
385 FFmpegEncoder::frames_done () const
387 boost::mutex::scoped_lock lm (_mutex);
388 return _last_time.frames_round (_film->video_frame_rate ());