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