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