Speculative fix for failure to pick up correct audio / subtitle streams.
[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 extern "C" {
32 #include <tiffio.h>
33 #include <libavcodec/avcodec.h>
34 #include <libavformat/avformat.h>
35 #include <libswscale/swscale.h>
36 #include <libpostproc/postprocess.h>
37 }
38 #include <sndfile.h>
39 #include "film.h"
40 #include "format.h"
41 #include "transcoder.h"
42 #include "job.h"
43 #include "filter.h"
44 #include "film_state.h"
45 #include "options.h"
46 #include "exceptions.h"
47 #include "image.h"
48 #include "util.h"
49 #include "log.h"
50 #include "ffmpeg_decoder.h"
51 #include "subtitle.h"
52
53 using namespace std;
54 using namespace boost;
55
56 FFmpegDecoder::FFmpegDecoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
57         : Decoder (s, o, j, l, minimal, ignore_length)
58         , _format_context (0)
59         , _video_stream (-1)
60         , _audio_stream (-1)
61         , _subtitle_stream (-1)
62         , _frame (0)
63         , _video_codec_context (0)
64         , _video_codec (0)
65         , _audio_codec_context (0)
66         , _audio_codec (0)
67         , _subtitle_codec_context (0)
68         , _subtitle_codec (0)
69 {
70         setup_general ();
71         setup_video ();
72         setup_audio ();
73         setup_subtitle ();
74 }
75
76 FFmpegDecoder::~FFmpegDecoder ()
77 {
78         if (_audio_codec_context) {
79                 avcodec_close (_audio_codec_context);
80         }
81         
82         if (_video_codec_context) {
83                 avcodec_close (_video_codec_context);
84         }
85
86         if (_subtitle_codec_context) {
87                 avcodec_close (_subtitle_codec_context);
88         }
89         
90         av_free (_frame);
91         avformat_close_input (&_format_context);
92 }       
93
94 void
95 FFmpegDecoder::setup_general ()
96 {
97         int r;
98         
99         av_register_all ();
100
101         if ((r = avformat_open_input (&_format_context, _fs->content_path().c_str(), 0, 0)) != 0) {
102                 throw OpenFileError (_fs->content_path ());
103         }
104
105         if (avformat_find_stream_info (_format_context, 0) < 0) {
106                 throw DecodeError ("could not find stream information");
107         }
108
109         /* Find video, audio and subtitle streams and choose the first of each */
110
111         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
112                 if (_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
113                         _video_stream = i;
114                 } else if (_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
115                         if (_audio_stream == -1) {
116                                 _audio_stream = i;
117                         }
118                         _audio_streams.push_back (Stream (stream_name (_format_context->streams[i]), i));
119                 } else if (_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
120                         if (_subtitle_stream == -1) {
121                                 _subtitle_stream = i;
122                         }
123                         _subtitle_streams.push_back (Stream (stream_name (_format_context->streams[i]), i));
124                 }
125         }
126
127         /* Now override audio and subtitle streams with those from the Film, if it has any */
128
129         if (_fs->audio_stream() != -1) {
130                 vector<Stream>::iterator i = _audio_streams.begin ();
131                 while (i != _audio_streams.end() && i->id != _fs->audio_stream()) {
132                         ++i;
133                 }
134
135                 if (i != _audio_streams.end()) {
136                         _audio_stream = _fs->audio_stream ();
137                 }
138         }
139
140         if (_fs->subtitle_stream() != -1) {
141                 vector<Stream>::iterator i = _subtitle_streams.begin ();
142                 while (i != _subtitle_streams.end() && i->id != _fs->subtitle_stream()) {
143                         ++i;
144                 }
145
146                 if (i != _subtitle_streams.end()) {
147                         _subtitle_stream = _fs->subtitle_stream ();
148                 }
149         }
150
151         if (_video_stream < 0) {
152                 throw DecodeError ("could not find video stream");
153         }
154
155         _frame = avcodec_alloc_frame ();
156         if (_frame == 0) {
157                 throw DecodeError ("could not allocate frame");
158         }
159 }
160
161 void
162 FFmpegDecoder::setup_video ()
163 {
164         _video_codec_context = _format_context->streams[_video_stream]->codec;
165         _video_codec = avcodec_find_decoder (_video_codec_context->codec_id);
166
167         if (_video_codec == 0) {
168                 throw DecodeError ("could not find video decoder");
169         }
170         
171         if (avcodec_open2 (_video_codec_context, _video_codec, 0) < 0) {
172                 throw DecodeError ("could not open video decoder");
173         }
174 }
175
176 void
177 FFmpegDecoder::setup_audio ()
178 {
179         if (_audio_stream < 0) {
180                 return;
181         }
182         
183         _audio_codec_context = _format_context->streams[_audio_stream]->codec;
184         _audio_codec = avcodec_find_decoder (_audio_codec_context->codec_id);
185
186         if (_audio_codec == 0) {
187                 throw DecodeError ("could not find audio decoder");
188         }
189
190         if (avcodec_open2 (_audio_codec_context, _audio_codec, 0) < 0) {
191                 throw DecodeError ("could not open audio decoder");
192         }
193
194         /* This is a hack; sometimes it seems that _audio_codec_context->channel_layout isn't set up,
195            so bodge it here.  No idea why we should have to do this.
196         */
197
198         if (_audio_codec_context->channel_layout == 0) {
199                 _audio_codec_context->channel_layout = av_get_default_channel_layout (audio_channels ());
200         }
201 }
202
203 void
204 FFmpegDecoder::setup_subtitle ()
205 {
206         if (_subtitle_stream < 0) {
207                 return;
208         }
209
210         _subtitle_codec_context = _format_context->streams[_subtitle_stream]->codec;
211         _subtitle_codec = avcodec_find_decoder (_subtitle_codec_context->codec_id);
212
213         if (_subtitle_codec == 0) {
214                 throw DecodeError ("could not find subtitle decoder");
215         }
216         
217         if (avcodec_open2 (_subtitle_codec_context, _subtitle_codec, 0) < 0) {
218                 throw DecodeError ("could not open subtitle decoder");
219         }
220 }
221
222
223 bool
224 FFmpegDecoder::do_pass ()
225 {
226         int r = av_read_frame (_format_context, &_packet);
227         if (r < 0) {
228                 if (r != AVERROR_EOF) {
229                         throw DecodeError ("error on av_read_frame");
230                 }
231                 
232                 /* Get any remaining frames */
233                 
234                 _packet.data = 0;
235                 _packet.size = 0;
236
237                 int frame_finished;
238
239                 while (avcodec_decode_video2 (_video_codec_context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
240                         process_video (_frame);
241                 }
242
243                 if (_audio_stream >= 0 && _opt->decode_audio) {
244                         while (avcodec_decode_audio4 (_audio_codec_context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
245                                 int const data_size = av_samples_get_buffer_size (
246                                         0, _audio_codec_context->channels, _frame->nb_samples, audio_sample_format (), 1
247                                         );
248                                 
249                                 assert (_audio_codec_context->channels == _fs->audio_channels());
250                                 process_audio (_frame->data[0], data_size);
251                         }
252                 }
253
254                 return true;
255         }
256
257         if (_packet.stream_index == _video_stream) {
258
259                 int frame_finished;
260                 if (avcodec_decode_video2 (_video_codec_context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
261                         process_video (_frame);
262                 }
263
264         } else if (_audio_stream >= 0 && _packet.stream_index == _audio_stream && _opt->decode_audio) {
265                 
266                 avcodec_get_frame_defaults (_frame);
267                 
268                 int frame_finished;
269                 if (avcodec_decode_audio4 (_audio_codec_context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
270                         int const data_size = av_samples_get_buffer_size (
271                                 0, _audio_codec_context->channels, _frame->nb_samples, audio_sample_format (), 1
272                                 );
273
274                         assert (_audio_codec_context->channels == _fs->audio_channels());
275                         process_audio (_frame->data[0], data_size);
276                 }
277
278         } else if (_subtitle_stream >= 0 && _packet.stream_index == _subtitle_stream && _opt->decode_subtitles) {
279
280                 int got_subtitle;
281                 AVSubtitle sub;
282                 if (avcodec_decode_subtitle2 (_subtitle_codec_context, &sub, &got_subtitle, &_packet) && got_subtitle) {
283                         /* I'm not entirely sure why, but sometimes we get an AVSubtitle with
284                            no AVSubtitleRects.
285                         */
286                         if (sub.num_rects > 0) {
287                                 process_subtitle (shared_ptr<TimedSubtitle> (new TimedSubtitle (sub)));
288                         }
289                         avsubtitle_free (&sub);
290                 }
291         }
292         
293         av_free_packet (&_packet);
294         return false;
295 }
296
297 int
298 FFmpegDecoder::length_in_frames () const
299 {
300         return (_format_context->duration / AV_TIME_BASE) * frames_per_second ();
301 }
302
303 float
304 FFmpegDecoder::frames_per_second () const
305 {
306         AVStream* s = _format_context->streams[_video_stream];
307
308         if (s->avg_frame_rate.num && s->avg_frame_rate.den) {
309                 return av_q2d (s->avg_frame_rate);
310         }
311
312         return av_q2d (s->r_frame_rate);
313 }
314
315 int
316 FFmpegDecoder::audio_channels () const
317 {
318         if (_audio_codec_context == 0) {
319                 return 0;
320         }
321
322         return _audio_codec_context->channels;
323 }
324
325 int
326 FFmpegDecoder::audio_sample_rate () const
327 {
328         if (_audio_codec_context == 0) {
329                 return 0;
330         }
331         
332         return _audio_codec_context->sample_rate;
333 }
334
335 AVSampleFormat
336 FFmpegDecoder::audio_sample_format () const
337 {
338         if (_audio_codec_context == 0) {
339                 return (AVSampleFormat) 0;
340         }
341         
342         return _audio_codec_context->sample_fmt;
343 }
344
345 int64_t
346 FFmpegDecoder::audio_channel_layout () const
347 {
348         if (_audio_codec_context == 0) {
349                 return 0;
350         }
351         
352         return _audio_codec_context->channel_layout;
353 }
354
355 Size
356 FFmpegDecoder::native_size () const
357 {
358         return Size (_video_codec_context->width, _video_codec_context->height);
359 }
360
361 PixelFormat
362 FFmpegDecoder::pixel_format () const
363 {
364         return _video_codec_context->pix_fmt;
365 }
366
367 int
368 FFmpegDecoder::time_base_numerator () const
369 {
370         return _video_codec_context->time_base.num;
371 }
372
373 int
374 FFmpegDecoder::time_base_denominator () const
375 {
376         return _video_codec_context->time_base.den;
377 }
378
379 int
380 FFmpegDecoder::sample_aspect_ratio_numerator () const
381 {
382         return _video_codec_context->sample_aspect_ratio.num;
383 }
384
385 int
386 FFmpegDecoder::sample_aspect_ratio_denominator () const
387 {
388         return _video_codec_context->sample_aspect_ratio.den;
389 }
390
391 bool
392 FFmpegDecoder::has_subtitles () const
393 {
394         return (_subtitle_stream != -1);
395 }
396
397 vector<Stream>
398 FFmpegDecoder::audio_streams () const
399 {
400         return _audio_streams;
401 }
402
403 vector<Stream>
404 FFmpegDecoder::subtitle_streams () const
405 {
406         return _subtitle_streams;
407 }
408
409 void
410 FFmpegDecoder::set_audio_stream (int s)
411 {
412         _audio_stream = s;
413         setup_audio ();
414 }
415
416 void
417 FFmpegDecoder::set_subtitle_stream (int s)
418 {
419         _subtitle_stream = s;
420         setup_subtitle ();
421 }
422
423 string
424 FFmpegDecoder::stream_name (AVStream* s) const
425 {
426         stringstream n;
427         
428         AVDictionaryEntry const * lang = av_dict_get (s->metadata, "language", 0, 0);
429         if (lang) {
430                 n << lang->value;
431         }
432         
433         AVDictionaryEntry const * title = av_dict_get (s->metadata, "title", 0, 0);
434         if (title) {
435                 if (!n.str().empty()) {
436                         n << " ";
437                 }
438                 n << title->value;
439         }
440
441         if (n.str().empty()) {
442                 n << "unknown";
443         }
444
445         return n.str ();
446 }