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