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