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