Add some code to help with profiling the player.
[dcpomatic.git] / src / lib / ffmpeg_file_encoder.cc
1 /*
2     Copyright (C) 2017-2018 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 FFmpegFileEncoder::_video_stream_index = 0;
44 int FFmpegFileEncoder::_audio_stream_index = 1;
45
46 static AVPixelFormat
47 force_pixel_format (AVPixelFormat, AVPixelFormat out)
48 {
49         return out;
50 }
51
52 FFmpegFileEncoder::FFmpegFileEncoder (
53         dcp::Size video_frame_size,
54         int video_frame_rate,
55         int audio_frame_rate,
56         int channels,
57         shared_ptr<Log> log,
58         ExportFormat format,
59         int x264_crf,
60         boost::filesystem::path output
61         )
62         : _video_options (0)
63         , _audio_channels (channels)
64         , _output (output)
65         , _video_frame_size (video_frame_size)
66         , _video_frame_rate (video_frame_rate)
67         , _audio_frame_rate (audio_frame_rate)
68         , _log (log)
69 {
70         switch (format) {
71         case EXPORT_FORMAT_PRORES:
72                 _pixel_format = AV_PIX_FMT_YUV422P10;
73                 _sample_format = AV_SAMPLE_FMT_S16;
74                 _video_codec_name = "prores_ks";
75                 _audio_codec_name = "pcm_s16le";
76                 av_dict_set (&_video_options, "profile", "3", 0);
77                 av_dict_set (&_video_options, "threads", "auto", 0);
78                 break;
79         case EXPORT_FORMAT_H264:
80                 _pixel_format = AV_PIX_FMT_YUV420P;
81                 _sample_format = AV_SAMPLE_FMT_FLTP;
82                 _video_codec_name = "libx264";
83                 _audio_codec_name = "aac";
84                 av_dict_set_int (&_video_options, "crf", x264_crf, 0);
85                 break;
86         }
87
88         setup_video ();
89         setup_audio ();
90
91         avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
92         if (!_format_context) {
93                 throw runtime_error ("could not allocate FFmpeg format context");
94         }
95
96         _video_stream = avformat_new_stream (_format_context, _video_codec);
97         if (!_video_stream) {
98                 throw runtime_error ("could not create FFmpeg output video stream");
99         }
100
101         _audio_stream = avformat_new_stream (_format_context, _audio_codec);
102         if (!_audio_stream) {
103                 throw runtime_error ("could not create FFmpeg output audio stream");
104         }
105
106         _video_stream->id = _video_stream_index;
107         _video_stream->codec = _video_codec_context;
108
109         _audio_stream->id = _audio_stream_index;
110         _audio_stream->codec = _audio_codec_context;
111
112         if (avcodec_open2 (_video_codec_context, _video_codec, &_video_options) < 0) {
113                 throw runtime_error ("could not open FFmpeg video codec");
114         }
115
116         int r = avcodec_open2 (_audio_codec_context, _audio_codec, 0);
117         if (r < 0) {
118                 char buffer[256];
119                 av_strerror (r, buffer, sizeof(buffer));
120                 throw runtime_error (String::compose ("could not open FFmpeg audio codec (%1)", buffer));
121         }
122
123         if (avio_open_boost (&_format_context->pb, _output, AVIO_FLAG_WRITE) < 0) {
124                 throw runtime_error ("could not open FFmpeg output file");
125         }
126
127         if (avformat_write_header (_format_context, 0) < 0) {
128                 throw runtime_error ("could not write header to FFmpeg output file");
129         }
130
131         _pending_audio.reset (new AudioBuffers(channels, 0));
132 }
133
134 void
135 FFmpegFileEncoder::setup_video ()
136 {
137         _video_codec = avcodec_find_encoder_by_name (_video_codec_name.c_str());
138         if (!_video_codec) {
139                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _video_codec_name));
140         }
141
142         _video_codec_context = avcodec_alloc_context3 (_video_codec);
143         if (!_video_codec_context) {
144                 throw runtime_error ("could not allocate FFmpeg video context");
145         }
146
147         avcodec_get_context_defaults3 (_video_codec_context, _video_codec);
148
149         /* Variable quantisation */
150         _video_codec_context->global_quality = 0;
151         _video_codec_context->width = _video_frame_size.width;
152         _video_codec_context->height = _video_frame_size.height;
153         _video_codec_context->time_base = (AVRational) { 1, _video_frame_rate };
154         _video_codec_context->pix_fmt = _pixel_format;
155         _video_codec_context->flags |= AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_GLOBAL_HEADER;
156 }
157
158 void
159 FFmpegFileEncoder::setup_audio ()
160 {
161         _audio_codec = avcodec_find_encoder_by_name (_audio_codec_name.c_str());
162         if (!_audio_codec) {
163                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _audio_codec_name));
164         }
165
166         _audio_codec_context = avcodec_alloc_context3 (_audio_codec);
167         if (!_audio_codec_context) {
168                 throw runtime_error ("could not allocate FFmpeg audio context");
169         }
170
171         avcodec_get_context_defaults3 (_audio_codec_context, _audio_codec);
172
173         /* XXX: configurable */
174         _audio_codec_context->bit_rate = 256 * 1024;
175         _audio_codec_context->sample_fmt = _sample_format;
176         _audio_codec_context->sample_rate = _audio_frame_rate;
177         _audio_codec_context->channel_layout = av_get_default_channel_layout (_audio_channels);
178         _audio_codec_context->channels = _audio_channels;
179 }
180
181 void
182 FFmpegFileEncoder::flush ()
183 {
184         if (_pending_audio->frames() > 0) {
185                 audio_frame (_pending_audio->frames ());
186         }
187
188         bool flushed_video = false;
189         bool flushed_audio = false;
190
191         while (!flushed_video || !flushed_audio) {
192                 AVPacket packet;
193                 av_init_packet (&packet);
194                 packet.data = 0;
195                 packet.size = 0;
196
197                 int got_packet;
198                 avcodec_encode_video2 (_video_codec_context, &packet, 0, &got_packet);
199                 if (got_packet) {
200                         packet.stream_index = 0;
201                         av_interleaved_write_frame (_format_context, &packet);
202                 } else {
203                         flushed_video = true;
204                 }
205                 av_packet_unref (&packet);
206
207                 av_init_packet (&packet);
208                 packet.data = 0;
209                 packet.size = 0;
210
211                 avcodec_encode_audio2 (_audio_codec_context, &packet, 0, &got_packet);
212                 if (got_packet) {
213                         packet.stream_index = 0;
214                         av_interleaved_write_frame (_format_context, &packet);
215                 } else {
216                         flushed_audio = true;
217                 }
218                 av_packet_unref (&packet);
219         }
220
221         av_write_trailer (_format_context);
222
223         avcodec_close (_video_codec_context);
224         avcodec_close (_audio_codec_context);
225         avio_close (_format_context->pb);
226         avformat_free_context (_format_context);
227 }
228
229 void
230 FFmpegFileEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
231 {
232         shared_ptr<Image> image = video->image (
233                 boost::optional<dcp::NoteHandler>(bind(&Log::dcp_log, _log.get(), _1, _2)),
234                 bind (&force_pixel_format, _1, _pixel_format),
235                 true,
236                 false
237                 );
238
239         AVFrame* frame = av_frame_alloc ();
240         DCPOMATIC_ASSERT (frame);
241
242         _pending_images[image->data()[0]] = image;
243         for (int i = 0; i < 3; ++i) {
244                 AVBufferRef* buffer = av_buffer_create(image->data()[i], image->stride()[i] * image->size().height, &buffer_free, this, 0);
245                 frame->buf[i] = av_buffer_ref (buffer);
246                 frame->data[i] = buffer->data;
247                 frame->linesize[i] = image->stride()[i];
248                 av_buffer_unref (&buffer);
249         }
250
251         frame->width = image->size().width;
252         frame->height = image->size().height;
253         frame->format = _pixel_format;
254         frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
255
256         AVPacket packet;
257         av_init_packet (&packet);
258         packet.data = 0;
259         packet.size = 0;
260
261         int got_packet;
262         if (avcodec_encode_video2 (_video_codec_context, &packet, frame, &got_packet) < 0) {
263                 throw EncodeError ("FFmpeg video encode failed");
264         }
265
266         if (got_packet && packet.size) {
267                 packet.stream_index = _video_stream_index;
268                 av_interleaved_write_frame (_format_context, &packet);
269                 av_packet_unref (&packet);
270         }
271
272         av_frame_free (&frame);
273
274 }
275
276 /** Called when the player gives us some audio */
277 void
278 FFmpegFileEncoder::audio (shared_ptr<AudioBuffers> audio)
279 {
280         _pending_audio->append (audio);
281
282         int frame_size = _audio_codec_context->frame_size;
283         if (frame_size == 0) {
284                 /* codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE */
285                 frame_size = _audio_frame_rate / _video_frame_rate;
286         }
287
288         while (_pending_audio->frames() >= frame_size) {
289                 audio_frame (frame_size);
290         }
291 }
292
293 void
294 FFmpegFileEncoder::audio_frame (int size)
295 {
296         DCPOMATIC_ASSERT (size);
297
298         AVFrame* frame = av_frame_alloc ();
299         DCPOMATIC_ASSERT (frame);
300
301         int const channels = _pending_audio->channels();
302         DCPOMATIC_ASSERT (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; ++j) {
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 FFmpegFileEncoder::subtitle (PlayerText, DCPTimePeriod)
363 {
364
365 }
366
367 void
368 FFmpegFileEncoder::buffer_free (void* opaque, uint8_t* data)
369 {
370         reinterpret_cast<FFmpegFileEncoder*>(opaque)->buffer_free2(data);
371 }
372
373 void
374 FFmpegFileEncoder::buffer_free2 (uint8_t* data)
375 {
376         _pending_images.erase (data);
377 }