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