C++11 tidying.
[dcpomatic.git] / src / lib / ffmpeg_file_encoder.cc
1 /*
2     Copyright (C) 2017-2021 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
22 #include "ffmpeg_encoder.h"
23 #include "ffmpeg_wrapper.h"
24 #include "film.h"
25 #include "job.h"
26 #include "player.h"
27 #include "player_video.h"
28 #include "log.h"
29 #include "image.h"
30 #include "cross.h"
31 #include "compose.hpp"
32 #include <iostream>
33
34 #include "i18n.h"
35
36
37 using std::cout;
38 using std::make_shared;
39 using std::pair;
40 using std::runtime_error;
41 using std::shared_ptr;
42 using std::string;
43 using std::weak_ptr;
44 using boost::bind;
45 using boost::optional;
46 using namespace dcpomatic;
47 #if BOOST_VERSION >= 106100
48 using namespace boost::placeholders;
49 #endif
50
51
52 int FFmpegFileEncoder::_video_stream_index = 0;
53 int FFmpegFileEncoder::_audio_stream_index_base = 1;
54
55
56 class ExportAudioStream
57 {
58 public:
59         ExportAudioStream (string codec_name, int channels, int frame_rate, AVSampleFormat sample_format, AVFormatContext* format_context, int stream_index)
60                 : _format_context (format_context)
61                 , _stream_index (stream_index)
62         {
63                 _codec = avcodec_find_encoder_by_name (codec_name.c_str());
64                 if (!_codec) {
65                         throw EncodeError (String::compose("avcodec_find_encoder_by_name failed for %1", codec_name));
66                 }
67
68                 _codec_context = avcodec_alloc_context3 (_codec);
69                 if (!_codec_context) {
70                         throw std::bad_alloc ();
71                 }
72
73                 /* XXX: configurable */
74                 _codec_context->bit_rate = channels * 128 * 1024;
75                 _codec_context->sample_fmt = sample_format;
76                 _codec_context->sample_rate = frame_rate;
77                 _codec_context->channel_layout = av_get_default_channel_layout (channels);
78                 _codec_context->channels = channels;
79
80                 int r = avcodec_open2 (_codec_context, _codec, 0);
81                 if (r < 0) {
82                         throw EncodeError (N_("avcodec_open2"), N_("ExportAudioStream::ExportAudioStream"), r);
83                 }
84
85                 _stream = avformat_new_stream (format_context, _codec);
86                 if (!_stream) {
87                         throw EncodeError (N_("avformat_new_stream"), N_("ExportAudioStream::ExportAudioStream"));
88                 }
89
90                 _stream->id = stream_index;
91                 _stream->disposition |= AV_DISPOSITION_DEFAULT;
92                 r = avcodec_parameters_from_context (_stream->codecpar, _codec_context);
93                 if (r < 0) {
94                         throw EncodeError (N_("avcodec_parameters_from_context"), N_("ExportAudioStream::ExportAudioStream"), r);
95                 }
96         }
97
98         ~ExportAudioStream ()
99         {
100                 avcodec_close (_codec_context);
101         }
102
103         ExportAudioStream (ExportAudioStream const&) = delete;
104         ExportAudioStream& operator= (ExportAudioStream const&) = delete;
105
106         int frame_size () const {
107                 return _codec_context->frame_size;
108         }
109
110         bool flush ()
111         {
112                 int r = avcodec_send_frame (_codec_context, nullptr);
113                 if (r < 0 && r != AVERROR_EOF) {
114                         /* We get EOF if we've already flushed the stream once */
115                         throw EncodeError (N_("avcodec_send_frame"), N_("ExportAudioStream::flush"), r);
116                 }
117
118                 ffmpeg::Packet packet;
119                 r = avcodec_receive_packet (_codec_context, packet.get());
120                 if (r == AVERROR_EOF) {
121                         return true;
122                 } else if (r < 0) {
123                         throw EncodeError (N_("avcodec_receive_packet"), N_("ExportAudioStream::flush"), r);
124                 }
125
126                 packet->stream_index = _stream_index;
127                 av_interleaved_write_frame (_format_context, packet.get());
128                 return false;
129         }
130
131         void write (int size, int channel_offset, int channels, float** data, int64_t sample_offset)
132         {
133                 DCPOMATIC_ASSERT (size);
134
135                 auto frame = av_frame_alloc ();
136                 DCPOMATIC_ASSERT (frame);
137
138                 int const buffer_size = av_samples_get_buffer_size (0, channels, size, _codec_context->sample_fmt, 0);
139                 DCPOMATIC_ASSERT (buffer_size >= 0);
140
141                 auto samples = av_malloc (buffer_size);
142                 DCPOMATIC_ASSERT (samples);
143
144                 frame->nb_samples = size;
145                 frame->format = _codec_context->sample_fmt;
146                 frame->channels = channels;
147                 int r = avcodec_fill_audio_frame (frame, channels, _codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
148                 DCPOMATIC_ASSERT (r >= 0);
149
150                 switch (_codec_context->sample_fmt) {
151                 case AV_SAMPLE_FMT_S16:
152                 {
153                         int16_t* q = reinterpret_cast<int16_t*> (samples);
154                         for (int i = 0; i < size; ++i) {
155                                 for (int j = 0; j < channels; ++j) {
156                                         *q++ = data[j + channel_offset][i] * 32767;
157                                 }
158                         }
159                         break;
160                 }
161                 case AV_SAMPLE_FMT_S32:
162                 {
163                         int32_t* q = reinterpret_cast<int32_t*> (samples);
164                         for (int i = 0; i < size; ++i) {
165                                 for (int j = 0; j < channels; ++j) {
166                                         *q++ = data[j + channel_offset][i] * 2147483647;
167                                 }
168                         }
169                         break;
170                 }
171                 case AV_SAMPLE_FMT_FLTP:
172                 {
173                         float* q = reinterpret_cast<float*> (samples);
174                         for (int i = 0; i < channels; ++i) {
175                                 memcpy (q, data[i + channel_offset], sizeof(float) * size);
176                                 q += size;
177                         }
178                         break;
179                 }
180                 default:
181                         DCPOMATIC_ASSERT (false);
182                 }
183
184                 DCPOMATIC_ASSERT (_codec_context->time_base.num == 1);
185                 frame->pts = sample_offset * _codec_context->time_base.den / _codec_context->sample_rate;
186
187                 r = avcodec_send_frame (_codec_context, frame);
188                 av_free (samples);
189                 av_frame_free (&frame);
190                 if (r < 0) {
191                         throw EncodeError (N_("avcodec_send_frame"), N_("ExportAudioStream::write"), r);
192                 }
193
194                 ffmpeg::Packet packet;
195                 r = avcodec_receive_packet (_codec_context, packet.get());
196                 if (r < 0 && r != AVERROR(EAGAIN)) {
197                         throw EncodeError (N_("avcodec_receive_packet"), N_("ExportAudioStream::write"), r);
198                 } else if (r >= 0) {
199                         packet->stream_index = _stream_index;
200                         av_interleaved_write_frame (_format_context, packet.get());
201                 }
202         }
203
204 private:
205         AVFormatContext* _format_context;
206         AVCodec* _codec;
207         AVCodecContext* _codec_context;
208         AVStream* _stream;
209         int _stream_index;
210 };
211
212
213 FFmpegFileEncoder::FFmpegFileEncoder (
214         dcp::Size video_frame_size,
215         int video_frame_rate,
216         int audio_frame_rate,
217         int channels,
218         ExportFormat format,
219         bool audio_stream_per_channel,
220         int x264_crf,
221         boost::filesystem::path output
222         )
223         : _audio_stream_per_channel (audio_stream_per_channel)
224         , _audio_channels (channels)
225         , _output (output)
226         , _video_frame_size (video_frame_size)
227         , _video_frame_rate (video_frame_rate)
228         , _audio_frame_rate (audio_frame_rate)
229 {
230         _pixel_format = pixel_format (format);
231
232         switch (format) {
233         case ExportFormat::PRORES:
234                 _sample_format = AV_SAMPLE_FMT_S16;
235                 _video_codec_name = "prores_ks";
236                 _audio_codec_name = "pcm_s16le";
237                 av_dict_set (&_video_options, "profile", "3", 0);
238                 av_dict_set (&_video_options, "threads", "auto", 0);
239                 break;
240         case ExportFormat::H264_AAC:
241                 _sample_format = AV_SAMPLE_FMT_FLTP;
242                 _video_codec_name = "libx264";
243                 _audio_codec_name = "aac";
244                 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
245                 break;
246         case ExportFormat::H264_PCM:
247                 _sample_format = AV_SAMPLE_FMT_S32;
248                 _video_codec_name = "libx264";
249                 _audio_codec_name = "pcm_s24le";
250                 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
251                 break;
252         default:
253                 DCPOMATIC_ASSERT (false);
254         }
255
256         int r = avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
257         if (!_format_context) {
258                 throw EncodeError (N_("avformat_alloc_output_context2"), "FFmpegFileEncoder::FFmpegFileEncoder", r);
259         }
260
261         setup_video ();
262         setup_audio ();
263
264         r = avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE);
265         if (r < 0) {
266                 throw EncodeError (String::compose(_("Could not open output file %1 (%2)"), _output.string(), r));
267         }
268
269         AVDictionary* options = nullptr;
270
271         r = avformat_write_header (_format_context, &options);
272         if (r < 0) {
273                 throw EncodeError (N_("avformat_write_header"), N_("FFmpegFileEncoder::FFmpegFileEncoder"), r);
274         }
275
276         _pending_audio.reset (new AudioBuffers(channels, 0));
277 }
278
279
280 FFmpegFileEncoder::~FFmpegFileEncoder ()
281 {
282         _audio_streams.clear ();
283         avcodec_close (_video_codec_context);
284         avformat_free_context (_format_context);
285 }
286
287
288 AVPixelFormat
289 FFmpegFileEncoder::pixel_format (ExportFormat format)
290 {
291         switch (format) {
292         case ExportFormat::PRORES:
293                 return AV_PIX_FMT_YUV422P10;
294         case ExportFormat::H264_AAC:
295         case ExportFormat::H264_PCM:
296                 return AV_PIX_FMT_YUV420P;
297         default:
298                 DCPOMATIC_ASSERT (false);
299         }
300
301         return AV_PIX_FMT_YUV422P10;
302 }
303
304
305 void
306 FFmpegFileEncoder::setup_video ()
307 {
308         _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
309         if (!_video_codec) {
310                 throw EncodeError (String::compose("avcodec_find_encoder_by_name failed for %1", _video_codec_name));
311         }
312
313         _video_codec_context = avcodec_alloc_context3 (_video_codec);
314         if (!_video_codec_context) {
315                 throw std::bad_alloc ();
316         }
317
318         /* Variable quantisation */
319         _video_codec_context->global_quality = 0;
320         _video_codec_context->width = _video_frame_size.width;
321         _video_codec_context->height = _video_frame_size.height;
322         _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
323         _video_codec_context->pix_fmt = _pixel_format;
324         _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
325
326         if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
327                 throw EncodeError (N_("avcodec_open"), N_("FFmpegFileEncoder::setup_video"));
328         }
329
330         _video_stream = avformat_new_stream (_format_context, _video_codec);
331         if (!_video_stream) {
332                 throw EncodeError (N_("avformat_new_stream"), N_("FFmpegFileEncoder::setup_video"));
333         }
334
335         _video_stream->id = _video_stream_index;
336         int r = avcodec_parameters_from_context (_video_stream->codecpar, _video_codec_context);
337         if (r < 0) {
338                 throw EncodeError (N_("avcodec_parameters_from_context"), N_("FFmpegFileEncoder::setup_video"), r);
339         }
340 }
341
342
343 void
344 FFmpegFileEncoder::setup_audio ()
345 {
346         int const streams = _audio_stream_per_channel ? _audio_channels : 1;
347         int const channels_per_stream = _audio_stream_per_channel ? 1 : _audio_channels;
348
349         for (int i = 0; i < streams; ++i) {
350                 _audio_streams.push_back(
351                         make_shared<ExportAudioStream>(
352                                 _audio_codec_name, channels_per_stream, _audio_frame_rate, _sample_format, _format_context, _audio_stream_index_base + i
353                                 )
354                         );
355         }
356 }
357
358
359 void
360 FFmpegFileEncoder::flush ()
361 {
362         if (_pending_audio->frames() > 0) {
363                 audio_frame (_pending_audio->frames ());
364         }
365
366         bool flushed_video = false;
367         bool flushed_audio = false;
368
369         while (!flushed_video || !flushed_audio) {
370                 int r = avcodec_send_frame (_video_codec_context, nullptr);
371                 if (r < 0 && r != AVERROR_EOF) {
372                         /* We get EOF if we've already flushed the stream once */
373                         throw EncodeError (N_("avcodec_send_frame"), N_("FFmpegFileEncoder::flush"), r);
374                 }
375
376                 ffmpeg::Packet packet;
377                 r = avcodec_receive_packet (_video_codec_context, packet.get());
378                 if (r == AVERROR_EOF) {
379                         flushed_video = true;
380                 } else if (r < 0) {
381                         throw EncodeError (N_("avcodec_receive_packet"), N_("FFmpegFileEncoder::flush"), r);
382                 } else {
383                         packet->stream_index = _video_stream_index;
384                         av_interleaved_write_frame (_format_context, packet.get());
385                 }
386
387                 flushed_audio = true;
388                 for (auto i: _audio_streams) {
389                         if (!i->flush()) {
390                                 flushed_audio = false;
391                         }
392                 }
393         }
394
395         av_write_trailer (_format_context);
396 }
397
398
399 void
400 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
401 {
402         /* All our output formats are video range at the moment */
403         auto image = video->image (
404                 bind (&PlayerVideo::force, _1, _pixel_format),
405                 VideoRange::VIDEO,
406                 true,
407                 false
408                 );
409
410         auto frame = av_frame_alloc ();
411         DCPOMATIC_ASSERT (frame);
412
413         {
414                 boost::mutex::scoped_lock lm (_pending_images_mutex);
415                 _pending_images[image->data()[0]] = image;
416         }
417
418         for (int i = 0; i < 3; ++i) {
419                 auto buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
420                 frame->buf[i] = av_buffer_ref (buffer);
421                 frame->data[i] = buffer->data;
422                 frame->linesize[i] = image->stride()[i];
423                 av_buffer_unref (&buffer);
424         }
425
426         frame->width = image->size().width;
427         frame->height = image->size().height;
428         frame->format = _pixel_format;
429         DCPOMATIC_ASSERT (_video_stream->time_base.num == 1);
430         frame->pts = time.get() * _video_stream->time_base.den / DCPTime::HZ;
431
432         int r = avcodec_send_frame (_video_codec_context, frame);
433         av_frame_free (&frame);
434         if (r < 0) {
435                 throw EncodeError (N_("avcodec_send_frame"), N_("FFmpegFileEncoder::video"), r);
436         }
437
438         ffmpeg::Packet packet;
439         r = avcodec_receive_packet (_video_codec_context, packet.get());
440         if (r < 0 && r != AVERROR(EAGAIN)) {
441                 throw EncodeError (N_("avcodec_receive_packet"), N_("FFmpegFileEncoder::video"), r);
442         } else if (r >= 0) {
443                 packet->stream_index = _video_stream_index;
444                 av_interleaved_write_frame (_format_context, packet.get());
445         }
446 }
447
448
449 /** Called when the player gives us some audio */
450 void
451 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
452 {
453         _pending_audio->append (audio);
454
455         DCPOMATIC_ASSERT (!_audio_streams.empty());
456         int frame_size = _audio_streams[0]->frame_size();
457         if (frame_size == 0) {
458                 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
459                 frame_size = _audio_frame_rate / _video_frame_rate;
460         }
461
462         while (_pending_audio->frames() >= frame_size) {
463                 audio_frame (frame_size);
464         }
465 }
466
467
468 void
469 FFmpegFileEncoder::audio_frame (int size)
470 {
471         if (_audio_stream_per_channel) {
472                 int offset = 0;
473                 for (auto i: _audio_streams) {
474                         i->write (size, offset, 1, _pending_audio->data(), _audio_frames);
475                         ++offset;
476                 }
477         } else {
478                 DCPOMATIC_ASSERT (!_audio_streams.empty());
479                 DCPOMATIC_ASSERT (_pending_audio->channels());
480                 _audio_streams[0]->write (size, 0, _pending_audio->channels(), _pending_audio->data(), _audio_frames);
481         }
482
483         _pending_audio->trim_start (size);
484         _audio_frames += size;
485 }
486
487
488 void
489 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)
490 {
491
492 }
493
494
495 void
496 FFmpegFileEncoder::buffer_free (void* opaque, uint8_t* data)
497 {
498         reinterpret_cast<FFmpegFileEncoder*>(opaque)->buffer_free2(data);
499 }
500
501
502 void
503 FFmpegFileEncoder::buffer_free2 (uint8_t* data)
504 {
505         boost::mutex::scoped_lock lm (_pending_images_mutex);
506         if (_pending_images.find(data) != _pending_images.end()) {
507                 _pending_images.erase (data);
508         }
509 }