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