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