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