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"
28 #include "compose.hpp"
34 using std::runtime_error;
36 using boost::shared_ptr;
38 using boost::weak_ptr;
40 int FFmpegEncoder::_video_stream_index = 0;
41 int FFmpegEncoder::_audio_stream_index = 1;
44 force_pixel_format (AVPixelFormat, AVPixelFormat out)
49 FFmpegEncoder::FFmpegEncoder (shared_ptr<const Film> film, weak_ptr<Job> job, boost::filesystem::path output, Format format)
54 , _pending_audio (new AudioBuffers (film->audio_channels(), 0))
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 ();
78 FFmpegEncoder::setup_video ()
80 _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
82 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
85 _video_codec_context = avcodec_alloc_context3 (_video_codec);
86 if (!_video_codec_context) {
87 throw runtime_error ("could not allocate FFmpeg video context");
90 avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
92 /* Variable quantisation */
93 _video_codec_context->global_quality = 0;
94 _video_codec_context->width = _film->frame_size().width;
95 _video_codec_context->height = _film->frame_size().height;
96 _video_codec_context->time_base = (AVRational) { 1, _film->video_frame_rate() };
97 _video_codec_context->pix_fmt = _pixel_format;
98 _video_codec_context->flags |= CODEC_FLAG_QSCALE | CODEC_FLAG_GLOBAL_HEADER;
102 FFmpegEncoder::setup_audio ()
104 _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
106 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
109 _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
110 if (!_audio_codec_context) {
111 throw runtime_error ("could not allocate FFmpeg audio context");
114 avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
116 /* XXX: configurable */
117 _audio_codec_context->bit_rate = 256 * 1024;
118 _audio_codec_context->sample_fmt = _sample_format;
119 _audio_codec_context->sample_rate = _film->audio_frame_rate ();
120 _audio_codec_context->channel_layout = av_get_default_channel_layout (_film->audio_channels ());
121 _audio_codec_context->channels = _film->audio_channels ();
130 avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
131 if (!_format_context) {
132 throw runtime_error ("could not allocate FFmpeg format context");
135 _video_stream = avformat_new_stream (_format_context, _video_codec);
136 if (!_video_stream) {
137 throw runtime_error ("could not create FFmpeg output video stream");
140 _audio_stream = avformat_new_stream (_format_context, _audio_codec);
141 if (!_audio_stream) {
142 throw runtime_error ("could not create FFmpeg output audio stream");
145 _video_stream->id = _video_stream_index;
146 _video_stream->codec = _video_codec_context;
148 _audio_stream->id = _audio_stream_index;
149 _audio_stream->codec = _audio_codec_context;
151 if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
152 throw runtime_error ("could not open FFmpeg video codec");
155 int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
158 av_strerror (r, buffer, sizeof(buffer));
159 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
162 if (avio_open (&_format_context->pb, _output.c_str(), AVIO_FLAG_WRITE) < 0) {
163 throw runtime_error ("could not open FFmpeg output file");
166 if (avformat_write_header (_format_context, 0) < 0) {
167 throw runtime_error ("could not write header to FFmpeg output file");
171 shared_ptr<Job> job = _job.lock ();
172 DCPOMATIC_ASSERT (job);
173 job->sub (_("Encoding"));
176 while (!_player->pass ()) {}
178 if (_pending_audio->frames() > 0) {
179 audio_frame (_pending_audio->frames ());
184 bool flushed_video = false;
185 bool flushed_audio = false;
187 while (!flushed_video || !flushed_audio) {
189 av_init_packet (&packet);
194 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
196 packet.stream_index = 0;
197 av_interleaved_write_frame (_format_context, &packet);
199 flushed_video = true;
201 av_packet_unref (&packet);
203 av_init_packet (&packet);
207 avcodec_encode_audio2 (_video_codec_context, &packet, 0, &got_packet);
209 packet.stream_index = 0;
210 av_interleaved_write_frame (_format_context, &packet);
212 flushed_audio = true;
214 av_packet_unref (&packet);
217 av_write_trailer (_format_context);
219 avcodec_close (_video_codec_context);
220 avcodec_close (_audio_codec_context);
221 avio_close (_format_context->pb);
222 avformat_free_context (_format_context);
226 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
228 shared_ptr<Image> image = video->image (
229 bind (&Log::dcp_log, _film->log().get(), _1, _2),
230 bind (&force_pixel_format, _1, _pixel_format),
235 AVFrame* frame = av_frame_alloc ();
236 DCPOMATIC_ASSERT (frame);
238 for (int i = 0; i < 3; ++i) {
239 size_t const size = image->stride()[i] * image->size().height;
240 AVBufferRef* buffer = av_buffer_alloc (size);
241 DCPOMATIC_ASSERT (buffer);
242 /* XXX: inefficient */
243 memcpy (buffer->data, image->data()[i], size);
244 frame->buf[i] = av_buffer_ref (buffer);
245 frame->data[i] = buffer->data;
246 frame->linesize[i] = image->stride()[i];
247 av_buffer_unref (&buffer);
250 frame->width = image->size().width;
251 frame->height = image->size().height;
252 frame->format = _pixel_format;
253 frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
256 av_init_packet (&packet);
261 if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
262 throw EncodeError ("FFmpeg video encode failed");
265 if (got_packet && packet.size) {
266 packet.stream_index = _video_stream_index;
267 av_interleaved_write_frame (_format_context, &packet);
268 av_packet_unref (&packet);
271 av_frame_free (&frame);
276 boost::mutex::scoped_lock lm (_mutex);
280 shared_ptr<Job> job = _job.lock ();
282 job->set_progress (float(time.get()) / _film->length().get());
287 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio, DCPTime)
289 _pending_audio->append (audio);
291 while (_pending_audio->frames() >= _audio_codec_context->frame_size) {
292 audio_frame (_audio_codec_context->frame_size);
297 FFmpegEncoder::audio_frame (int size)
299 AVFrame* frame = av_frame_alloc ();
300 DCPOMATIC_ASSERT (frame);
302 int const channels = _audio_codec_context->channels;
304 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
305 DCPOMATIC_ASSERT (buffer_size >= 0);
307 void* samples = av_malloc (buffer_size);
308 DCPOMATIC_ASSERT (samples);
310 frame->nb_samples = size;
311 int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
312 DCPOMATIC_ASSERT (r >= 0);
314 float** p = _pending_audio->data ();
315 switch (_audio_codec_context->sample_fmt) {
316 case AV_SAMPLE_FMT_S16:
318 int16_t* q = reinterpret_cast<int16_t*> (samples);
319 for (int i = 0; i < size; ++i) {
320 for (int j = 0; j < channels; ++i) {
321 *q++ = p[j][i] * 32767;
326 case AV_SAMPLE_FMT_FLTP:
328 float* q = reinterpret_cast<float*> (samples);
329 for (int i = 0; i < channels; ++i) {
330 memcpy (q, p[i], sizeof(float) * size);
336 DCPOMATIC_ASSERT (false);
340 av_init_packet (&packet);
345 if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
346 throw EncodeError ("FFmpeg audio encode failed");
349 if (got_packet && packet.size) {
350 packet.stream_index = _audio_stream_index;
351 av_interleaved_write_frame (_format_context, &packet);
352 av_packet_unref (&packet);
356 av_frame_free (&frame);
358 _pending_audio->trim_start (size);
362 FFmpegEncoder::subtitle (PlayerSubtitles, DCPTimePeriod)
368 FFmpegEncoder::current_rate () const
370 return _history.rate ();
374 FFmpegEncoder::frames_done () const
376 boost::mutex::scoped_lock lm (_mutex);
377 return _last_time.frames_round (_film->video_frame_rate ());