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