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