Fix assertion failure with .MTS files.
[dcpomatic.git] / src / lib / ffmpeg_examiner.cc
1 /*
2     Copyright (C) 2013-2015 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 extern "C" {
21 #include <libavcodec/avcodec.h>
22 #include <libavformat/avformat.h>
23 #include <libavutil/pixfmt.h>
24 #include <libavutil/pixdesc.h>
25 }
26 #include "ffmpeg_examiner.h"
27 #include "ffmpeg_content.h"
28 #include "job.h"
29 #include "ffmpeg_audio_stream.h"
30 #include "ffmpeg_subtitle_stream.h"
31 #include "util.h"
32 #include "safe_stringstream.h"
33 #include <iostream>
34
35 #include "i18n.h"
36
37 using std::string;
38 using std::cout;
39 using std::max;
40 using boost::shared_ptr;
41 using boost::optional;
42
43 /** @param job job that the examiner is operating in, or 0 */
44 FFmpegExaminer::FFmpegExaminer (shared_ptr<const FFmpegContent> c, shared_ptr<Job> job)
45         : FFmpeg (c)
46         , _video_length (0)
47         , _need_video_length (false)
48 {
49         /* Find audio and subtitle streams */
50
51         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
52                 AVStream* s = _format_context->streams[i];
53                 if (s->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
54
55                         /* This is a hack; sometimes it seems that _audio_codec_context->channel_layout isn't set up,
56                            so bodge it here.  No idea why we should have to do this.
57                         */
58
59                         if (s->codec->channel_layout == 0) {
60                                 s->codec->channel_layout = av_get_default_channel_layout (s->codec->channels);
61                         }
62
63                         _audio_streams.push_back (
64                                 shared_ptr<FFmpegAudioStream> (
65                                         new FFmpegAudioStream (audio_stream_name (s), s->id, s->codec->sample_rate, s->codec->channels)
66                                         )
67                                 );
68
69                 } else if (s->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
70                         _subtitle_streams.push_back (shared_ptr<FFmpegSubtitleStream> (new FFmpegSubtitleStream (subtitle_stream_name (s), s->id)));
71                 }
72         }
73
74         /* See if the header has duration information in it */
75         _need_video_length = _format_context->duration == AV_NOPTS_VALUE;
76         if (!_need_video_length) {
77                 _video_length = (double (_format_context->duration) / AV_TIME_BASE) * video_frame_rate().get ();
78         } else if (job) {
79                 job->sub (_("Finding length"));
80                 job->set_progress_unknown ();
81         }
82
83         if (job) {
84                 job->sub (_("Finding subtitles"));
85         }
86
87         /* Run through until we find:
88          *   - the first video.
89          *   - the first audio for each stream.
90          *   - the subtitle periods for each stream.
91          *
92          * We have to note subtitle periods as otherwise we have no way of knowing
93          * where we should look for subtitles (video and audio are always present,
94          * so they are ok).
95          */
96
97         while (true) {
98                 int r = av_read_frame (_format_context, &_packet);
99                 if (r < 0) {
100                         break;
101                 }
102
103                 if (job) {
104                         job->set_progress_unknown ();
105                 }
106
107                 AVCodecContext* context = _format_context->streams[_packet.stream_index]->codec;
108
109                 if (_packet.stream_index == _video_stream) {
110                         video_packet (context);
111                 }
112
113                 bool got_all_audio = true;
114
115                 for (size_t i = 0; i < _audio_streams.size(); ++i) {
116                         if (_audio_streams[i]->uses_index (_format_context, _packet.stream_index)) {
117                                 audio_packet (context, _audio_streams[i]);
118                         }
119                         if (!_audio_streams[i]->first_audio) {
120                                 got_all_audio = false;
121                         }
122                 }
123
124                 for (size_t i = 0; i < _subtitle_streams.size(); ++i) {
125                         if (_subtitle_streams[i]->uses_index (_format_context, _packet.stream_index)) {
126                                 subtitle_packet (context, _subtitle_streams[i]);
127                         }
128                 }
129
130                 av_free_packet (&_packet);
131
132                 if (_first_video && got_all_audio && _subtitle_streams.empty ()) {
133                         /* All done */
134                         break;
135                 }
136         }
137
138         for (LastSubtitleMap::const_iterator i = _last_subtitle_start.begin(); i != _last_subtitle_start.end(); ++i) {
139                 if (i->second) {
140                         i->first->add_subtitle (
141                                 ContentTimePeriod (
142                                         i->second.get (),
143                                         ContentTime::from_frames (video_length(), video_frame_rate().get_value_or (24))
144                                         )
145                                 );
146                 }
147         }
148 }
149
150 void
151 FFmpegExaminer::video_packet (AVCodecContext* context)
152 {
153         if (_first_video && !_need_video_length) {
154                 return;
155         }
156
157         int frame_finished;
158         if (avcodec_decode_video2 (context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
159                 if (!_first_video) {
160                         _first_video = frame_time (_format_context->streams[_video_stream]);
161                 }
162                 if (_need_video_length) {
163                         _video_length = frame_time (
164                                 _format_context->streams[_video_stream]
165                                 ).get_value_or (ContentTime ()).frames_round (video_frame_rate().get ());
166                 }
167         }
168 }
169
170 void
171 FFmpegExaminer::audio_packet (AVCodecContext* context, shared_ptr<FFmpegAudioStream> stream)
172 {
173         if (stream->first_audio) {
174                 return;
175         }
176
177         int frame_finished;
178         if (avcodec_decode_audio4 (context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
179                 stream->first_audio = frame_time (stream->stream (_format_context));
180         }
181 }
182
183 void
184 FFmpegExaminer::subtitle_packet (AVCodecContext* context, shared_ptr<FFmpegSubtitleStream> stream)
185 {
186         int frame_finished;
187         AVSubtitle sub;
188         if (avcodec_decode_subtitle2 (context, &sub, &frame_finished, &_packet) >= 0 && frame_finished) {
189                 FFmpegSubtitlePeriod const period = subtitle_period (sub);
190                 LastSubtitleMap::iterator last = _last_subtitle_start.find (stream);
191                 if (last != _last_subtitle_start.end() && last->second) {
192                         /* We have seen the start of a subtitle but not yet the end.  Whatever this is
193                            finishes the previous subtitle, so add it */
194                         stream->add_subtitle (ContentTimePeriod (last->second.get (), period.from));
195                         if (sub.num_rects == 0) {
196                                 /* This is a `proper' end-of-subtitle */
197                                 _last_subtitle_start[stream] = optional<ContentTime> ();
198                         } else {
199                                 /* This is just another subtitle, so we start again */
200                                 _last_subtitle_start[stream] = period.from;
201                         }
202                 } else if (sub.num_rects == 1) {
203                         if (period.to) {
204                                 stream->add_subtitle (ContentTimePeriod (period.from, period.to.get ()));
205                         } else {
206                                 _last_subtitle_start[stream] = period.from;
207                         }
208                 }
209                 avsubtitle_free (&sub);
210         }
211 }
212
213 optional<ContentTime>
214 FFmpegExaminer::frame_time (AVStream* s) const
215 {
216         optional<ContentTime> t;
217
218         int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
219         if (bet != AV_NOPTS_VALUE) {
220                 t = ContentTime::from_seconds (bet * av_q2d (s->time_base));
221         }
222
223         return t;
224 }
225
226 optional<double>
227 FFmpegExaminer::video_frame_rate () const
228 {
229         /* This use of r_frame_rate is debateable; there's a few different
230          * frame rates in the format context, but this one seems to be the most
231          * reliable.
232          */
233         return av_q2d (av_stream_get_r_frame_rate (_format_context->streams[_video_stream]));
234 }
235
236 dcp::Size
237 FFmpegExaminer::video_size () const
238 {
239         return dcp::Size (video_codec_context()->width, video_codec_context()->height);
240 }
241
242 /** @return Length according to our content's header */
243 Frame
244 FFmpegExaminer::video_length () const
245 {
246         return max (Frame (1), _video_length);
247 }
248
249 optional<double>
250 FFmpegExaminer::sample_aspect_ratio () const
251 {
252         AVRational sar = av_guess_sample_aspect_ratio (_format_context, _format_context->streams[_video_stream], 0);
253         if (sar.num == 0) {
254                 /* I assume this means that we don't know */
255                 return optional<double> ();
256         }
257         return double (sar.num) / sar.den;
258 }
259
260 string
261 FFmpegExaminer::audio_stream_name (AVStream* s) const
262 {
263         SafeStringStream n;
264
265         n << stream_name (s);
266
267         if (!n.str().empty()) {
268                 n << "; ";
269         }
270
271         n << s->codec->channels << " channels";
272
273         return n.str ();
274 }
275
276 string
277 FFmpegExaminer::subtitle_stream_name (AVStream* s) const
278 {
279         SafeStringStream n;
280
281         n << stream_name (s);
282
283         if (n.str().empty()) {
284                 n << _("unknown");
285         }
286
287         return n.str ();
288 }
289
290 string
291 FFmpegExaminer::stream_name (AVStream* s) const
292 {
293         SafeStringStream n;
294
295         if (s->metadata) {
296                 AVDictionaryEntry const * lang = av_dict_get (s->metadata, "language", 0, 0);
297                 if (lang) {
298                         n << lang->value;
299                 }
300
301                 AVDictionaryEntry const * title = av_dict_get (s->metadata, "title", 0, 0);
302                 if (title) {
303                         if (!n.str().empty()) {
304                                 n << " ";
305                         }
306                         n << title->value;
307                 }
308         }
309
310         return n.str ();
311 }
312
313 int
314 FFmpegExaminer::bits_per_pixel () const
315 {
316         return av_get_bits_per_pixel (av_pix_fmt_desc_get (video_codec_context()->pix_fmt));
317 }