Various stuff; mostly change to decoder scaling and adding subtitle; scaling test.
[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 "filter.h"
43 #include "exceptions.h"
44 #include "image.h"
45 #include "util.h"
46 #include "log.h"
47 #include "ffmpeg_decoder.h"
48 #include "filter_graph.h"
49 #include "subtitle.h"
50 #include "audio_buffers.h"
51
52 #include "i18n.h"
53
54 using std::cout;
55 using std::string;
56 using std::vector;
57 using std::stringstream;
58 using std::list;
59 using std::min;
60 using boost::shared_ptr;
61 using boost::optional;
62 using boost::dynamic_pointer_cast;
63 using libdcp::Size;
64
65 boost::mutex FFmpegDecoder::_mutex;
66
67 FFmpegDecoder::FFmpegDecoder (shared_ptr<const Film> f, shared_ptr<const FFmpegContent> c, bool video, bool audio, bool subtitles)
68         : Decoder (f)
69         , VideoDecoder (f, c)
70         , AudioDecoder (f, c)
71         , _ffmpeg_content (c)
72         , _format_context (0)
73         , _video_stream (-1)
74         , _frame (0)
75         , _video_codec_context (0)
76         , _video_codec (0)
77         , _audio_codec_context (0)
78         , _audio_codec (0)
79         , _subtitle_codec_context (0)
80         , _subtitle_codec (0)
81         , _decode_video (video)
82         , _decode_audio (audio)
83         , _decode_subtitles (subtitles)
84 {
85         setup_general ();
86         setup_video ();
87         setup_audio ();
88         setup_subtitle ();
89 }
90
91 FFmpegDecoder::~FFmpegDecoder ()
92 {
93         boost::mutex::scoped_lock lm (_mutex);
94         
95         if (_audio_codec_context) {
96                 avcodec_close (_audio_codec_context);
97         }
98
99         if (_video_codec_context) {
100                 avcodec_close (_video_codec_context);
101         }
102
103         if (_subtitle_codec_context) {
104                 avcodec_close (_subtitle_codec_context);
105         }
106
107         av_free (_frame);
108         
109         avformat_close_input (&_format_context);
110 }       
111
112 void
113 FFmpegDecoder::setup_general ()
114 {
115         av_register_all ();
116
117         if (avformat_open_input (&_format_context, _ffmpeg_content->file().string().c_str(), 0, 0) < 0) {
118                 throw OpenFileError (_ffmpeg_content->file().string ());
119         }
120
121         if (avformat_find_stream_info (_format_context, 0) < 0) {
122                 throw DecodeError (_("could not find stream information"));
123         }
124
125         /* Find video, audio and subtitle streams */
126
127         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
128                 AVStream* s = _format_context->streams[i];
129                 if (s->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
130                         _video_stream = i;
131                 } else if (s->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
132
133                         /* This is a hack; sometimes it seems that _audio_codec_context->channel_layout isn't set up,
134                            so bodge it here.  No idea why we should have to do this.
135                         */
136
137                         if (s->codec->channel_layout == 0) {
138                                 s->codec->channel_layout = av_get_default_channel_layout (s->codec->channels);
139                         }
140                         
141                         _audio_streams.push_back (
142                                 shared_ptr<FFmpegAudioStream> (
143                                         new FFmpegAudioStream (stream_name (s), i, s->codec->sample_rate, s->codec->channels)
144                                         )
145                                 );
146
147                 } else if (s->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
148                         _subtitle_streams.push_back (shared_ptr<FFmpegSubtitleStream> (new 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 void
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                         shared_ptr<const Film> film = _film.lock ();
233                         assert (film);
234                         film->log()->log (String::compose (N_("error on av_read_frame (%1) (%2)"), buf, r));
235                 }
236
237                 /* Get any remaining frames */
238                 
239                 _packet.data = 0;
240                 _packet.size = 0;
241                 
242                 /* XXX: should we reset _packet.data and size after each *_decode_* call? */
243                 
244                 if (_decode_video) {
245                         while (decode_video_packet ());
246                 }
247
248                 if (_ffmpeg_content->audio_stream() && _decode_audio) {
249                         decode_audio_packet ();
250                 }
251                         
252                 return;
253         }
254
255         avcodec_get_frame_defaults (_frame);
256
257         if (_packet.stream_index == _video_stream && _decode_video) {
258                 decode_video_packet ();
259         } else if (_ffmpeg_content->audio_stream() && _packet.stream_index == _ffmpeg_content->audio_stream()->id && _decode_audio) {
260                 decode_audio_packet ();
261         } else if (_ffmpeg_content->subtitle_stream() && _packet.stream_index == _ffmpeg_content->subtitle_stream()->id && _decode_subtitles) {
262
263                 int got_subtitle;
264                 AVSubtitle sub;
265                 if (avcodec_decode_subtitle2 (_subtitle_codec_context, &sub, &got_subtitle, &_packet) && got_subtitle) {
266                         /* Sometimes we get an empty AVSubtitle, which is used by some codecs to
267                            indicate that the previous subtitle should stop.
268                         */
269                         if (sub.num_rects > 0) {
270                                 shared_ptr<TimedSubtitle> ts;
271                                 try {
272                                         subtitle (shared_ptr<TimedSubtitle> (new TimedSubtitle (sub)));
273                                 } catch (...) {
274                                         /* some problem with the subtitle; we probably didn't understand it */
275                                 }
276                         } else {
277                                 subtitle (shared_ptr<TimedSubtitle> ());
278                         }
279                         avsubtitle_free (&sub);
280                 }
281         }
282
283         av_free_packet (&_packet);
284 }
285
286 /** @param data pointer to array of pointers to buffers.
287  *  Only the first buffer will be used for non-planar data, otherwise there will be one per channel.
288  */
289 shared_ptr<AudioBuffers>
290 FFmpegDecoder::deinterleave_audio (uint8_t** data, int size)
291 {
292         assert (_ffmpeg_content->audio_channels());
293         assert (bytes_per_audio_sample());
294
295         /* Deinterleave and convert to float */
296
297         assert ((size % (bytes_per_audio_sample() * _ffmpeg_content->audio_channels())) == 0);
298
299         int const total_samples = size / bytes_per_audio_sample();
300         int const frames = total_samples / _ffmpeg_content->audio_channels();
301         shared_ptr<AudioBuffers> audio (new AudioBuffers (_ffmpeg_content->audio_channels(), frames));
302
303         switch (audio_sample_format()) {
304         case AV_SAMPLE_FMT_S16:
305         {
306                 int16_t* p = reinterpret_cast<int16_t *> (data[0]);
307                 int sample = 0;
308                 int channel = 0;
309                 for (int i = 0; i < total_samples; ++i) {
310                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
311
312                         ++channel;
313                         if (channel == _ffmpeg_content->audio_channels()) {
314                                 channel = 0;
315                                 ++sample;
316                         }
317                 }
318         }
319         break;
320
321         case AV_SAMPLE_FMT_S16P:
322         {
323                 int16_t** p = reinterpret_cast<int16_t **> (data);
324                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
325                         for (int j = 0; j < frames; ++j) {
326                                 audio->data(i)[j] = static_cast<float>(p[i][j]) / (1 << 15);
327                         }
328                 }
329         }
330         break;
331         
332         case AV_SAMPLE_FMT_S32:
333         {
334                 int32_t* p = reinterpret_cast<int32_t *> (data[0]);
335                 int sample = 0;
336                 int channel = 0;
337                 for (int i = 0; i < total_samples; ++i) {
338                         audio->data(channel)[sample] = static_cast<float>(*p++) / (1 << 31);
339
340                         ++channel;
341                         if (channel == _ffmpeg_content->audio_channels()) {
342                                 channel = 0;
343                                 ++sample;
344                         }
345                 }
346         }
347         break;
348
349         case AV_SAMPLE_FMT_FLT:
350         {
351                 float* p = reinterpret_cast<float*> (data[0]);
352                 int sample = 0;
353                 int channel = 0;
354                 for (int i = 0; i < total_samples; ++i) {
355                         audio->data(channel)[sample] = *p++;
356
357                         ++channel;
358                         if (channel == _ffmpeg_content->audio_channels()) {
359                                 channel = 0;
360                                 ++sample;
361                         }
362                 }
363         }
364         break;
365                 
366         case AV_SAMPLE_FMT_FLTP:
367         {
368                 float** p = reinterpret_cast<float**> (data);
369                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
370                         memcpy (audio->data(i), p[i], frames * sizeof(float));
371                 }
372         }
373         break;
374
375         default:
376                 throw DecodeError (String::compose (_("Unrecognised audio sample format (%1)"), static_cast<int> (audio_sample_format())));
377         }
378
379         return audio;
380 }
381
382 float
383 FFmpegDecoder::video_frame_rate () const
384 {
385         AVStream* s = _format_context->streams[_video_stream];
386
387         if (s->avg_frame_rate.num && s->avg_frame_rate.den) {
388                 return av_q2d (s->avg_frame_rate);
389         }
390
391         return av_q2d (s->r_frame_rate);
392 }
393
394 AVSampleFormat
395 FFmpegDecoder::audio_sample_format () const
396 {
397         if (_audio_codec_context == 0) {
398                 return (AVSampleFormat) 0;
399         }
400         
401         return _audio_codec_context->sample_fmt;
402 }
403
404 libdcp::Size
405 FFmpegDecoder::video_size () const
406 {
407         return libdcp::Size (_video_codec_context->width, _video_codec_context->height);
408 }
409
410 string
411 FFmpegDecoder::stream_name (AVStream* s) const
412 {
413         stringstream n;
414
415         if (s->metadata) {
416                 AVDictionaryEntry const * lang = av_dict_get (s->metadata, N_("language"), 0, 0);
417                 if (lang) {
418                         n << lang->value;
419                 }
420                 
421                 AVDictionaryEntry const * title = av_dict_get (s->metadata, N_("title"), 0, 0);
422                 if (title) {
423                         if (!n.str().empty()) {
424                                 n << N_(" ");
425                         }
426                         n << title->value;
427                 }
428         }
429
430         if (n.str().empty()) {
431                 n << N_("unknown");
432         }
433
434         return n.str ();
435 }
436
437 int
438 FFmpegDecoder::bytes_per_audio_sample () const
439 {
440         return av_get_bytes_per_sample (audio_sample_format ());
441 }
442
443 void
444 FFmpegDecoder::seek (Time t)
445 {
446         do_seek (t, false, false);
447 }
448
449 void
450 FFmpegDecoder::seek_back ()
451 {
452         if (next() < (2.5 * TIME_HZ / video_frame_rate())) {
453                 return;
454         }
455         
456         do_seek (next() - 2.5 * TIME_HZ / video_frame_rate(), true, true);
457 }
458
459 void
460 FFmpegDecoder::seek_forward ()
461 {
462         if (next() >= (_ffmpeg_content->length() - 0.5 * TIME_HZ / video_frame_rate())) {
463                 return;
464         }
465         
466         do_seek (next() - 0.5 * TIME_HZ / video_frame_rate(), true, true);
467 }
468
469 void
470 FFmpegDecoder::do_seek (Time t, bool backwards, bool accurate)
471 {
472         int64_t const vt = t / (av_q2d (_format_context->streams[_video_stream]->time_base) * TIME_HZ);
473         av_seek_frame (_format_context, _video_stream, vt, backwards ? AVSEEK_FLAG_BACKWARD : 0);
474
475         avcodec_flush_buffers (_video_codec_context);
476         if (_subtitle_codec_context) {
477                 avcodec_flush_buffers (_subtitle_codec_context);
478         }
479
480         if (accurate) {
481                 while (1) {
482                         int r = av_read_frame (_format_context, &_packet);
483                         if (r < 0) {
484                                 return;
485                         }
486                         
487                         avcodec_get_frame_defaults (_frame);
488                         
489                         if (_packet.stream_index == _video_stream) {
490                                 int finished = 0;
491                                 int const r = avcodec_decode_video2 (_video_codec_context, _frame, &finished, &_packet);
492                                 if (r >= 0 && finished) {
493                                         int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
494                                         if (bet > vt) {
495                                                 break;
496                                         }
497                                 }
498                         }
499                         
500                         av_free_packet (&_packet);
501                 }
502         }
503
504         return;
505 }
506
507 /** @return Length (in video frames) according to our content's header */
508 ContentVideoFrame
509 FFmpegDecoder::video_length () const
510 {
511         return (double(_format_context->duration) / AV_TIME_BASE) * video_frame_rate();
512 }
513
514 void
515 FFmpegDecoder::decode_audio_packet ()
516 {
517         /* Audio packets can contain multiple frames, so we may have to call avcodec_decode_audio4
518            several times.
519         */
520         
521         AVPacket copy_packet = _packet;
522
523         while (copy_packet.size > 0) {
524
525                 int frame_finished;
526                 int const decode_result = avcodec_decode_audio4 (_audio_codec_context, _frame, &frame_finished, &copy_packet);
527                 if (decode_result >= 0) {
528                         if (frame_finished) {
529                         
530                                 /* Where we are in the source, in seconds */
531                                 double const source_pts_seconds = av_q2d (_format_context->streams[copy_packet.stream_index]->time_base)
532                                         * av_frame_get_best_effort_timestamp(_frame);
533                                 
534                                 int const data_size = av_samples_get_buffer_size (
535                                         0, _audio_codec_context->channels, _frame->nb_samples, audio_sample_format (), 1
536                                         );
537                                 
538                                 assert (_audio_codec_context->channels == _ffmpeg_content->audio_channels());
539                                 audio (deinterleave_audio (_frame->data, data_size), source_pts_seconds);
540                         }
541                         
542                         copy_packet.data += decode_result;
543                         copy_packet.size -= decode_result;
544                 }
545         }
546 }
547
548 bool
549 FFmpegDecoder::decode_video_packet ()
550 {
551         int frame_finished;
552         if (avcodec_decode_video2 (_video_codec_context, _frame, &frame_finished, &_packet) < 0 || !frame_finished) {
553                 return false;
554         }
555                 
556         boost::mutex::scoped_lock lm (_filter_graphs_mutex);
557
558         shared_ptr<FilterGraph> graph;
559         
560         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
561         while (i != _filter_graphs.end() && !(*i)->can_process (libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format)) {
562                 ++i;
563         }
564
565         if (i == _filter_graphs.end ()) {
566                 shared_ptr<const Film> film = _film.lock ();
567                 assert (film);
568
569                 graph.reset (new FilterGraph (_ffmpeg_content, libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format));
570                 _filter_graphs.push_back (graph);
571
572                 film->log()->log (String::compose (N_("New graph for %1x%2, pixel format %3"), _frame->width, _frame->height, _frame->format));
573         } else {
574                 graph = *i;
575         }
576
577         list<shared_ptr<Image> > images = graph->process (_frame);
578
579         string post_process = Filter::ffmpeg_strings (_ffmpeg_content->filters()).second;
580         
581         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
582
583                 shared_ptr<Image> image = *i;
584                 if (!post_process.empty ()) {
585                         image = image->post_process (post_process, true);
586                 }
587                 
588                 int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
589                 if (bet != AV_NOPTS_VALUE) {
590                         /* XXX: may need to insert extra frames / remove frames here ...
591                            (as per old Matcher)
592                         */
593                         Time const t = bet * av_q2d (_format_context->streams[_video_stream]->time_base) * TIME_HZ;
594                         video (image, false, t);
595                 } else {
596                         shared_ptr<const Film> film = _film.lock ();
597                         assert (film);
598                         film->log()->log ("Dropping frame without PTS");
599                 }
600         }
601
602         return true;
603 }
604
605 Time
606 FFmpegDecoder::next () const
607 {
608         if (_decode_video && _decode_audio && _audio_codec_context) {
609                 return min (_next_video, _next_audio);
610         }
611
612         if (_decode_audio && _audio_codec_context) {
613                 return _next_audio;
614         }
615
616         return _next_video;
617 }