Fix bad A/V sync in some (and maybe lots) of circumstances.
[dcpomatic.git] / src / lib / ffmpeg_decoder.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file  src/ffmpeg_decoder.cc
21  *  @brief A decoder using FFmpeg to decode content.
22  */
23
24 #include <stdexcept>
25 #include <vector>
26 #include <sstream>
27 #include <iomanip>
28 #include <iostream>
29 #include <stdint.h>
30 #include <boost/lexical_cast.hpp>
31 #include <sndfile.h>
32 extern "C" {
33 #include <libavcodec/avcodec.h>
34 #include <libavformat/avformat.h>
35 }
36 #include "film.h"
37 #include "filter.h"
38 #include "exceptions.h"
39 #include "image.h"
40 #include "util.h"
41 #include "log.h"
42 #include "ffmpeg_decoder.h"
43 #include "filter_graph.h"
44 #include "audio_buffers.h"
45 #include "ffmpeg_content.h"
46
47 #include "i18n.h"
48
49 using std::cout;
50 using std::string;
51 using std::vector;
52 using std::stringstream;
53 using std::list;
54 using std::min;
55 using std::pair;
56 using boost::shared_ptr;
57 using boost::optional;
58 using boost::dynamic_pointer_cast;
59 using libdcp::Size;
60
61 FFmpegDecoder::FFmpegDecoder (shared_ptr<const Film> f, shared_ptr<const FFmpegContent> c, bool video, bool audio)
62         : Decoder (f)
63         , VideoDecoder (f, c)
64         , AudioDecoder (f, c)
65         , SubtitleDecoder (f)
66         , FFmpeg (c)
67         , _subtitle_codec_context (0)
68         , _subtitle_codec (0)
69         , _decode_video (video)
70         , _decode_audio (audio)
71         , _pts_offset (0)
72         , _just_sought (false)
73 {
74         setup_subtitle ();
75
76         /* Audio and video frame PTS values may not start with 0.  We want
77            to fiddle them so that:
78
79            1.  One of them starts at time 0.
80            2.  The first video PTS value ends up on a frame boundary.
81
82            Then we remove big initial gaps in PTS and we allow our
83            insertion of black frames to work.
84
85            We will do:
86              audio_pts_to_use = audio_pts_from_ffmpeg + pts_offset;
87              video_pts_to_use = video_pts_from_ffmpeg + pts_offset;
88         */
89
90         bool const have_video = video && c->first_video();
91         bool const have_audio = audio && c->audio_stream() && c->audio_stream()->first_audio;
92
93         /* First, make one of them start at 0 */
94
95         if (have_audio && have_video) {
96                 _pts_offset = - min (c->first_video().get(), c->audio_stream()->first_audio.get());
97         } else if (have_video) {
98                 _pts_offset = - c->first_video().get();
99         } else if (have_audio) {
100                 _pts_offset = - c->audio_stream()->first_audio.get();
101         }
102
103         /* Now adjust both so that the video pts starts on a frame */
104         if (have_video && have_audio) {
105                 double first_video = c->first_video().get() + _pts_offset;
106                 double const old_first_video = first_video;
107                 
108                 /* Round the first video up to a frame boundary */
109                 if (fabs (rint (first_video * c->video_frame_rate()) - first_video * c->video_frame_rate()) > 1e-6) {
110                         first_video = ceil (first_video * c->video_frame_rate()) / c->video_frame_rate ();
111                 }
112
113                 _pts_offset += first_video - old_first_video;
114         }
115 }
116
117 FFmpegDecoder::~FFmpegDecoder ()
118 {
119         boost::mutex::scoped_lock lm (_mutex);
120
121         if (_subtitle_codec_context) {
122                 avcodec_close (_subtitle_codec_context);
123         }
124 }
125
126 void
127 FFmpegDecoder::flush ()
128 {
129         /* Get any remaining frames */
130         
131         _packet.data = 0;
132         _packet.size = 0;
133         
134         /* XXX: should we reset _packet.data and size after each *_decode_* call? */
135         
136         if (_decode_video) {
137                 while (decode_video_packet ()) {}
138         }
139         
140         if (_ffmpeg_content->audio_stream() && _decode_audio) {
141                 decode_audio_packet ();
142         }
143
144         /* Stop us being asked for any more data */
145         _video_position = _ffmpeg_content->video_length ();
146         _audio_position = _ffmpeg_content->audio_length ();
147 }
148
149 void
150 FFmpegDecoder::pass ()
151 {
152         int r = av_read_frame (_format_context, &_packet);
153
154         if (r < 0) {
155                 if (r != AVERROR_EOF) {
156                         /* Maybe we should fail here, but for now we'll just finish off instead */
157                         char buf[256];
158                         av_strerror (r, buf, sizeof(buf));
159                         shared_ptr<const Film> film = _film.lock ();
160                         assert (film);
161                         film->log()->log (String::compose (N_("error on av_read_frame (%1) (%2)"), buf, r));
162                 }
163
164                 flush ();
165                 return;
166         }
167
168         shared_ptr<const Film> film = _film.lock ();
169         assert (film);
170
171         int const si = _packet.stream_index;
172         
173         if (si == _video_stream && _decode_video) {
174                 decode_video_packet ();
175         } else if (_ffmpeg_content->audio_stream() && si == _ffmpeg_content->audio_stream()->index (_format_context) && _decode_audio) {
176                 decode_audio_packet ();
177         } else if (_ffmpeg_content->subtitle_stream() && si == _ffmpeg_content->subtitle_stream()->index (_format_context) && film->with_subtitles ()) {
178                 decode_subtitle_packet ();
179         }
180
181         av_free_packet (&_packet);
182 }
183
184 /** @param data pointer to array of pointers to buffers.
185  *  Only the first buffer will be used for non-planar data, otherwise there will be one per channel.
186  */
187 shared_ptr<AudioBuffers>
188 FFmpegDecoder::deinterleave_audio (uint8_t** data, int size)
189 {
190         assert (_ffmpeg_content->audio_channels());
191         assert (bytes_per_audio_sample());
192
193         /* Deinterleave and convert to float */
194
195         assert ((size % (bytes_per_audio_sample() * _ffmpeg_content->audio_channels())) == 0);
196
197         int const total_samples = size / bytes_per_audio_sample();
198         int const frames = total_samples / _ffmpeg_content->audio_channels();
199         shared_ptr<AudioBuffers> audio (new AudioBuffers (_ffmpeg_content->audio_channels(), frames));
200
201         switch (audio_sample_format()) {
202         case AV_SAMPLE_FMT_S16:
203         {
204                 int16_t* p = reinterpret_cast<int16_t *> (data[0]);
205                 int sample = 0;
206                 int channel = 0;
207                 for (int i = 0; i < total_samples; ++i) {
208                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
209
210                         ++channel;
211                         if (channel == _ffmpeg_content->audio_channels()) {
212                                 channel = 0;
213                                 ++sample;
214                         }
215                 }
216         }
217         break;
218
219         case AV_SAMPLE_FMT_S16P:
220         {
221                 int16_t** p = reinterpret_cast<int16_t **> (data);
222                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
223                         for (int j = 0; j < frames; ++j) {
224                                 audio->data(i)[j] = static_cast<float>(p[i][j]) / (1 << 15);
225                         }
226                 }
227         }
228         break;
229         
230         case AV_SAMPLE_FMT_S32:
231         {
232                 int32_t* p = reinterpret_cast<int32_t *> (data[0]);
233                 int sample = 0;
234                 int channel = 0;
235                 for (int i = 0; i < total_samples; ++i) {
236                         audio->data(channel)[sample] = static_cast<float>(*p++) / (1 << 31);
237
238                         ++channel;
239                         if (channel == _ffmpeg_content->audio_channels()) {
240                                 channel = 0;
241                                 ++sample;
242                         }
243                 }
244         }
245         break;
246
247         case AV_SAMPLE_FMT_FLT:
248         {
249                 float* p = reinterpret_cast<float*> (data[0]);
250                 int sample = 0;
251                 int channel = 0;
252                 for (int i = 0; i < total_samples; ++i) {
253                         audio->data(channel)[sample] = *p++;
254
255                         ++channel;
256                         if (channel == _ffmpeg_content->audio_channels()) {
257                                 channel = 0;
258                                 ++sample;
259                         }
260                 }
261         }
262         break;
263                 
264         case AV_SAMPLE_FMT_FLTP:
265         {
266                 float** p = reinterpret_cast<float**> (data);
267                 for (int i = 0; i < _ffmpeg_content->audio_channels(); ++i) {
268                         memcpy (audio->data(i), p[i], frames * sizeof(float));
269                 }
270         }
271         break;
272
273         default:
274                 throw DecodeError (String::compose (_("Unrecognised audio sample format (%1)"), static_cast<int> (audio_sample_format())));
275         }
276
277         return audio;
278 }
279
280 AVSampleFormat
281 FFmpegDecoder::audio_sample_format () const
282 {
283         if (!_ffmpeg_content->audio_stream()) {
284                 return (AVSampleFormat) 0;
285         }
286         
287         return audio_codec_context()->sample_fmt;
288 }
289
290 int
291 FFmpegDecoder::bytes_per_audio_sample () const
292 {
293         return av_get_bytes_per_sample (audio_sample_format ());
294 }
295
296 void
297 FFmpegDecoder::seek (VideoContent::Frame frame, bool accurate)
298 {
299         double const time_base = av_q2d (_format_context->streams[_video_stream]->time_base);
300
301         /* If we are doing an accurate seek, our initial shot will be 5 frames (5 being
302            a number plucked from the air) earlier than we want to end up.  The loop below
303            will hopefully then step through to where we want to be.
304         */
305         int initial = frame;
306
307         if (accurate) {
308                 initial -= 5;
309         }
310
311         if (initial < 0) {
312                 initial = 0;
313         }
314
315         /* Initial seek time in the stream's timebase */
316         int64_t const initial_vt = ((initial / _ffmpeg_content->video_frame_rate()) - _pts_offset) / time_base;
317
318         av_seek_frame (_format_context, _video_stream, initial_vt, AVSEEK_FLAG_BACKWARD);
319
320         avcodec_flush_buffers (video_codec_context());
321         if (_subtitle_codec_context) {
322                 avcodec_flush_buffers (_subtitle_codec_context);
323         }
324
325         /* This !accurate is piling hack upon hack; setting _just_sought to true
326            even with accurate == true defeats our attempt to align the start
327            of the video and audio.  Here we disable that defeat when accurate == true
328            i.e. when we are making a DCP rather than just previewing one.
329            Ewww.  This should be gone in 2.0.
330         */
331         if (!accurate) {
332                 _just_sought = true;
333         }
334         
335         _video_position = frame;
336         
337         if (frame == 0 || !accurate) {
338                 /* We're already there, or we're as close as we need to be */
339                 return;
340         }
341
342         while (1) {
343                 int r = av_read_frame (_format_context, &_packet);
344                 if (r < 0) {
345                         return;
346                 }
347
348                 if (_packet.stream_index != _video_stream) {
349                         av_free_packet (&_packet);
350                         continue;
351                 }
352                 
353                 int finished = 0;
354                 r = avcodec_decode_video2 (video_codec_context(), _frame, &finished, &_packet);
355                 if (r >= 0 && finished) {
356                         _video_position = rint (
357                                 (av_frame_get_best_effort_timestamp (_frame) * time_base + _pts_offset) * _ffmpeg_content->video_frame_rate()
358                                 );
359
360                         if (_video_position >= (frame - 1)) {
361                                 av_free_packet (&_packet);
362                                 break;
363                         }
364                 }
365                 
366                 av_free_packet (&_packet);
367         }
368 }
369
370 void
371 FFmpegDecoder::decode_audio_packet ()
372 {
373         /* Audio packets can contain multiple frames, so we may have to call avcodec_decode_audio4
374            several times.
375         */
376         
377         AVPacket copy_packet = _packet;
378         
379         while (copy_packet.size > 0) {
380
381                 int frame_finished;
382                 int const decode_result = avcodec_decode_audio4 (audio_codec_context(), _frame, &frame_finished, &copy_packet);
383                 if (decode_result < 0) {
384                         shared_ptr<const Film> film = _film.lock ();
385                         assert (film);
386                         film->log()->log (String::compose ("avcodec_decode_audio4 failed (%1)", decode_result));
387                         return;
388                 }
389
390                 if (frame_finished) {
391                         
392                         if (_audio_position == 0) {
393                                 /* Where we are in the source, in seconds */
394                                 double const pts = av_q2d (_format_context->streams[copy_packet.stream_index]->time_base)
395                                         * av_frame_get_best_effort_timestamp(_frame) + _pts_offset;
396
397                                 if (pts > 0) {
398                                         /* Emit some silence */
399                                         shared_ptr<AudioBuffers> silence (
400                                                 new AudioBuffers (
401                                                         _ffmpeg_content->audio_channels(),
402                                                         pts * _ffmpeg_content->content_audio_frame_rate()
403                                                         )
404                                                 );
405                                         
406                                         silence->make_silent ();
407                                         audio (silence, _audio_position);
408                                 }
409                         }
410                         
411                         int const data_size = av_samples_get_buffer_size (
412                                 0, audio_codec_context()->channels, _frame->nb_samples, audio_sample_format (), 1
413                                 );
414                         
415                         audio (deinterleave_audio (_frame->data, data_size), _audio_position);
416                 }
417                         
418                 copy_packet.data += decode_result;
419                 copy_packet.size -= decode_result;
420         }
421 }
422
423 bool
424 FFmpegDecoder::decode_video_packet ()
425 {
426         int frame_finished;
427         if (avcodec_decode_video2 (video_codec_context(), _frame, &frame_finished, &_packet) < 0 || !frame_finished) {
428                 return false;
429         }
430
431         boost::mutex::scoped_lock lm (_filter_graphs_mutex);
432
433         shared_ptr<FilterGraph> graph;
434         
435         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
436         while (i != _filter_graphs.end() && !(*i)->can_process (libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format)) {
437                 ++i;
438         }
439
440         if (i == _filter_graphs.end ()) {
441                 shared_ptr<const Film> film = _film.lock ();
442                 assert (film);
443
444                 graph.reset (new FilterGraph (_ffmpeg_content, libdcp::Size (_frame->width, _frame->height), (AVPixelFormat) _frame->format));
445                 _filter_graphs.push_back (graph);
446
447                 film->log()->log (String::compose (N_("New graph for %1x%2, pixel format %3"), _frame->width, _frame->height, _frame->format));
448         } else {
449                 graph = *i;
450         }
451
452         list<pair<shared_ptr<Image>, int64_t> > images = graph->process (_frame);
453
454         string post_process = Filter::ffmpeg_strings (_ffmpeg_content->filters()).second;
455         
456         for (list<pair<shared_ptr<Image>, int64_t> >::iterator i = images.begin(); i != images.end(); ++i) {
457
458                 shared_ptr<Image> image = i->first;
459                 if (!post_process.empty ()) {
460                         image = image->post_process (post_process, true);
461                 }
462                 
463                 if (i->second != AV_NOPTS_VALUE) {
464
465                         double const pts = i->second * av_q2d (_format_context->streams[_video_stream]->time_base) + _pts_offset;
466
467                         if (_just_sought) {
468                                 /* We just did a seek, so disable any attempts to correct for where we
469                                    are / should be.
470                                 */
471                                 _video_position = rint (pts * _ffmpeg_content->video_frame_rate ());
472                                 _just_sought = false;
473                         }
474
475                         double const next = _video_position / _ffmpeg_content->video_frame_rate();
476                         double const one_frame = 1 / _ffmpeg_content->video_frame_rate ();
477                         double delta = pts - next;
478
479                         while (delta > one_frame) {
480                                 /* This PTS is more than one frame forward in time of where we think we should be; emit
481                                    a black frame.
482                                 */
483
484                                 /* XXX: I think this should be a copy of the last frame... */
485                                 boost::shared_ptr<Image> black (
486                                         new Image (
487                                                 static_cast<AVPixelFormat> (_frame->format),
488                                                 libdcp::Size (video_codec_context()->width, video_codec_context()->height),
489                                                 true
490                                                 )
491                                         );
492                                 
493                                 black->make_black ();
494                                 video (image, false, _video_position);
495                                 delta -= one_frame;
496                         }
497
498                         if (delta > -one_frame) {
499                                 /* This PTS is within a frame of being right; emit this (otherwise it will be dropped) */
500                                 video (image, false, _video_position);
501                         }
502                                 
503                 } else {
504                         shared_ptr<const Film> film = _film.lock ();
505                         assert (film);
506                         film->log()->log ("Dropping frame without PTS");
507                 }
508         }
509
510         return true;
511 }
512
513         
514 void
515 FFmpegDecoder::setup_subtitle ()
516 {
517         boost::mutex::scoped_lock lm (_mutex);
518         
519         if (!_ffmpeg_content->subtitle_stream() || _ffmpeg_content->subtitle_stream()->index (_format_context) >= int (_format_context->nb_streams)) {
520                 return;
521         }
522
523         _subtitle_codec_context = _ffmpeg_content->subtitle_stream()->stream(_format_context)->codec;
524         _subtitle_codec = avcodec_find_decoder (_subtitle_codec_context->codec_id);
525
526         if (_subtitle_codec == 0) {
527                 throw DecodeError (_("could not find subtitle decoder"));
528         }
529         
530         if (avcodec_open2 (_subtitle_codec_context, _subtitle_codec, 0) < 0) {
531                 throw DecodeError (N_("could not open subtitle decoder"));
532         }
533 }
534
535 bool
536 FFmpegDecoder::done () const
537 {
538         bool const vd = !_decode_video || (_video_position >= _ffmpeg_content->video_length());
539         bool const ad = !_decode_audio || !_ffmpeg_content->audio_stream() || (_audio_position >= _ffmpeg_content->audio_length());
540         return vd && ad;
541 }
542         
543 void
544 FFmpegDecoder::decode_subtitle_packet ()
545 {
546         int got_subtitle;
547         AVSubtitle sub;
548         if (avcodec_decode_subtitle2 (_subtitle_codec_context, &sub, &got_subtitle, &_packet) < 0 || !got_subtitle) {
549                 return;
550         }
551
552         /* Sometimes we get an empty AVSubtitle, which is used by some codecs to
553            indicate that the previous subtitle should stop.
554         */
555         if (sub.num_rects <= 0) {
556                 subtitle (shared_ptr<Image> (), dcpomatic::Rect<double> (), 0, 0);
557                 return;
558         } else if (sub.num_rects > 1) {
559                 throw DecodeError (_("multi-part subtitles not yet supported"));
560         }
561                 
562         /* Subtitle PTS in seconds (within the source, not taking into account any of the
563            source that we may have chopped off for the DCP)
564         */
565         double const packet_time = (static_cast<double> (sub.pts ) / AV_TIME_BASE) + _pts_offset;
566
567         /* hence start time for this sub */
568         Time const from = (packet_time + (double (sub.start_display_time) / 1e3)) * TIME_HZ;
569         Time const to = (packet_time + (double (sub.end_display_time) / 1e3)) * TIME_HZ;
570
571         AVSubtitleRect const * rect = sub.rects[0];
572
573         if (rect->type != SUBTITLE_BITMAP) {
574                 throw DecodeError (_("non-bitmap subtitles not yet supported"));
575         }
576
577         /* Note RGBA is expressed little-endian, so the first byte in the word is R, second
578            G, third B, fourth A.
579         */
580         shared_ptr<Image> image (new Image (PIX_FMT_RGBA, libdcp::Size (rect->w, rect->h), true));
581
582         /* Start of the first line in the subtitle */
583         uint8_t* sub_p = rect->pict.data[0];
584         /* sub_p looks up into a BGRA palette which is here
585            (i.e. first byte B, second G, third R, fourth A)
586         */
587         uint32_t const * palette = (uint32_t *) rect->pict.data[1];
588         /* Start of the output data */
589         uint32_t* out_p = (uint32_t *) image->data()[0];
590
591         for (int y = 0; y < rect->h; ++y) {
592                 uint8_t* sub_line_p = sub_p;
593                 uint32_t* out_line_p = out_p;
594                 for (int x = 0; x < rect->w; ++x) {
595                         uint32_t const p = palette[*sub_line_p++];
596                         *out_line_p++ = ((p & 0xff) << 16) | (p & 0xff00) | ((p & 0xff0000) >> 16) | (p & 0xff000000);
597                 }
598                 sub_p += rect->pict.linesize[0];
599                 out_p += image->stride()[0] / sizeof (uint32_t);
600         }
601
602         libdcp::Size const vs = _ffmpeg_content->video_size ();
603
604         subtitle (
605                 image,
606                 dcpomatic::Rect<double> (
607                         static_cast<double> (rect->x) / vs.width,
608                         static_cast<double> (rect->y) / vs.height,
609                         static_cast<double> (rect->w) / vs.width,
610                         static_cast<double> (rect->h) / vs.height
611                         ),
612                 from,
613                 to
614                 );
615                           
616         
617         avsubtitle_free (&sub);
618 }