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