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