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