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