Half-way through trying to make seek work again.
[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, c)
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                                 shared_ptr<FFmpegAudioStream> (
145                                         new FFmpegAudioStream (stream_name (s), i, s->codec->sample_rate, s->codec->channels)
146                                         )
147                                 );
148
149                 } else if (s->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
150                         _subtitle_streams.push_back (shared_ptr<FFmpegSubtitleStream> (new FFmpegSubtitleStream (stream_name (s), i)));
151                 }
152         }
153
154         if (_video_stream < 0) {
155                 throw DecodeError (N_("could not find video stream"));
156         }
157
158         _frame = avcodec_alloc_frame ();
159         if (_frame == 0) {
160                 throw DecodeError (N_("could not allocate frame"));
161         }
162 }
163
164 void
165 FFmpegDecoder::setup_video ()
166 {
167         boost::mutex::scoped_lock lm (_mutex);
168         
169         _video_codec_context = _format_context->streams[_video_stream]->codec;
170         _video_codec = avcodec_find_decoder (_video_codec_context->codec_id);
171
172         if (_video_codec == 0) {
173                 throw DecodeError (_("could not find video decoder"));
174         }
175
176         if (avcodec_open2 (_video_codec_context, _video_codec, 0) < 0) {
177                 throw DecodeError (N_("could not open video decoder"));
178         }
179 }
180
181 void
182 FFmpegDecoder::setup_audio ()
183 {
184         boost::mutex::scoped_lock lm (_mutex);
185         
186         if (!_ffmpeg_content->audio_stream ()) {
187                 return;
188         }
189
190         _audio_codec_context = _format_context->streams[_ffmpeg_content->audio_stream()->id]->codec;
191         _audio_codec = avcodec_find_decoder (_audio_codec_context->codec_id);
192
193         if (_audio_codec == 0) {
194                 throw DecodeError (_("could not find audio decoder"));
195         }
196
197         if (avcodec_open2 (_audio_codec_context, _audio_codec, 0) < 0) {
198                 throw DecodeError (N_("could not open audio decoder"));
199         }
200 }
201
202 void
203 FFmpegDecoder::setup_subtitle ()
204 {
205         boost::mutex::scoped_lock lm (_mutex);
206         
207         if (!_ffmpeg_content->subtitle_stream() || _ffmpeg_content->subtitle_stream()->id >= int (_format_context->nb_streams)) {
208                 return;
209         }
210
211         _subtitle_codec_context = _format_context->streams[_ffmpeg_content->subtitle_stream()->id]->codec;
212         _subtitle_codec = avcodec_find_decoder (_subtitle_codec_context->codec_id);
213
214         if (_subtitle_codec == 0) {
215                 throw DecodeError (_("could not find subtitle decoder"));
216         }
217         
218         if (avcodec_open2 (_subtitle_codec_context, _subtitle_codec, 0) < 0) {
219                 throw DecodeError (N_("could not open subtitle decoder"));
220         }
221 }
222
223
224 bool
225 FFmpegDecoder::pass ()
226 {
227         cout << "ffd pass.\n";
228         int r = av_read_frame (_format_context, &_packet);
229         cout << "A " << r << "\n";
230
231         if (r < 0) {
232                 if (r != AVERROR_EOF) {
233                         /* Maybe we should fail here, but for now we'll just finish off instead */
234                         char buf[256];
235                         av_strerror (r, buf, sizeof(buf));
236                         _film->log()->log (String::compose (N_("error on av_read_frame (%1) (%2)"), buf, r));
237                 }
238
239                 /* Get any remaining frames */
240                 
241                 _packet.data = 0;
242                 _packet.size = 0;
243                 
244                 /* XXX: should we reset _packet.data and size after each *_decode_* call? */
245                 
246                 if (_decode_video) {
247                         while (decode_video_packet ());
248                 }
249
250                 if (_ffmpeg_content->audio_stream() && _decode_audio) {
251                         decode_audio_packet ();
252                 }
253                         
254                 return true;
255         }
256
257         avcodec_get_frame_defaults (_frame);
258
259         if (_packet.stream_index == _video_stream && _decode_video) {
260                 cout << "dvp\n";
261                 decode_video_packet ();
262                 cout << "ok.\n";
263         } else if (_ffmpeg_content->audio_stream() && _packet.stream_index == _ffmpeg_content->audio_stream()->id && _decode_audio) {
264                 decode_audio_packet ();
265         } else if (_ffmpeg_content->subtitle_stream() && _packet.stream_index == _ffmpeg_content->subtitle_stream()->id && _decode_subtitles) {
266
267                 int got_subtitle;
268                 AVSubtitle sub;
269                 if (avcodec_decode_subtitle2 (_subtitle_codec_context, &sub, &got_subtitle, &_packet) && got_subtitle) {
270                         /* Sometimes we get an empty AVSubtitle, which is used by some codecs to
271                            indicate that the previous subtitle should stop.
272                         */
273                         if (sub.num_rects > 0) {
274                                 shared_ptr<TimedSubtitle> ts;
275                                 try {
276                                         emit_subtitle (shared_ptr<TimedSubtitle> (new TimedSubtitle (sub)));
277                                 } catch (...) {
278                                         /* some problem with the subtitle; we probably didn't understand it */
279                                 }
280                         } else {
281                                 emit_subtitle (shared_ptr<TimedSubtitle> ());
282                         }
283                         avsubtitle_free (&sub);
284                 }
285         }
286
287         cout << "out.\n";
288         av_free_packet (&_packet);
289         return false;
290 }
291
292 /** @param data pointer to array of pointers to buffers.
293  *  Only the first buffer will be used for non-planar data, otherwise there will be one per channel.
294  */
295 shared_ptr<AudioBuffers>
296 FFmpegDecoder::deinterleave_audio (uint8_t** data, int size)
297 {
298         assert (_ffmpeg_content->audio_channels());
299         assert (bytes_per_audio_sample());
300
301         /* Deinterleave and convert to float */
302
303         assert ((size % (bytes_per_audio_sample() * _ffmpeg_content->audio_channels())) == 0);
304
305         int const total_samples = size / bytes_per_audio_sample();
306         int const frames = total_samples / _ffmpeg_content->audio_channels();
307         shared_ptr<AudioBuffers> audio (new AudioBuffers (_ffmpeg_content->audio_channels(), frames));
308
309         switch (audio_sample_format()) {
310         case AV_SAMPLE_FMT_S16:
311         {
312                 int16_t* p = reinterpret_cast<int16_t *> (data[0]);
313                 int sample = 0;
314                 int channel = 0;
315                 for (int i = 0; i < total_samples; ++i) {
316                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
317
318                         ++channel;
319                         if (channel == _ffmpeg_content->audio_channels()) {
320                                 channel = 0;
321                                 ++sample;
322                         }
323                 }
324         }
325         break;
326
327         case AV_SAMPLE_FMT_S16P:
328         {
329                 int16_t** p = reinterpret_cast<int16_t **> (data);
330                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
331                         for (int j = 0; j < frames; ++j) {
332                                 audio->data(i)[j] = static_cast<float>(p[i][j]) / (1 << 15);
333                         }
334                 }
335         }
336         break;
337         
338         case AV_SAMPLE_FMT_S32:
339         {
340                 int32_t* p = reinterpret_cast<int32_t *> (data[0]);
341                 int sample = 0;
342                 int channel = 0;
343                 for (int i = 0; i < total_samples; ++i) {
344                         audio->data(channel)[sample] = static_cast<float>(*p++) / (1 << 31);
345
346                         ++channel;
347                         if (channel == _ffmpeg_content->audio_channels()) {
348                                 channel = 0;
349                                 ++sample;
350                         }
351                 }
352         }
353         break;
354
355         case AV_SAMPLE_FMT_FLT:
356         {
357                 float* p = reinterpret_cast<float*> (data[0]);
358                 int sample = 0;
359                 int channel = 0;
360                 for (int i = 0; i < total_samples; ++i) {
361                         audio->data(channel)[sample] = *p++;
362
363                         ++channel;
364                         if (channel == _ffmpeg_content->audio_channels()) {
365                                 channel = 0;
366                                 ++sample;
367                         }
368                 }
369         }
370         break;
371                 
372         case AV_SAMPLE_FMT_FLTP:
373         {
374                 float** p = reinterpret_cast<float**> (data);
375                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
376                         memcpy (audio->data(i), p[i], frames * sizeof(float));
377                 }
378         }
379         break;
380
381         default:
382                 throw DecodeError (String::compose (_("Unrecognised audio sample format (%1)"), static_cast<int> (audio_sample_format())));
383         }
384
385         return audio;
386 }
387
388 float
389 FFmpegDecoder::video_frame_rate () const
390 {
391         AVStream* s = _format_context->streams[_video_stream];
392
393         if (s->avg_frame_rate.num && s->avg_frame_rate.den) {
394                 return av_q2d (s->avg_frame_rate);
395         }
396
397         return av_q2d (s->r_frame_rate);
398 }
399
400 AVSampleFormat
401 FFmpegDecoder::audio_sample_format () const
402 {
403         if (_audio_codec_context == 0) {
404                 return (AVSampleFormat) 0;
405         }
406         
407         return _audio_codec_context->sample_fmt;
408 }
409
410 libdcp::Size
411 FFmpegDecoder::native_size () const
412 {
413         return libdcp::Size (_video_codec_context->width, _video_codec_context->height);
414 }
415
416 PixelFormat
417 FFmpegDecoder::pixel_format () const
418 {
419         return _video_codec_context->pix_fmt;
420 }
421
422 int
423 FFmpegDecoder::time_base_numerator () const
424 {
425         return _video_codec_context->time_base.num;
426 }
427
428 int
429 FFmpegDecoder::time_base_denominator () const
430 {
431         return _video_codec_context->time_base.den;
432 }
433
434 int
435 FFmpegDecoder::sample_aspect_ratio_numerator () const
436 {
437         return _video_codec_context->sample_aspect_ratio.num;
438 }
439
440 int
441 FFmpegDecoder::sample_aspect_ratio_denominator () const
442 {
443         return _video_codec_context->sample_aspect_ratio.den;
444 }
445
446 string
447 FFmpegDecoder::stream_name (AVStream* s) const
448 {
449         stringstream n;
450
451         if (s->metadata) {
452                 AVDictionaryEntry const * lang = av_dict_get (s->metadata, N_("language"), 0, 0);
453                 if (lang) {
454                         n << lang->value;
455                 }
456                 
457                 AVDictionaryEntry const * title = av_dict_get (s->metadata, N_("title"), 0, 0);
458                 if (title) {
459                         if (!n.str().empty()) {
460                                 n << N_(" ");
461                         }
462                         n << title->value;
463                 }
464         }
465
466         if (n.str().empty()) {
467                 n << N_("unknown");
468         }
469
470         return n.str ();
471 }
472
473 int
474 FFmpegDecoder::bytes_per_audio_sample () const
475 {
476         return av_get_bytes_per_sample (audio_sample_format ());
477 }
478
479 bool
480 FFmpegDecoder::seek (Time t)
481 {
482         return do_seek (t, false, false);
483 }
484
485 bool
486 FFmpegDecoder::seek_back ()
487 {
488         if (last_content_time() < 2.5) {
489                 return true;
490         }
491         
492         return do_seek (last_content_time() - 2.5 * TIME_HZ / video_frame_rate(), true, true);
493 }
494
495 bool
496 FFmpegDecoder::seek_forward ()
497 {
498         if (last_content_time() >= (video_length() - video_frame_rate())) {
499                 return true;
500         }
501         
502         return do_seek (last_content_time() - 0.5 * TIME_HZ / video_frame_rate(), true, true);
503 }
504
505 bool
506 FFmpegDecoder::do_seek (Time t, bool backwards, bool accurate)
507 {
508         int64_t const vt = t / (av_q2d (_format_context->streams[_video_stream]->time_base) * TIME_HZ);
509
510         cout << "seek to " << vt << " (acc=" << accurate << ") (sec " << (vt * av_q2d (_format_context->streams[_video_stream]->time_base)) << "\n";
511
512         int const r = av_seek_frame (_format_context, _video_stream, vt, backwards ? AVSEEK_FLAG_BACKWARD : 0);
513
514         avcodec_flush_buffers (_video_codec_context);
515         if (_subtitle_codec_context) {
516                 avcodec_flush_buffers (_subtitle_codec_context);
517         }
518
519         if (accurate) {
520                 while (1) {
521                         int r = av_read_frame (_format_context, &_packet);
522                         if (r < 0) {
523                                 return true;
524                         }
525                         
526                         avcodec_get_frame_defaults (_frame);
527                         
528                         if (_packet.stream_index == _video_stream) {
529                                 int finished = 0;
530                                 int const r = avcodec_decode_video2 (_video_codec_context, _frame, &finished, &_packet);
531                                 if (r >= 0 && finished) {
532                                         int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
533                                         if (bet > vt) {
534                                                 break;
535                                         }
536                                 }
537                         }
538                         
539                         av_free_packet (&_packet);
540                 }
541         }
542
543         cout << "seek ok.\n";
544         return r < 0;
545 }
546
547 void
548 FFmpegDecoder::film_changed (Film::Property p)
549 {
550         switch (p) {
551         case Film::FILTERS:
552         {
553                 boost::mutex::scoped_lock lm (_filter_graphs_mutex);
554                 _filter_graphs.clear ();
555         }
556         break;
557
558         default:
559                 break;
560         }
561 }
562
563 /** @return Length (in video frames) according to our content's header */
564 ContentVideoFrame
565 FFmpegDecoder::video_length () const
566 {
567         return (double(_format_context->duration) / AV_TIME_BASE) * video_frame_rate();
568 }
569
570 void
571 FFmpegDecoder::decode_audio_packet ()
572 {
573         /* Audio packets can contain multiple frames, so we may have to call avcodec_decode_audio4
574            several times.
575         */
576         
577         AVPacket copy_packet = _packet;
578
579         while (copy_packet.size > 0) {
580
581                 int frame_finished;
582                 int const decode_result = avcodec_decode_audio4 (_audio_codec_context, _frame, &frame_finished, &copy_packet);
583                 if (decode_result >= 0) {
584                         if (frame_finished) {
585                         
586                                 /* Where we are in the source, in seconds */
587                                 double const source_pts_seconds = av_q2d (_format_context->streams[copy_packet.stream_index]->time_base)
588                                         * av_frame_get_best_effort_timestamp(_frame);
589                                 
590                                 int const data_size = av_samples_get_buffer_size (
591                                         0, _audio_codec_context->channels, _frame->nb_samples, audio_sample_format (), 1
592                                         );
593                                 
594                                 assert (_audio_codec_context->channels == _ffmpeg_content->audio_channels());
595                                 Audio (deinterleave_audio (_frame->data, data_size), source_pts_seconds);
596                         }
597                         
598                         copy_packet.data += decode_result;
599                         copy_packet.size -= decode_result;
600                 }
601         }
602 }
603
604 bool
605 FFmpegDecoder::decode_video_packet ()
606 {
607         int frame_finished;
608         cout << "avc decode v2\n";
609         if (avcodec_decode_video2 (_video_codec_context, _frame, &frame_finished, &_packet) < 0 || !frame_finished) {
610                 return false;
611         }
612         cout << "done that.\n";
613                 
614         boost::mutex::scoped_lock lm (_filter_graphs_mutex);
615
616         cout << "got lock.\n";
617         
618         shared_ptr<FilterGraph> graph;
619         
620         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
621         while (i != _filter_graphs.end() && !(*i)->can_process (libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format)) {
622                 ++i;
623         }
624
625         cout << "found graph.\n";
626         
627         if (i == _filter_graphs.end ()) {
628                 graph.reset (new FilterGraph (_film, this, libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format));
629                 _filter_graphs.push_back (graph);
630                 _film->log()->log (String::compose (N_("New graph for %1x%2, pixel format %3"), _frame->width, _frame->height, _frame->format));
631         } else {
632                 graph = *i;
633         }
634
635
636         cout << "pushed in.\n";
637         list<shared_ptr<Image> > images = graph->process (_frame);
638         cout << "got " << images.size() << "\n";
639         
640         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
641                 int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
642                 if (bet != AV_NOPTS_VALUE) {
643                         /* XXX: may need to insert extra frames / remove frames here ...
644                            (as per old Matcher)
645                         */
646                         cout << "emitting.\n";
647                         emit_video (*i, false, bet * av_q2d (_format_context->streams[_video_stream]->time_base) * TIME_HZ);
648                         cout << "emitted.\n";
649                 } else {
650                         _film->log()->log ("Dropping frame without PTS");
651                 }
652         }
653
654         return true;
655 }