e99a960cef4723095ab6017b278f0c5a78a51e95
[dcpomatic.git] / src / lib / ffmpeg_decoder.cc
1 /* -*- c-basic-offset: 8; default-tab-width: 8; -*- */
2
3 /*
4     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
5
6     This program 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     This program 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 this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 */
21
22 /** @file  src/ffmpeg_decoder.cc
23  *  @brief A decoder using FFmpeg to decode content.
24  */
25
26 #include <stdexcept>
27 #include <vector>
28 #include <sstream>
29 #include <iomanip>
30 #include <iostream>
31 #include <stdint.h>
32 #include <boost/lexical_cast.hpp>
33 extern "C" {
34 #include <tiffio.h>
35 #include <libavcodec/avcodec.h>
36 #include <libavformat/avformat.h>
37 #include <libswscale/swscale.h>
38 #include <libpostproc/postprocess.h>
39 }
40 #include <sndfile.h>
41 #include "film.h"
42 #include "format.h"
43 #include "transcoder.h"
44 #include "job.h"
45 #include "filter.h"
46 #include "exceptions.h"
47 #include "image.h"
48 #include "util.h"
49 #include "log.h"
50 #include "ffmpeg_decoder.h"
51 #include "filter_graph.h"
52 #include "subtitle.h"
53 #include "audio_buffers.h"
54
55 #include "i18n.h"
56
57 using std::cout;
58 using std::string;
59 using std::vector;
60 using std::stringstream;
61 using std::list;
62 using boost::shared_ptr;
63 using boost::optional;
64 using boost::dynamic_pointer_cast;
65 using libdcp::Size;
66
67 boost::mutex FFmpegDecoder::_mutex;
68
69 FFmpegDecoder::FFmpegDecoder (shared_ptr<const Film> f, shared_ptr<const FFmpegContent> c, bool video, bool audio, bool subtitles)
70         : Decoder (f)
71         , VideoDecoder (f)
72         , AudioDecoder (f, c)
73         , _ffmpeg_content (c)
74         , _format_context (0)
75         , _video_stream (-1)
76         , _frame (0)
77         , _video_codec_context (0)
78         , _video_codec (0)
79         , _audio_codec_context (0)
80         , _audio_codec (0)
81         , _subtitle_codec_context (0)
82         , _subtitle_codec (0)
83         , _decode_video (video)
84         , _decode_audio (audio)
85         , _decode_subtitles (subtitles)
86 {
87         setup_general ();
88         setup_video ();
89         setup_audio ();
90         setup_subtitle ();
91 }
92
93 FFmpegDecoder::~FFmpegDecoder ()
94 {
95         boost::mutex::scoped_lock lm (_mutex);
96         
97         if (_audio_codec_context) {
98                 avcodec_close (_audio_codec_context);
99         }
100
101         if (_video_codec_context) {
102                 avcodec_close (_video_codec_context);
103         }
104
105         if (_subtitle_codec_context) {
106                 avcodec_close (_subtitle_codec_context);
107         }
108
109         av_free (_frame);
110         
111         avformat_close_input (&_format_context);
112 }       
113
114 void
115 FFmpegDecoder::setup_general ()
116 {
117         av_register_all ();
118
119         if (avformat_open_input (&_format_context, _ffmpeg_content->file().string().c_str(), 0, 0) < 0) {
120                 throw OpenFileError (_ffmpeg_content->file().string ());
121         }
122
123         if (avformat_find_stream_info (_format_context, 0) < 0) {
124                 throw DecodeError (_("could not find stream information"));
125         }
126
127         /* Find video, audio and subtitle streams */
128
129         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
130                 AVStream* s = _format_context->streams[i];
131                 if (s->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
132                         _video_stream = i;
133                 } else if (s->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
134
135                         /* This is a hack; sometimes it seems that _audio_codec_context->channel_layout isn't set up,
136                            so bodge it here.  No idea why we should have to do this.
137                         */
138
139                         if (s->codec->channel_layout == 0) {
140                                 s->codec->channel_layout = av_get_default_channel_layout (s->codec->channels);
141                         }
142                         
143                         _audio_streams.push_back (
144                                 FFmpegAudioStream (stream_name (s), i, s->codec->sample_rate, s->codec->channels)
145                                 );
146                         
147                 } else if (s->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
148                         _subtitle_streams.push_back (FFmpegSubtitleStream (stream_name (s), i));
149                 }
150         }
151
152         if (_video_stream < 0) {
153                 throw DecodeError (N_("could not find video stream"));
154         }
155
156         _frame = avcodec_alloc_frame ();
157         if (_frame == 0) {
158                 throw DecodeError (N_("could not allocate frame"));
159         }
160 }
161
162 void
163 FFmpegDecoder::setup_video ()
164 {
165         boost::mutex::scoped_lock lm (_mutex);
166         
167         _video_codec_context = _format_context->streams[_video_stream]->codec;
168         _video_codec = avcodec_find_decoder (_video_codec_context->codec_id);
169
170         if (_video_codec == 0) {
171                 throw DecodeError (_("could not find video decoder"));
172         }
173
174         if (avcodec_open2 (_video_codec_context, _video_codec, 0) < 0) {
175                 throw DecodeError (N_("could not open video decoder"));
176         }
177 }
178
179 void
180 FFmpegDecoder::setup_audio ()
181 {
182         boost::mutex::scoped_lock lm (_mutex);
183         
184         if (!_ffmpeg_content->audio_stream ()) {
185                 return;
186         }
187
188         _audio_codec_context = _format_context->streams[_ffmpeg_content->audio_stream()->id]->codec;
189         _audio_codec = avcodec_find_decoder (_audio_codec_context->codec_id);
190
191         if (_audio_codec == 0) {
192                 throw DecodeError (_("could not find audio decoder"));
193         }
194
195         if (avcodec_open2 (_audio_codec_context, _audio_codec, 0) < 0) {
196                 throw DecodeError (N_("could not open audio decoder"));
197         }
198 }
199
200 void
201 FFmpegDecoder::setup_subtitle ()
202 {
203         boost::mutex::scoped_lock lm (_mutex);
204         
205         if (!_ffmpeg_content->subtitle_stream() || _ffmpeg_content->subtitle_stream()->id >= int (_format_context->nb_streams)) {
206                 return;
207         }
208
209         _subtitle_codec_context = _format_context->streams[_ffmpeg_content->subtitle_stream()->id]->codec;
210         _subtitle_codec = avcodec_find_decoder (_subtitle_codec_context->codec_id);
211
212         if (_subtitle_codec == 0) {
213                 throw DecodeError (_("could not find subtitle decoder"));
214         }
215         
216         if (avcodec_open2 (_subtitle_codec_context, _subtitle_codec, 0) < 0) {
217                 throw DecodeError (N_("could not open subtitle decoder"));
218         }
219 }
220
221
222 bool
223 FFmpegDecoder::pass ()
224 {
225         int r = av_read_frame (_format_context, &_packet);
226
227         if (r < 0) {
228                 if (r != AVERROR_EOF) {
229                         /* Maybe we should fail here, but for now we'll just finish off instead */
230                         char buf[256];
231                         av_strerror (r, buf, sizeof(buf));
232                         _film->log()->log (String::compose (N_("error on av_read_frame (%1) (%2)"), buf, r));
233                 }
234
235                 /* Get any remaining frames */
236                 
237                 _packet.data = 0;
238                 _packet.size = 0;
239                 
240                 /* XXX: should we reset _packet.data and size after each *_decode_* call? */
241                 
242                 if (_decode_video) {
243                         while (decode_video_packet ());
244                 }
245
246                 if (_ffmpeg_content->audio_stream() && _decode_audio) {
247                         decode_audio_packet ();
248                 }
249                         
250                 return true;
251         }
252
253         avcodec_get_frame_defaults (_frame);
254
255         if (_packet.stream_index == _video_stream && _decode_video) {
256                 decode_video_packet ();
257         } else if (_ffmpeg_content->audio_stream() && _packet.stream_index == _ffmpeg_content->audio_stream()->id && _decode_audio) {
258                 decode_audio_packet ();
259         } else if (_ffmpeg_content->subtitle_stream() && _packet.stream_index == _ffmpeg_content->subtitle_stream()->id && _decode_subtitles) {
260
261                 int got_subtitle;
262                 AVSubtitle sub;
263                 if (avcodec_decode_subtitle2 (_subtitle_codec_context, &sub, &got_subtitle, &_packet) && got_subtitle) {
264                         /* Sometimes we get an empty AVSubtitle, which is used by some codecs to
265                            indicate that the previous subtitle should stop.
266                         */
267                         if (sub.num_rects > 0) {
268                                 shared_ptr<TimedSubtitle> ts;
269                                 try {
270                                         emit_subtitle (shared_ptr<TimedSubtitle> (new TimedSubtitle (sub)));
271                                 } catch (...) {
272                                         /* some problem with the subtitle; we probably didn't understand it */
273                                 }
274                         } else {
275                                 emit_subtitle (shared_ptr<TimedSubtitle> ());
276                         }
277                         avsubtitle_free (&sub);
278                 }
279         }
280         
281         av_free_packet (&_packet);
282         return false;
283 }
284
285 /** @param data pointer to array of pointers to buffers.
286  *  Only the first buffer will be used for non-planar data, otherwise there will be one per channel.
287  */
288 shared_ptr<AudioBuffers>
289 FFmpegDecoder::deinterleave_audio (uint8_t** data, int size)
290 {
291         assert (_ffmpeg_content->audio_channels());
292         assert (bytes_per_audio_sample());
293
294         /* Deinterleave and convert to float */
295
296         assert ((size % (bytes_per_audio_sample() * _ffmpeg_content->audio_channels())) == 0);
297
298         int const total_samples = size / bytes_per_audio_sample();
299         int const frames = total_samples / _ffmpeg_content->audio_channels();
300         shared_ptr<AudioBuffers> audio (new AudioBuffers (_ffmpeg_content->audio_channels(), frames));
301
302         switch (audio_sample_format()) {
303         case AV_SAMPLE_FMT_S16:
304         {
305                 int16_t* p = reinterpret_cast<int16_t *> (data[0]);
306                 int sample = 0;
307                 int channel = 0;
308                 for (int i = 0; i < total_samples; ++i) {
309                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
310
311                         ++channel;
312                         if (channel == _ffmpeg_content->audio_channels()) {
313                                 channel = 0;
314                                 ++sample;
315                         }
316                 }
317         }
318         break;
319
320         case AV_SAMPLE_FMT_S16P:
321         {
322                 int16_t** p = reinterpret_cast<int16_t **> (data);
323                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
324                         for (int j = 0; j < frames; ++j) {
325                                 audio->data(i)[j] = static_cast<float>(p[i][j]) / (1 << 15);
326                         }
327                 }
328         }
329         break;
330         
331         case AV_SAMPLE_FMT_S32:
332         {
333                 int32_t* p = reinterpret_cast<int32_t *> (data[0]);
334                 int sample = 0;
335                 int channel = 0;
336                 for (int i = 0; i < total_samples; ++i) {
337                         audio->data(channel)[sample] = static_cast<float>(*p++) / (1 << 31);
338
339                         ++channel;
340                         if (channel == _ffmpeg_content->audio_channels()) {
341                                 channel = 0;
342                                 ++sample;
343                         }
344                 }
345         }
346         break;
347
348         case AV_SAMPLE_FMT_FLT:
349         {
350                 float* p = reinterpret_cast<float*> (data[0]);
351                 int sample = 0;
352                 int channel = 0;
353                 for (int i = 0; i < total_samples; ++i) {
354                         audio->data(channel)[sample] = *p++;
355
356                         ++channel;
357                         if (channel == _ffmpeg_content->audio_channels()) {
358                                 channel = 0;
359                                 ++sample;
360                         }
361                 }
362         }
363         break;
364                 
365         case AV_SAMPLE_FMT_FLTP:
366         {
367                 float** p = reinterpret_cast<float**> (data);
368                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
369                         memcpy (audio->data(i), p[i], frames * sizeof(float));
370                 }
371         }
372         break;
373
374         default:
375                 throw DecodeError (String::compose (_("Unrecognised audio sample format (%1)"), static_cast<int> (audio_sample_format())));
376         }
377
378         return audio;
379 }
380
381 float
382 FFmpegDecoder::video_frame_rate () const
383 {
384         AVStream* s = _format_context->streams[_video_stream];
385
386         if (s->avg_frame_rate.num && s->avg_frame_rate.den) {
387                 return av_q2d (s->avg_frame_rate);
388         }
389
390         return av_q2d (s->r_frame_rate);
391 }
392
393 AVSampleFormat
394 FFmpegDecoder::audio_sample_format () const
395 {
396         if (_audio_codec_context == 0) {
397                 return (AVSampleFormat) 0;
398         }
399         
400         return _audio_codec_context->sample_fmt;
401 }
402
403 libdcp::Size
404 FFmpegDecoder::native_size () const
405 {
406         return libdcp::Size (_video_codec_context->width, _video_codec_context->height);
407 }
408
409 PixelFormat
410 FFmpegDecoder::pixel_format () const
411 {
412         return _video_codec_context->pix_fmt;
413 }
414
415 int
416 FFmpegDecoder::time_base_numerator () const
417 {
418         return _video_codec_context->time_base.num;
419 }
420
421 int
422 FFmpegDecoder::time_base_denominator () const
423 {
424         return _video_codec_context->time_base.den;
425 }
426
427 int
428 FFmpegDecoder::sample_aspect_ratio_numerator () const
429 {
430         return _video_codec_context->sample_aspect_ratio.num;
431 }
432
433 int
434 FFmpegDecoder::sample_aspect_ratio_denominator () const
435 {
436         return _video_codec_context->sample_aspect_ratio.den;
437 }
438
439 string
440 FFmpegDecoder::stream_name (AVStream* s) const
441 {
442         stringstream n;
443
444         if (s->metadata) {
445                 AVDictionaryEntry const * lang = av_dict_get (s->metadata, N_("language"), 0, 0);
446                 if (lang) {
447                         n << lang->value;
448                 }
449                 
450                 AVDictionaryEntry const * title = av_dict_get (s->metadata, N_("title"), 0, 0);
451                 if (title) {
452                         if (!n.str().empty()) {
453                                 n << N_(" ");
454                         }
455                         n << title->value;
456                 }
457         }
458
459         if (n.str().empty()) {
460                 n << N_("unknown");
461         }
462
463         return n.str ();
464 }
465
466 int
467 FFmpegDecoder::bytes_per_audio_sample () const
468 {
469         return av_get_bytes_per_sample (audio_sample_format ());
470 }
471
472 bool
473 FFmpegDecoder::seek (double p)
474 {
475         return do_seek (p, false, false);
476 }
477
478 bool
479 FFmpegDecoder::seek_back ()
480 {
481         if (last_content_time() < 2.5) {
482                 return true;
483         }
484         
485         return do_seek (last_content_time() - 2.5 / video_frame_rate(), true, true);
486 }
487
488 bool
489 FFmpegDecoder::seek_forward ()
490 {
491         if (last_content_time() >= (video_length() - video_frame_rate())) {
492                 return true;
493         }
494         
495         return do_seek (last_content_time() - 0.5 / video_frame_rate(), true, true);
496 }
497
498 bool
499 FFmpegDecoder::do_seek (double p, bool backwards, bool accurate)
500 {
501         int64_t const vt = p / av_q2d (_format_context->streams[_video_stream]->time_base);
502
503         int const r = av_seek_frame (_format_context, _video_stream, vt, backwards ? AVSEEK_FLAG_BACKWARD : 0);
504
505         avcodec_flush_buffers (_video_codec_context);
506         if (_subtitle_codec_context) {
507                 avcodec_flush_buffers (_subtitle_codec_context);
508         }
509
510         if (accurate) {
511                 while (1) {
512                         int r = av_read_frame (_format_context, &_packet);
513                         if (r < 0) {
514                                 return true;
515                         }
516                         
517                         avcodec_get_frame_defaults (_frame);
518                         
519                         if (_packet.stream_index == _video_stream) {
520                                 int finished = 0;
521                                 int const r = avcodec_decode_video2 (_video_codec_context, _frame, &finished, &_packet);
522                                 if (r >= 0 && finished) {
523                                         int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
524                                         if (bet > vt) {
525                                                 break;
526                                         }
527                                 }
528                         }
529                         
530                         av_free_packet (&_packet);
531                 }
532         }
533                 
534         return r < 0;
535 }
536
537 void
538 FFmpegDecoder::film_changed (Film::Property p)
539 {
540         switch (p) {
541         case Film::CROP:
542         case Film::FILTERS:
543         {
544                 boost::mutex::scoped_lock lm (_filter_graphs_mutex);
545                 _filter_graphs.clear ();
546         }
547         break;
548
549         default:
550                 break;
551         }
552 }
553
554 /** @return Length (in video frames) according to our content's header */
555 ContentVideoFrame
556 FFmpegDecoder::video_length () const
557 {
558         return (double(_format_context->duration) / AV_TIME_BASE) * video_frame_rate();
559 }
560
561 void
562 FFmpegDecoder::decode_audio_packet ()
563 {
564         /* Audio packets can contain multiple frames, so we may have to call avcodec_decode_audio4
565            several times.
566         */
567         
568         AVPacket copy_packet = _packet;
569
570         while (copy_packet.size > 0) {
571
572                 int frame_finished;
573                 int const decode_result = avcodec_decode_audio4 (_audio_codec_context, _frame, &frame_finished, &copy_packet);
574                 if (decode_result >= 0) {
575                         if (frame_finished) {
576                         
577                                 /* Where we are in the source, in seconds */
578                                 double const source_pts_seconds = av_q2d (_format_context->streams[copy_packet.stream_index]->time_base)
579                                         * av_frame_get_best_effort_timestamp(_frame);
580                                 
581                                 int const data_size = av_samples_get_buffer_size (
582                                         0, _audio_codec_context->channels, _frame->nb_samples, audio_sample_format (), 1
583                                         );
584                                 
585                                 assert (_audio_codec_context->channels == _ffmpeg_content->audio_channels());
586                                 Audio (deinterleave_audio (_frame->data, data_size), source_pts_seconds);
587                         }
588                         
589                         copy_packet.data += decode_result;
590                         copy_packet.size -= decode_result;
591                 }
592         }
593 }
594
595 bool
596 FFmpegDecoder::decode_video_packet ()
597 {
598         int frame_finished;
599         if (avcodec_decode_video2 (_video_codec_context, _frame, &frame_finished, &_packet) < 0 || !frame_finished) {
600                 return false;
601         }
602                 
603         boost::mutex::scoped_lock lm (_filter_graphs_mutex);
604         
605         shared_ptr<FilterGraph> graph;
606         
607         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
608         while (i != _filter_graphs.end() && !(*i)->can_process (libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format)) {
609                 ++i;
610         }
611         
612         if (i == _filter_graphs.end ()) {
613                 graph.reset (new FilterGraph (_film, this, libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format));
614                 _filter_graphs.push_back (graph);
615                 _film->log()->log (String::compose (N_("New graph for %1x%2, pixel format %3"), _frame->width, _frame->height, _frame->format));
616         } else {
617                 graph = *i;
618         }
619         
620         list<shared_ptr<Image> > images = graph->process (_frame);
621         
622         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
623                 int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
624                 if (bet != AV_NOPTS_VALUE) {
625                         /* XXX: may need to insert extra frames / remove frames here ...
626                            (as per old Matcher)
627                         */
628                         emit_video (*i, false, bet * av_q2d (_format_context->streams[_video_stream]->time_base) * TIME_HZ);
629                 } else {
630                         _film->log()->log ("Dropping frame without PTS");
631                 }
632         }
633
634         return true;
635 }