Add basic quality option for x264 export.
[dcpomatic.git] / src / lib / ffmpeg_encoder.cc
1 /*
2     Copyright (C) 2017 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
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.
10
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.
15
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/>.
18
19 */
20
21 #include "ffmpeg_encoder.h"
22 #include "film.h"
23 #include "job.h"
24 #include "player.h"
25 #include "player_video.h"
26 #include "log.h"
27 #include "image.h"
28 #include "cross.h"
29 #include "butler.h"
30 #include "compose.hpp"
31 #include <iostream>
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::runtime_error;
37 using std::cout;
38 using std::pair;
39 using boost::shared_ptr;
40 using boost::bind;
41 using boost::weak_ptr;
42
43 int FFmpegEncoder::_video_stream_index = 0;
44 int FFmpegEncoder::_audio_stream_index = 1;
45
46 static AVPixelFormat
47 force_pixel_format (AVPixelFormat, AVPixelFormat out)
48 {
49         return out;
50 }
51
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)
53         : Encoder (film, job)
54         , _video_options (0)
55         , _history (1000)
56         , _output (output)
57 {
58         switch (format) {
59         case FORMAT_PRORES:
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);
66                 break;
67         case FORMAT_H264:
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);
73                 break;
74         }
75
76         _player->set_always_burn_open_subtitles ();
77         _player->set_play_referenced ();
78
79         int const ch = film->audio_channels ();
80
81         AudioMapping map;
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));
94         } else {
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) {
99                         map.set (i, i, 1);
100                 }
101         }
102
103         _butler.reset (new Butler (_player, film->log(), map, _output_audio_channels));
104 }
105
106 void
107 FFmpegEncoder::setup_video ()
108 {
109         _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
110         if (!_video_codec) {
111                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
112         }
113
114         _video_codec_context = avcodec_alloc_context3 (_video_codec);
115         if (!_video_codec_context) {
116                 throw runtime_error ("could not allocate FFmpeg video context");
117         }
118
119         avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
120
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;
128 }
129
130 void
131 FFmpegEncoder::setup_audio ()
132 {
133         _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
134         if (!_audio_codec) {
135                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
136         }
137
138         _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
139         if (!_audio_codec_context) {
140                 throw runtime_error ("could not allocate FFmpeg audio context");
141         }
142
143         avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
144
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;
151 }
152
153 void
154 FFmpegEncoder::go ()
155 {
156         setup_video ();
157         setup_audio ();
158
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");
162         }
163
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");
167         }
168
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");
172         }
173
174         _video_stream->id = _video_stream_index;
175         _video_stream->codec = _video_codec_context;
176
177         _audio_stream->id = _audio_stream_index;
178         _audio_stream->codec = _audio_codec_context;
179
180         if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
181                 throw runtime_error ("could not open FFmpeg video codec");
182         }
183
184         int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
185         if (r < 0) {
186                 char buffer[256];
187                 av_strerror (r, buffer, sizeof(buffer));
188                 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
189         }
190
191         if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
192                 throw runtime_error ("could not open FFmpeg output file");
193         }
194
195         if (avformat_write_header (_format_context, 0) < 0) {
196                 throw runtime_error ("could not write header to FFmpeg output file");
197         }
198
199         {
200                 shared_ptr<Job> job = _job.lock ();
201                 DCPOMATIC_ASSERT (job);
202                 job->sub (_("Encoding"));
203         }
204
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++;
218                         }
219                 }
220                 audio (deinterleaved);
221         }
222         delete[] interleaved;
223
224         if (_pending_audio->frames() > 0) {
225                 audio_frame (_pending_audio->frames ());
226         }
227
228         /* Flush */
229
230         bool flushed_video = false;
231         bool flushed_audio = false;
232
233         while (!flushed_video || !flushed_audio) {
234                 AVPacket packet;
235                 av_init_packet (&packet);
236                 packet.data = 0;
237                 packet.size = 0;
238
239                 int got_packet;
240                 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
241                 if (got_packet) {
242                         packet.stream_index = 0;
243                         av_interleaved_write_frame (_format_context, &packet);
244                 } else {
245                         flushed_video = true;
246                 }
247                 av_packet_unref (&packet);
248
249                 av_init_packet (&packet);
250                 packet.data = 0;
251                 packet.size = 0;
252
253                 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
254                 if (got_packet) {
255                         packet.stream_index = 0;
256                         av_interleaved_write_frame (_format_context, &packet);
257                 } else {
258                         flushed_audio = true;
259                 }
260                 av_packet_unref (&packet);
261         }
262
263         av_write_trailer (_format_context);
264
265         avcodec_close (_video_codec_context);
266         avcodec_close (_audio_codec_context);
267         avio_close (_format_context->pb);
268         avformat_free_context (_format_context);
269 }
270
271 void
272 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
273 {
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),
277                 true,
278                 false
279                 );
280
281         AVFrame* frame = av_frame_alloc ();
282         DCPOMATIC_ASSERT (frame);
283
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);
291         }
292
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);
297
298         AVPacket packet;
299         av_init_packet (&packet);
300         packet.data = 0;
301         packet.size = 0;
302
303         int got_packet;
304         if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
305                 throw EncodeError ("FFmpeg video encode failed");
306         }
307
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);
312         }
313
314         av_frame_free (&frame);
315
316         _history.event ();
317
318         {
319                 boost::mutex::scoped_lock lm (_mutex);
320                 _last_time = time;
321         }
322
323         shared_ptr<Job> job = _job.lock ();
324         if (job) {
325                 job->set_progress (float(time.get()) / _film->length().get());
326         }
327 }
328
329 /** Called when the player gives us some audio */
330 void
331 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio)
332 {
333         _pending_audio->append (audio);
334
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();
339         }
340
341         while (_pending_audio->frames() >= frame_size) {
342                 audio_frame (frame_size);
343         }
344 }
345
346 void
347 FFmpegEncoder::audio_frame (int size)
348 {
349         DCPOMATIC_ASSERT (size);
350
351         AVFrame* frame = av_frame_alloc ();
352         DCPOMATIC_ASSERT (frame);
353
354         int const channels = _pending_audio->channels();
355         DCPOMATIC_ASSERT (channels);
356
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);
359
360         void* samples = av_malloc (buffer_size);
361         DCPOMATIC_ASSERT (samples);
362
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);
366
367         float** p = _pending_audio->data ();
368         switch (_audio_codec_context->sample_fmt) {
369         case AV_SAMPLE_FMT_S16:
370         {
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;
375                         }
376                 }
377                 break;
378         }
379         case AV_SAMPLE_FMT_FLTP:
380         {
381                 float* q = reinterpret_cast<float*> (samples);
382                 for (int i = 0; i < channels; ++i) {
383                         memcpy (q, p[i], sizeof(float) * size);
384                         q += size;
385                 }
386                 break;
387         }
388         default:
389                 DCPOMATIC_ASSERT (false);
390         }
391
392         AVPacket packet;
393         av_init_packet (&packet);
394         packet.data = 0;
395         packet.size = 0;
396
397         int got_packet;
398         if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
399                 throw EncodeError ("FFmpeg audio encode failed");
400         }
401
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);
406         }
407
408         av_free (samples);
409         av_frame_free (&frame);
410
411         _pending_audio->trim_start (size);
412 }
413
414 void
415 FFmpegEncoder::subtitle (PlayerText, DCPTimePeriod)
416 {
417
418 }
419
420 float
421 FFmpegEncoder::current_rate () const
422 {
423         return _history.rate ();
424 }
425
426 Frame
427 FFmpegEncoder::frames_done () const
428 {
429         boost::mutex::scoped_lock lm (_mutex);
430         return _last_time.frames_round (_film->video_frame_rate ());
431 }
432
433 void
434 FFmpegEncoder::buffer_free (void* opaque, uint8_t* data)
435 {
436         reinterpret_cast<FFmpegEncoder*>(opaque)->buffer_free2(data);
437 }
438
439 void
440 FFmpegEncoder::buffer_free2 (uint8_t* data)
441 {
442         _pending_images.erase (data);
443 }