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