Partial conversion of PlayerSubtitles -> PlayerText and SubtitleString -> PlainText.
[dcpomatic.git] / src / lib / ffmpeg_encoder.cc
1 /*
2     Copyright (C) 2017 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 "butler.h"
30 #include "compose.hpp"
31 #include <iostream>
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::runtime_error;
37 using std::cout;
38 using std::pair;
39 using boost::shared_ptr;
40 using boost::bind;
41 using boost::weak_ptr;
42
43 int FFmpegEncoder::_video_stream_index = 0;
44 int FFmpegEncoder::_audio_stream_index = 1;
45
46 static AVPixelFormat
47 force_pixel_format (AVPixelFormat, AVPixelFormat out)
48 {
49         return out;
50 }
51
52 FFmpegEncoder::FFmpegEncoder (shared_ptr<const Film> film, weak_ptr<Job> job, boost::filesystem::path output, Format format, bool mixdown_to_stereo)
53         : Encoder (film, job)
54         , _video_options (0)
55         , _history (1000)
56         , _output (output)
57 {
58         switch (format) {
59         case FORMAT_PRORES:
60                 _pixel_format = AV_PIX_FMT_YUV422P10;
61                 _sample_format = AV_SAMPLE_FMT_S16;
62                 _video_codec_name = "prores_ks";
63                 _audio_codec_name = "pcm_s16le";
64                 av_dict_set (&_video_options, "profile", "3", 0);
65                 av_dict_set (&_video_options, "threads", "auto", 0);
66                 break;
67         case FORMAT_H264:
68                 _pixel_format = AV_PIX_FMT_YUV420P;
69                 _sample_format = AV_SAMPLE_FMT_FLTP;
70                 _video_codec_name = "libx264";
71                 _audio_codec_name = "aac";
72                 break;
73         }
74
75         _player->set_always_burn_subtitles (true);
76         _player->set_play_referenced ();
77
78         int const ch = film->audio_channels ();
79
80         AudioMapping map;
81         if (mixdown_to_stereo) {
82                 _output_audio_channels = 2;
83                 map = AudioMapping (ch, 2);
84                 float const overall_gain = 2 / (4 + sqrt(2));
85                 float const minus_3dB = 1 / sqrt(2);
86                 map.set (dcp::LEFT,   0, overall_gain);
87                 map.set (dcp::RIGHT,  1, overall_gain);
88                 map.set (dcp::CENTRE, 0, overall_gain * minus_3dB);
89                 map.set (dcp::CENTRE, 1, overall_gain * minus_3dB);
90                 map.set (dcp::LS,     0, overall_gain);
91                 map.set (dcp::RS,     1, overall_gain);
92                 _pending_audio.reset (new AudioBuffers (2, 0));
93         } else {
94                 _output_audio_channels = ch;
95                 map = AudioMapping (ch, ch);
96                 _pending_audio.reset (new AudioBuffers (ch, 0));
97                 for (int i = 0; i < ch; ++i) {
98                         map.set (i, i, 1);
99                 }
100         }
101
102         _butler.reset (new Butler (_player, film->log(), map, _output_audio_channels));
103 }
104
105 void
106 FFmpegEncoder::setup_video ()
107 {
108         _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
109         if (!_video_codec) {
110                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
111         }
112
113         _video_codec_context = avcodec_alloc_context3 (_video_codec);
114         if (!_video_codec_context) {
115                 throw runtime_error ("could not allocate FFmpeg video context");
116         }
117
118         avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
119
120         /* Variable quantisation */
121         _video_codec_context->global_quality = 0;
122         _video_codec_context->width = _film->frame_size().width;
123         _video_codec_context->height = _film->frame_size().height;
124         _video_codec_context->time_base = (AVRational) { 1, _film->video_frame_rate() };
125         _video_codec_context->pix_fmt = _pixel_format;
126         _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
127 }
128
129 void
130 FFmpegEncoder::setup_audio ()
131 {
132         _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
133         if (!_audio_codec) {
134                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
135         }
136
137         _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
138         if (!_audio_codec_context) {
139                 throw runtime_error ("could not allocate FFmpeg audio context");
140         }
141
142         avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
143
144         /* XXX: configurable */
145         _audio_codec_context->bit_rate = 256 * 1024;
146         _audio_codec_context->sample_fmt = _sample_format;
147         _audio_codec_context->sample_rate = _film->audio_frame_rate ();
148         _audio_codec_context->channel_layout = av_get_default_channel_layout (_output_audio_channels);
149         _audio_codec_context->channels = _output_audio_channels;
150 }
151
152 void
153 FFmpegEncoder::go ()
154 {
155         setup_video ();
156         setup_audio ();
157
158         avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
159         if (!_format_context) {
160                 throw runtime_error ("could not allocate FFmpeg format context");
161         }
162
163         _video_stream = avformat_new_stream (_format_context, _video_codec);
164         if (!_video_stream) {
165                 throw runtime_error ("could not create FFmpeg output video stream");
166         }
167
168         _audio_stream = avformat_new_stream (_format_context, _audio_codec);
169         if (!_audio_stream) {
170                 throw runtime_error ("could not create FFmpeg output audio stream");
171         }
172
173         _video_stream->id = _video_stream_index;
174         _video_stream->codec = _video_codec_context;
175
176         _audio_stream->id = _audio_stream_index;
177         _audio_stream->codec = _audio_codec_context;
178
179         if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
180                 throw runtime_error ("could not open FFmpeg video codec");
181         }
182
183         int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
184         if (r < 0) {
185                 char buffer[256];
186                 av_strerror (r, buffer, sizeof(buffer));
187                 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
188         }
189
190         if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
191                 throw runtime_error ("could not open FFmpeg output file");
192         }
193
194         if (avformat_write_header (_format_context, 0) < 0) {
195                 throw runtime_error ("could not write header to FFmpeg output file");
196         }
197
198         {
199                 shared_ptr<Job> job = _job.lock ();
200                 DCPOMATIC_ASSERT (job);
201                 job->sub (_("Encoding"));
202         }
203
204         DCPTime const video_frame = DCPTime::from_frames (1, _film->video_frame_rate ());
205         int const audio_frames = video_frame.frames_round(_film->audio_frame_rate());
206         float* interleaved = new float[_output_audio_channels * audio_frames];
207         shared_ptr<AudioBuffers> deinterleaved (new AudioBuffers (_output_audio_channels, audio_frames));
208         for (DCPTime i; i < _film->length(); i += video_frame) {
209                 pair<shared_ptr<PlayerVideo>, DCPTime> v = _butler->get_video ();
210                 video (v.first, v.second);
211                 _butler->get_audio (interleaved, audio_frames);
212                 /* XXX: inefficient; butler interleaves and we deinterleave again */
213                 float* p = interleaved;
214                 for (int j = 0; j < audio_frames; ++j) {
215                         for (int k = 0; k < _output_audio_channels; ++k) {
216                                 deinterleaved->data(k)[j] = *p++;
217                         }
218                 }
219                 audio (deinterleaved);
220         }
221         delete[] interleaved;
222
223         if (_pending_audio->frames() > 0) {
224                 audio_frame (_pending_audio->frames ());
225         }
226
227         /* Flush */
228
229         bool flushed_video = false;
230         bool flushed_audio = false;
231
232         while (!flushed_video || !flushed_audio) {
233                 AVPacket packet;
234                 av_init_packet (&packet);
235                 packet.data = 0;
236                 packet.size = 0;
237
238                 int got_packet;
239                 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
240                 if (got_packet) {
241                         packet.stream_index = 0;
242                         av_interleaved_write_frame (_format_context, &packet);
243                 } else {
244                         flushed_video = true;
245                 }
246                 av_packet_unref (&packet);
247
248                 av_init_packet (&packet);
249                 packet.data = 0;
250                 packet.size = 0;
251
252                 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
253                 if (got_packet) {
254                         packet.stream_index = 0;
255                         av_interleaved_write_frame (_format_context, &packet);
256                 } else {
257                         flushed_audio = true;
258                 }
259                 av_packet_unref (&packet);
260         }
261
262         av_write_trailer (_format_context);
263
264         avcodec_close (_video_codec_context);
265         avcodec_close (_audio_codec_context);
266         avio_close (_format_context->pb);
267         avformat_free_context (_format_context);
268 }
269
270 void
271 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
272 {
273         shared_ptr<Image> image = video->image (
274                 bind (&Log::dcp_log, _film->log().get(), _1, _2),
275                 bind (&force_pixel_format, _1, _pixel_format),
276                 true,
277                 false
278                 );
279
280         AVFrame* frame = av_frame_alloc ();
281         DCPOMATIC_ASSERT (frame);
282
283         _pending_images[image->data()[0]] = image;
284         for (int i = 0; i < 3; ++i) {
285                 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
286                 frame->buf[i] = av_buffer_ref (buffer);
287                 frame->data[i] = buffer->data;
288                 frame->linesize[i] = image->stride()[i];
289                 av_buffer_unref (&buffer);
290         }
291
292         frame->width = image->size().width;
293         frame->height = image->size().height;
294         frame->format = _pixel_format;
295         frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
296
297         AVPacket packet;
298         av_init_packet (&packet);
299         packet.data = 0;
300         packet.size = 0;
301
302         int got_packet;
303         if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
304                 throw EncodeError ("FFmpeg video encode failed");
305         }
306
307         if (got_packet && packet.size) {
308                 packet.stream_index = _video_stream_index;
309                 av_interleaved_write_frame (_format_context, &packet);
310                 av_packet_unref (&packet);
311         }
312
313         av_frame_free (&frame);
314
315         _history.event ();
316
317         {
318                 boost::mutex::scoped_lock lm (_mutex);
319                 _last_time = time;
320         }
321
322         shared_ptr<Job> job = _job.lock ();
323         if (job) {
324                 job->set_progress (float(time.get()) / _film->length().get());
325         }
326 }
327
328 /** Called when the player gives us some audio */
329 void
330 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio)
331 {
332         _pending_audio->append (audio);
333
334         int frame_size = _audio_codec_context->frame_size;
335         if (frame_size == 0) {
336                 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
337                 frame_size = _film->audio_frame_rate() / _film->video_frame_rate();
338         }
339
340         while (_pending_audio->frames() >= frame_size) {
341                 audio_frame (frame_size);
342         }
343 }
344
345 void
346 FFmpegEncoder::audio_frame (int size)
347 {
348         DCPOMATIC_ASSERT (size);
349
350         AVFrame* frame = av_frame_alloc ();
351         DCPOMATIC_ASSERT (frame);
352
353         int const channels = _pending_audio->channels();
354         DCPOMATIC_ASSERT (channels);
355
356         int const buffer_size = av_samples_get_buffer_size (0, channels, size, _audio_codec_context->sample_fmt, 0);
357         DCPOMATIC_ASSERT (buffer_size >= 0);
358
359         void* samples = av_malloc (buffer_size);
360         DCPOMATIC_ASSERT (samples);
361
362         frame->nb_samples = size;
363         int r = avcodec_fill_audio_frame (frame, channels, _audio_codec_context->sample_fmt, (const uint8_t *) samples, buffer_size, 0);
364         DCPOMATIC_ASSERT (r >= 0);
365
366         float** p = _pending_audio->data ();
367         switch (_audio_codec_context->sample_fmt) {
368         case AV_SAMPLE_FMT_S16:
369         {
370                 int16_t* q = reinterpret_cast<int16_t*> (samples);
371                 for (int i = 0; i < size; ++i) {
372                         for (int j = 0; j < channels; ++j) {
373                                 *q++ = p[j][i] * 32767;
374                         }
375                 }
376                 break;
377         }
378         case AV_SAMPLE_FMT_FLTP:
379         {
380                 float* q = reinterpret_cast<float*> (samples);
381                 for (int i = 0; i < channels; ++i) {
382                         memcpy (q, p[i], sizeof(float) * size);
383                         q += size;
384                 }
385                 break;
386         }
387         default:
388                 DCPOMATIC_ASSERT (false);
389         }
390
391         AVPacket packet;
392         av_init_packet (&packet);
393         packet.data = 0;
394         packet.size = 0;
395
396         int got_packet;
397         if (avcodec_encode_audio2 (_audio_codec_context, &packet, frame, &got_packet) < 0) {
398                 throw EncodeError ("FFmpeg audio encode failed");
399         }
400
401         if (got_packet && packet.size) {
402                 packet.stream_index = _audio_stream_index;
403                 av_interleaved_write_frame (_format_context, &packet);
404                 av_packet_unref (&packet);
405         }
406
407         av_free (samples);
408         av_frame_free (&frame);
409
410         _pending_audio->trim_start (size);
411 }
412
413 void
414 FFmpegEncoder::subtitle (PlayerText, DCPTimePeriod)
415 {
416
417 }
418
419 float
420 FFmpegEncoder::current_rate () const
421 {
422         return _history.rate ();
423 }
424
425 Frame
426 FFmpegEncoder::frames_done () const
427 {
428         boost::mutex::scoped_lock lm (_mutex);
429         return _last_time.frames_round (_film->video_frame_rate ());
430 }
431
432 void
433 FFmpegEncoder::buffer_free (void* opaque, uint8_t* data)
434 {
435         reinterpret_cast<FFmpegEncoder*>(opaque)->buffer_free2(data);
436 }
437
438 void
439 FFmpegEncoder::buffer_free2 (uint8_t* data)
440 {
441         _pending_images.erase (data);
442 }