Try to enable all streams in MOV exports.
[dcpomatic.git] / src / lib / ffmpeg_file_encoder.cc
1 /*
2     Copyright (C) 2017-2018 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 "compose.hpp"
30 #include <iostream>
31
32 #include "i18n.h"
33
34 using std::string;
35 using std::runtime_error;
36 using std::cout;
37 using std::pair;
38 using boost::shared_ptr;
39 using boost::bind;
40 using boost::weak_ptr;
41 using boost::optional;
42 using namespace dcpomatic;
43 #if BOOST_VERSION >= 106100
44 using namespace boost::placeholders;
45 #endif
46
47 int FFmpegFileEncoder::_video_stream_index = 0;
48 int FFmpegFileEncoder::_audio_stream_index_base = 1;
49
50
51 class ExportAudioStream : public boost::noncopyable
52 {
53 public:
54         ExportAudioStream (string codec_name, int channels, int frame_rate, AVSampleFormat sample_format, AVFormatContext* format_context, int stream_index)
55                 : _format_context (format_context)
56                 , _stream_index (stream_index)
57         {
58                 _codec = avcodec_find_encoder_by_name (codec_name.c_str());
59                 if (!_codec) {
60                         throw runtime_error (String::compose("could not find FFmpeg encoder %1", codec_name));
61                 }
62
63                 _codec_context = avcodec_alloc_context3 (_codec);
64                 if (!_codec_context) {
65                         throw runtime_error ("could not allocate FFmpeg audio context");
66                 }
67
68                 avcodec_get_context_defaults3 (_codec_context, _codec);
69
70                 /* XXX: configurable */
71                 _codec_context->bit_rate = channels * 128 * 1024;
72                 _codec_context->sample_fmt = sample_format;
73                 _codec_context->sample_rate = frame_rate;
74                 _codec_context->channel_layout = av_get_default_channel_layout (channels);
75                 _codec_context->channels = channels;
76
77                 _stream = avformat_new_stream (format_context, _codec);
78                 if (!_stream) {
79                         throw runtime_error ("could not create FFmpeg output audio stream");
80                 }
81
82                 _stream->id = stream_index;
83                 _stream->disposition |= AV_DISPOSITION_DEFAULT;
84 DCPOMATIC_DISABLE_WARNINGS
85                 _stream->codec = _codec_context;
86 DCPOMATIC_ENABLE_WARNINGS
87
88                 int r = avcodec_open2 (_codec_context, _codec, 0);
89                 if (r < 0) {
90                         char buffer[256];
91                         av_strerror (r, buffer, sizeof(buffer));
92                         throw runtime_error (String::compose("could not open FFmpeg audio codec (%1)", buffer));
93                 }
94         }
95
96         ~ExportAudioStream ()
97         {
98                 avcodec_close (_codec_context);
99         }
100
101         int frame_size () const {
102                 return _codec_context->frame_size;
103         }
104
105         bool flush ()
106         {
107                 AVPacket packet;
108                 av_init_packet (&packet);
109                 packet.data = 0;
110                 packet.size = 0;
111                 bool flushed = false;
112
113                 int got_packet;
114 DCPOMATIC_DISABLE_WARNINGS
115                 avcodec_encode_audio2 (_codec_context, &packet, 0, &got_packet);
116 DCPOMATIC_ENABLE_WARNINGS
117                 if (got_packet) {
118                         packet.stream_index = 0;
119                         av_interleaved_write_frame (_format_context, &packet);
120                 } else {
121                         flushed = true;
122                 }
123                 av_packet_unref (&packet);
124                 return flushed;
125         }
126
127         void write (int size, int channel_offset, int channels, float** data, int64_t sample_offset)
128         {
129                 DCPOMATIC_ASSERT (size);
130
131                 AVFrame* frame = av_frame_alloc ();
132                 DCPOMATIC_ASSERT (frame);
133
134                 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _codec_context->sample_fmt, 0);
135                 DCPOMATIC_ASSERT (buffer_size >= 0);
136
137                 void* samples = av_malloc (buffer_size);
138                 DCPOMATIC_ASSERT (samples);
139
140                 frame->nb_samples = size;
141                 int r = avcodec_fill_audio_frame (frame, channels, _codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
142                 DCPOMATIC_ASSERT (r >= 0);
143
144                 switch (_codec_context->sample_fmt) {
145                 case AV_SAMPLE_FMT_S16:
146                 {
147                         int16_t* q = reinterpret_cast<int16_t*> (samples);
148                         for (int i = 0; i < size; ++i) {
149                                 for (int j = 0; j < channels; ++j) {
150                                         *q++ = data[j + channel_offset][i] * 32767;
151                                 }
152                         }
153                         break;
154                 }
155                 case AV_SAMPLE_FMT_S32:
156                 {
157                         int32_t* q = reinterpret_cast<int32_t*> (samples);
158                         for (int i = 0; i < size; ++i) {
159                                 for (int j = 0; j < channels; ++j) {
160                                         *q++ = data[j + channel_offset][i] * 2147483647;
161                                 }
162                         }
163                         break;
164                 }
165                 case AV_SAMPLE_FMT_FLTP:
166                 {
167                         float* q = reinterpret_cast<float*> (samples);
168                         for (int i = 0; i < channels; ++i) {
169                                 memcpy (q, data[i + channel_offset], sizeof(float) * size);
170                                 q += size;
171                         }
172                         break;
173                 }
174                 default:
175                         DCPOMATIC_ASSERT (false);
176                 }
177
178                 DCPOMATIC_ASSERT (_codec_context->time_base.num == 1);
179                 frame->pts = sample_offset * _codec_context->time_base.den / _codec_context->sample_rate;
180
181                 AVPacket packet;
182                 av_init_packet (&packet);
183                 packet.data = 0;
184                 packet.size = 0;
185                 int got_packet;
186
187                 DCPOMATIC_DISABLE_WARNINGS
188                 if (avcodec_encode_audio2 (_codec_context, &packet, frame, &got_packet) < 0) {
189                         throw EncodeError ("FFmpeg audio encode failed");
190                 }
191                 DCPOMATIC_ENABLE_WARNINGS
192
193                 if (got_packet && packet.size) {
194                         packet.stream_index = _stream_index;
195                         av_interleaved_write_frame (_format_context, &packet);
196                         av_packet_unref (&packet);
197                 }
198
199                 av_free (samples);
200                 av_frame_free (&frame);
201         }
202
203 private:
204         AVFormatContext* _format_context;
205         AVCodec* _codec;
206         AVCodecContext* _codec_context;
207         AVStream* _stream;
208         int _stream_index;
209 };
210
211
212 FFmpegFileEncoder::FFmpegFileEncoder (
213         dcp::Size video_frame_size,
214         int video_frame_rate,
215         int audio_frame_rate,
216         int channels,
217         ExportFormat format,
218         bool audio_stream_per_channel,
219         int x264_crf,
220         boost::filesystem::path output
221 #ifdef DCPOMATIC_VARIANT_SWAROOP
222         , optional<dcp::Key> key
223         , optional<string> id
224 #endif
225         )
226         : _audio_stream_per_channel (audio_stream_per_channel)
227         , _video_options (0)
228         , _audio_channels (channels)
229         , _output (output)
230         , _video_frame_size (video_frame_size)
231         , _video_frame_rate (video_frame_rate)
232         , _audio_frame_rate (audio_frame_rate)
233         , _audio_frames (0)
234 {
235         _pixel_format = pixel_format (format);
236
237         switch (format) {
238         case EXPORT_FORMAT_PRORES:
239                 _sample_format = AV_SAMPLE_FMT_S16;
240                 _video_codec_name = "prores_ks";
241                 _audio_codec_name = "pcm_s16le";
242                 av_dict_set (&_video_options, "profile", "3", 0);
243                 av_dict_set (&_video_options, "threads", "auto", 0);
244                 break;
245         case EXPORT_FORMAT_H264_AAC:
246                 _sample_format = AV_SAMPLE_FMT_FLTP;
247                 _video_codec_name = "libx264";
248                 _audio_codec_name = "aac";
249                 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
250                 break;
251         case EXPORT_FORMAT_H264_PCM:
252                 _sample_format = AV_SAMPLE_FMT_S32;
253                 _video_codec_name = "libx264";
254                 _audio_codec_name = "pcm_s24le";
255                 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
256                 break;
257         default:
258                 DCPOMATIC_ASSERT (false);
259         }
260
261 #ifdef DCPOMATIC_VARIANT_SWAROOP
262         int r = avformat_alloc_output_context2 (&_format_context, av_guess_format("mov", 0, 0), 0, 0);
263 #else
264         int r = avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
265 #endif
266         if (!_format_context) {
267                 throw runtime_error (String::compose("could not allocate FFmpeg format context (%1)", r));
268         }
269
270         setup_video ();
271         setup_audio ();
272
273         r = avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE);
274         if (r < 0) {
275                 throw runtime_error (String::compose("could not open FFmpeg output file %1 (%2)", _output.string(), r));
276         }
277
278         AVDictionary* options = 0;
279
280 #ifdef DCPOMATIC_VARIANT_SWAROOP
281         if (key) {
282                 av_dict_set (&options, "encryption_key", key->hex().c_str(), 0);
283                 /* XXX: is this OK? */
284                 av_dict_set (&options, "encryption_kid", "00000000000000000000000000000000", 0);
285                 av_dict_set (&options, "encryption_scheme", "cenc-aes-ctr", 0);
286         }
287
288         if (id) {
289                 if (av_dict_set(&_format_context->metadata, SWAROOP_ID_TAG, id->c_str(), 0) < 0) {
290                         throw runtime_error ("Could not write ID to output");
291                 }
292         }
293 #endif
294
295         if (avformat_write_header (_format_context, &options) < 0) {
296                 throw runtime_error ("could not write header to FFmpeg output file");
297         }
298
299         _pending_audio.reset (new AudioBuffers(channels, 0));
300 }
301
302
303 FFmpegFileEncoder::~FFmpegFileEncoder ()
304 {
305         _audio_streams.clear ();
306         avcodec_close (_video_codec_context);
307         avformat_free_context (_format_context);
308 }
309
310
311 AVPixelFormat
312 FFmpegFileEncoder::pixel_format (ExportFormat format)
313 {
314         switch (format) {
315         case EXPORT_FORMAT_PRORES:
316                 return AV_PIX_FMT_YUV422P10;
317         case EXPORT_FORMAT_H264_AAC:
318         case EXPORT_FORMAT_H264_PCM:
319                 return AV_PIX_FMT_YUV420P;
320         default:
321                 DCPOMATIC_ASSERT (false);
322         }
323
324         return AV_PIX_FMT_YUV422P10;
325 }
326
327 void
328 FFmpegFileEncoder::setup_video ()
329 {
330         _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
331         if (!_video_codec) {
332                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
333         }
334
335         _video_codec_context = avcodec_alloc_context3 (_video_codec);
336         if (!_video_codec_context) {
337                 throw runtime_error ("could not allocate FFmpeg video context");
338         }
339
340         avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
341
342         /* Variable quantisation */
343         _video_codec_context->global_quality = 0;
344         _video_codec_context->width = _video_frame_size.width;
345         _video_codec_context->height = _video_frame_size.height;
346         _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
347         _video_codec_context->pix_fmt = _pixel_format;
348         _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
349
350         _video_stream = avformat_new_stream (_format_context, _video_codec);
351         if (!_video_stream) {
352                 throw runtime_error ("could not create FFmpeg output video stream");
353         }
354
355 DCPOMATIC_DISABLE_WARNINGS
356         _video_stream->id = _video_stream_index;
357         _video_stream->codec = _video_codec_context;
358 DCPOMATIC_ENABLE_WARNINGS
359
360         if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
361                 throw runtime_error ("could not open FFmpeg video codec");
362         }
363 }
364
365
366 void
367 FFmpegFileEncoder::setup_audio ()
368 {
369         int const streams = _audio_stream_per_channel ? _audio_channels : 1;
370         int const channels_per_stream = _audio_stream_per_channel ? 1 : _audio_channels;
371
372         for (int i = 0; i < streams; ++i) {
373                 _audio_streams.push_back(
374                         shared_ptr<ExportAudioStream>(
375                                 new ExportAudioStream(_audio_codec_name, channels_per_stream, _audio_frame_rate, _sample_format, _format_context, _audio_stream_index_base + i)
376                                 )
377                         );
378         }
379 }
380
381
382 void
383 FFmpegFileEncoder::flush ()
384 {
385         if (_pending_audio->frames() > 0) {
386                 audio_frame (_pending_audio->frames ());
387         }
388
389         bool flushed_video = false;
390         bool flushed_audio = false;
391
392         while (!flushed_video || !flushed_audio) {
393                 AVPacket packet;
394                 av_init_packet (&packet);
395                 packet.data = 0;
396                 packet.size = 0;
397
398                 int got_packet;
399 DCPOMATIC_DISABLE_WARNINGS
400                 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
401 DCPOMATIC_ENABLE_WARNINGS
402                 if (got_packet) {
403                         packet.stream_index = 0;
404                         av_interleaved_write_frame (_format_context, &packet);
405                 } else {
406                         flushed_video = true;
407                 }
408                 av_packet_unref (&packet);
409
410                 flushed_audio = true;
411                 BOOST_FOREACH (shared_ptr<ExportAudioStream> i, _audio_streams) {
412                         if (!i->flush()) {
413                                 flushed_audio = false;
414                         }
415                 }
416         }
417
418         av_write_trailer (_format_context);
419 }
420
421 void
422 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
423 {
424         /* All our output formats are video range at the moment */
425         shared_ptr<Image> image = video->image (
426                 bind (&PlayerVideo::force, _1, _pixel_format),
427                 VIDEO_RANGE_VIDEO,
428                 true,
429                 false
430                 );
431
432         AVFrame* frame = av_frame_alloc ();
433         DCPOMATIC_ASSERT (frame);
434
435         {
436                 boost::mutex::scoped_lock lm (_pending_images_mutex);
437                 _pending_images[image->data()[0]] = image;
438         }
439
440         for (int i = 0; i < 3; ++i) {
441                 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
442                 frame->buf[i] = av_buffer_ref (buffer);
443                 frame->data[i] = buffer->data;
444                 frame->linesize[i] = image->stride()[i];
445                 av_buffer_unref (&buffer);
446         }
447
448         frame->width = image->size().width;
449         frame->height = image->size().height;
450         frame->format = _pixel_format;
451         DCPOMATIC_ASSERT (_video_stream->time_base.num == 1);
452         frame->pts = time.get() * _video_stream->time_base.den / DCPTime::HZ;
453
454         AVPacket packet;
455         av_init_packet (&packet);
456         packet.data = 0;
457         packet.size = 0;
458
459         int got_packet;
460 DCPOMATIC_DISABLE_WARNINGS
461         if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
462                 throw EncodeError ("FFmpeg video encode failed");
463         }
464 DCPOMATIC_ENABLE_WARNINGS
465
466         if (got_packet && packet.size) {
467                 packet.stream_index = _video_stream_index;
468                 av_interleaved_write_frame (_format_context, &packet);
469                 av_packet_unref (&packet);
470         }
471
472         av_frame_free (&frame);
473
474 }
475
476 /** Called when the player gives us some audio */
477 void
478 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
479 {
480         _pending_audio->append (audio);
481
482         DCPOMATIC_ASSERT (!_audio_streams.empty());
483         int frame_size = _audio_streams[0]->frame_size();
484         if (frame_size == 0) {
485                 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
486                 frame_size = _audio_frame_rate / _video_frame_rate;
487         }
488
489         while (_pending_audio->frames() >= frame_size) {
490                 audio_frame (frame_size);
491         }
492 }
493
494 void
495 FFmpegFileEncoder::audio_frame (int size)
496 {
497         if (_audio_stream_per_channel) {
498                 int offset = 0;
499                 BOOST_FOREACH (shared_ptr<ExportAudioStream> i, _audio_streams) {
500                         i->write (size, offset, 1, _pending_audio->data(), _audio_frames);
501                         ++offset;
502                 }
503         } else {
504                 DCPOMATIC_ASSERT (!_audio_streams.empty());
505                 DCPOMATIC_ASSERT (_pending_audio->channels());
506                 _audio_streams[0]->write (size, 0, _pending_audio->channels(), _pending_audio->data(), _audio_frames);
507         }
508
509         _pending_audio->trim_start (size);
510         _audio_frames += size;
511 }
512
513 void
514 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)
515 {
516
517 }
518
519 void
520 FFmpegFileEncoder::buffer_free (void* opaque, uint8_t* data)
521 {
522         reinterpret_cast<FFmpegFileEncoder*>(opaque)->buffer_free2(data);
523 }
524
525 void
526 FFmpegFileEncoder::buffer_free2 (uint8_t* data)
527 {
528         boost::mutex::scoped_lock lm (_pending_images_mutex);
529         if (_pending_images.find(data) != _pending_images.end()) {
530                 _pending_images.erase (data);
531         }
532 }