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