b75d6c5149ced496e4cb1eb4dd60b17d3aa9df67
[dcpomatic.git] / src / lib / ffmpeg_examiner.cc
1 /*
2     Copyright (C) 2013-2015 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic 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     DCP-o-matic 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 DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "dcpomatic_log.h"
22 #include "ffmpeg_examiner.h"
23 #include "ffmpeg_content.h"
24 #include "job.h"
25 #include "ffmpeg_audio_stream.h"
26 #include "ffmpeg_subtitle_stream.h"
27 #include "util.h"
28 #include "warnings.h"
29 DCPOMATIC_DISABLE_WARNINGS
30 extern "C" {
31 #include <libavcodec/avcodec.h>
32 #include <libavformat/avformat.h>
33 #include <libavutil/pixfmt.h>
34 #include <libavutil/pixdesc.h>
35 #include <libavutil/eval.h>
36 #include <libavutil/display.h>
37 }
38 DCPOMATIC_ENABLE_WARNINGS
39 #include <boost/foreach.hpp>
40 #include <iostream>
41
42 #include "i18n.h"
43
44 using std::string;
45 using std::cout;
46 using std::max;
47 using std::vector;
48 using std::shared_ptr;
49 using boost::optional;
50 using namespace dcpomatic;
51
52
53 /* This is how many frames from the start of any video that we will examine to see if we
54  * can spot soft 2:3 pull-down ("telecine").
55  */
56 static const int PULLDOWN_CHECK_FRAMES = 16;
57
58
59 /** @param job job that the examiner is operating in, or 0 */
60 FFmpegExaminer::FFmpegExaminer (shared_ptr<const FFmpegContent> c, shared_ptr<Job> job)
61         : FFmpeg (c)
62         , _video_length (0)
63         , _need_video_length (false)
64         , _pulldown (false)
65 {
66         /* Find audio and subtitle streams */
67
68         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
69                 AVStream* s = _format_context->streams[i];
70 DCPOMATIC_DISABLE_WARNINGS
71                 if (s->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
72
73                         /* This is a hack; sometimes it seems that _audio_codec_context->channel_layout isn't set up,
74                            so bodge it here.  No idea why we should have to do this.
75                         */
76
77                         if (s->codec->channel_layout == 0) {
78                                 s->codec->channel_layout = av_get_default_channel_layout (s->codec->channels);
79                         }
80
81                         DCPOMATIC_ASSERT (_format_context->duration != AV_NOPTS_VALUE);
82                         DCPOMATIC_ASSERT (s->codec->codec);
83                         DCPOMATIC_ASSERT (s->codec->codec->name);
84
85                         _audio_streams.push_back (
86                                 shared_ptr<FFmpegAudioStream> (
87                                         new FFmpegAudioStream (
88                                                 stream_name (s),
89                                                 s->codec->codec->name,
90                                                 s->id,
91                                                 s->codec->sample_rate,
92                                                 llrint ((double (_format_context->duration) / AV_TIME_BASE) * s->codec->sample_rate),
93                                                 s->codec->channels
94                                                 )
95                                         )
96                                 );
97
98                 } else if (s->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
99                         _subtitle_streams.push_back (shared_ptr<FFmpegSubtitleStream> (new FFmpegSubtitleStream (subtitle_stream_name (s), s->id)));
100                 }
101         }
102
103         if (has_video ()) {
104                 /* See if the header has duration information in it */
105                 _need_video_length = _format_context->duration == AV_NOPTS_VALUE;
106                 if (!_need_video_length) {
107                         _video_length = llrint ((double (_format_context->duration) / AV_TIME_BASE) * video_frame_rate().get());
108                 }
109         }
110
111         if (job && _need_video_length) {
112                 job->sub (_("Finding length"));
113         }
114
115         /* Run through until we find:
116          *   - the first video.
117          *   - the first audio for each stream.
118          *   - the top-field-first and repeat-first-frame values ("temporal_reference") for the first PULLDOWN_CHECK_FRAMES video frames.
119          */
120
121         int64_t const len = _file_group.length ();
122         /* A string which we build up to describe the top-field-first and repeat-first-frame values for the first few frames.
123          * It would be nicer to use something like vector<bool> here but we want to search the array for a pattern later,
124          * and a string seems a reasonably neat way to do that.
125          */
126         string temporal_reference;
127         while (true) {
128                 int r = av_read_frame (_format_context, &_packet);
129                 if (r < 0) {
130                         break;
131                 }
132
133                 if (job) {
134                         if (len > 0) {
135                                 job->set_progress (float (_format_context->pb->pos) / len);
136                         } else {
137                                 job->set_progress_unknown ();
138                         }
139                 }
140
141                 AVCodecContext* context = _format_context->streams[_packet.stream_index]->codec;
142 DCPOMATIC_ENABLE_WARNINGS
143
144                 if (_video_stream && _packet.stream_index == _video_stream.get()) {
145                         video_packet (context, temporal_reference);
146                 }
147
148                 bool got_all_audio = true;
149
150                 for (size_t i = 0; i < _audio_streams.size(); ++i) {
151                         if (_audio_streams[i]->uses_index (_format_context, _packet.stream_index)) {
152                                 audio_packet (context, _audio_streams[i]);
153                         }
154                         if (!_audio_streams[i]->first_audio) {
155                                 got_all_audio = false;
156                         }
157                 }
158
159                 av_packet_unref (&_packet);
160
161                 if (_first_video && got_all_audio && temporal_reference.size() >= (PULLDOWN_CHECK_FRAMES * 2)) {
162                         /* All done */
163                         break;
164                 }
165         }
166
167         if (_video_stream) {
168                 /* This code taken from get_rotation() in ffmpeg:cmdutils.c */
169                 AVStream* stream = _format_context->streams[*_video_stream];
170                 AVDictionaryEntry* rotate_tag = av_dict_get (stream->metadata, "rotate", 0, 0);
171                 uint8_t* displaymatrix = av_stream_get_side_data (stream, AV_PKT_DATA_DISPLAYMATRIX, 0);
172                 _rotation = 0;
173
174                 if (rotate_tag && *rotate_tag->value && strcmp(rotate_tag->value, "0")) {
175                         char *tail;
176                         _rotation = av_strtod (rotate_tag->value, &tail);
177                         if (*tail) {
178                                 _rotation = 0;
179                         }
180                 }
181
182                 if (displaymatrix && !_rotation) {
183                         _rotation = - av_display_rotation_get ((int32_t*) displaymatrix);
184                 }
185
186                 _rotation = *_rotation - 360 * floor (*_rotation / 360 + 0.9 / 360);
187         }
188
189         LOG_GENERAL("Temporal reference was %1", temporal_reference);
190         if (temporal_reference.find("T2T3B2B3T2T3B2B3") != string::npos || temporal_reference.find("B2B3T2T3B2B3T2T3") != string::npos) {
191                 /* The magical sequence (taken from mediainfo) suggests that 2:3 pull-down is in use */
192                 _pulldown = true;
193                 LOG_GENERAL_NC("Suggest that this may be 2:3 pull-down (soft telecine)");
194         }
195 }
196
197
198 /** @param temporal_reference A string to which we should add two characters per frame;
199  *  the first   is T or B depending on whether it's top- or bottom-field first,
200  *  ths seconds is 3 or 2 depending on whether "repeat_pict" is true or not.
201  */
202 void
203 FFmpegExaminer::video_packet (AVCodecContext* context, string& temporal_reference)
204 {
205         DCPOMATIC_ASSERT (_video_stream);
206
207         if (_first_video && !_need_video_length && temporal_reference.size() >= (PULLDOWN_CHECK_FRAMES * 2)) {
208                 return;
209         }
210
211         int frame_finished;
212 DCPOMATIC_DISABLE_WARNINGS
213         if (avcodec_decode_video2 (context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
214 DCPOMATIC_ENABLE_WARNINGS
215                 if (!_first_video) {
216                         _first_video = frame_time (_format_context->streams[_video_stream.get()]);
217                 }
218                 if (_need_video_length) {
219                         _video_length = frame_time (
220                                 _format_context->streams[_video_stream.get()]
221                                 ).get_value_or (ContentTime ()).frames_round (video_frame_rate().get ());
222                 }
223                 if (temporal_reference.size() < (PULLDOWN_CHECK_FRAMES * 2)) {
224                         temporal_reference += (_frame->top_field_first ? "T" : "B");
225                         temporal_reference += (_frame->repeat_pict ? "3" : "2");
226                 }
227         }
228 }
229
230
231 void
232 FFmpegExaminer::audio_packet (AVCodecContext* context, shared_ptr<FFmpegAudioStream> stream)
233 {
234         if (stream->first_audio) {
235                 return;
236         }
237
238         int frame_finished;
239 DCPOMATIC_DISABLE_WARNINGS
240         if (avcodec_decode_audio4 (context, _frame, &frame_finished, &_packet) >= 0 && frame_finished) {
241 DCPOMATIC_ENABLE_WARNINGS
242                 stream->first_audio = frame_time (stream->stream (_format_context));
243         }
244 }
245
246
247 optional<ContentTime>
248 FFmpegExaminer::frame_time (AVStream* s) const
249 {
250         optional<ContentTime> t;
251
252 DCPOMATIC_DISABLE_WARNINGS
253         int64_t const bet = av_frame_get_best_effort_timestamp (_frame);
254 DCPOMATIC_ENABLE_WARNINGS
255         if (bet != AV_NOPTS_VALUE) {
256                 t = ContentTime::from_seconds (bet * av_q2d (s->time_base));
257         }
258
259         return t;
260 }
261
262
263 optional<double>
264 FFmpegExaminer::video_frame_rate () const
265 {
266         DCPOMATIC_ASSERT (_video_stream);
267         return av_q2d(av_guess_frame_rate(_format_context, _format_context->streams[_video_stream.get()], 0));
268 }
269
270 dcp::Size
271 FFmpegExaminer::video_size () const
272 {
273         return dcp::Size (video_codec_context()->width, video_codec_context()->height);
274 }
275
276 /** @return Length according to our content's header */
277 Frame
278 FFmpegExaminer::video_length () const
279 {
280         return max (Frame (1), _video_length);
281 }
282
283 optional<double>
284 FFmpegExaminer::sample_aspect_ratio () const
285 {
286         DCPOMATIC_ASSERT (_video_stream);
287         AVRational sar = av_guess_sample_aspect_ratio (_format_context, _format_context->streams[_video_stream.get()], 0);
288         if (sar.num == 0) {
289                 /* I assume this means that we don't know */
290                 return optional<double> ();
291         }
292         return double (sar.num) / sar.den;
293 }
294
295 string
296 FFmpegExaminer::subtitle_stream_name (AVStream* s) const
297 {
298         string n = stream_name (s);
299
300         if (n.empty()) {
301                 n = _("unknown");
302         }
303
304         return n;
305 }
306
307 string
308 FFmpegExaminer::stream_name (AVStream* s) const
309 {
310         string n;
311
312         if (s->metadata) {
313                 AVDictionaryEntry const * lang = av_dict_get (s->metadata, "language", 0, 0);
314                 if (lang) {
315                         n = lang->value;
316                 }
317
318                 AVDictionaryEntry const * title = av_dict_get (s->metadata, "title", 0, 0);
319                 if (title) {
320                         if (!n.empty()) {
321                                 n += " ";
322                         }
323                         n += title->value;
324                 }
325         }
326
327         return n;
328 }
329
330 optional<int>
331 FFmpegExaminer::bits_per_pixel () const
332 {
333         if (video_codec_context()->pix_fmt == -1) {
334                 return optional<int>();
335         }
336
337         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get (video_codec_context()->pix_fmt);
338         DCPOMATIC_ASSERT (d);
339         return av_get_bits_per_pixel (d);
340 }
341
342 bool
343 FFmpegExaminer::yuv () const
344 {
345         switch (video_codec_context()->pix_fmt) {
346         case AV_PIX_FMT_YUV420P:
347         case AV_PIX_FMT_YUYV422:
348         case AV_PIX_FMT_YUV422P:
349         case AV_PIX_FMT_YUV444P:
350         case AV_PIX_FMT_YUV410P:
351         case AV_PIX_FMT_YUV411P:
352         case AV_PIX_FMT_YUVJ420P:
353         case AV_PIX_FMT_YUVJ422P:
354         case AV_PIX_FMT_YUVJ444P:
355         case AV_PIX_FMT_UYVY422:
356         case AV_PIX_FMT_UYYVYY411:
357         case AV_PIX_FMT_NV12:
358         case AV_PIX_FMT_NV21:
359         case AV_PIX_FMT_YUV440P:
360         case AV_PIX_FMT_YUVJ440P:
361         case AV_PIX_FMT_YUVA420P:
362         case AV_PIX_FMT_YUV420P16LE:
363         case AV_PIX_FMT_YUV420P16BE:
364         case AV_PIX_FMT_YUV422P16LE:
365         case AV_PIX_FMT_YUV422P16BE:
366         case AV_PIX_FMT_YUV444P16LE:
367         case AV_PIX_FMT_YUV444P16BE:
368         case AV_PIX_FMT_YUV420P9BE:
369         case AV_PIX_FMT_YUV420P9LE:
370         case AV_PIX_FMT_YUV420P10BE:
371         case AV_PIX_FMT_YUV420P10LE:
372         case AV_PIX_FMT_YUV422P10BE:
373         case AV_PIX_FMT_YUV422P10LE:
374         case AV_PIX_FMT_YUV444P9BE:
375         case AV_PIX_FMT_YUV444P9LE:
376         case AV_PIX_FMT_YUV444P10BE:
377         case AV_PIX_FMT_YUV444P10LE:
378         case AV_PIX_FMT_YUV422P9BE:
379         case AV_PIX_FMT_YUV422P9LE:
380         case AV_PIX_FMT_YUVA420P9BE:
381         case AV_PIX_FMT_YUVA420P9LE:
382         case AV_PIX_FMT_YUVA422P9BE:
383         case AV_PIX_FMT_YUVA422P9LE:
384         case AV_PIX_FMT_YUVA444P9BE:
385         case AV_PIX_FMT_YUVA444P9LE:
386         case AV_PIX_FMT_YUVA420P10BE:
387         case AV_PIX_FMT_YUVA420P10LE:
388         case AV_PIX_FMT_YUVA422P10BE:
389         case AV_PIX_FMT_YUVA422P10LE:
390         case AV_PIX_FMT_YUVA444P10BE:
391         case AV_PIX_FMT_YUVA444P10LE:
392         case AV_PIX_FMT_YUVA420P16BE:
393         case AV_PIX_FMT_YUVA420P16LE:
394         case AV_PIX_FMT_YUVA422P16BE:
395         case AV_PIX_FMT_YUVA422P16LE:
396         case AV_PIX_FMT_YUVA444P16BE:
397         case AV_PIX_FMT_YUVA444P16LE:
398         case AV_PIX_FMT_NV16:
399         case AV_PIX_FMT_NV20LE:
400         case AV_PIX_FMT_NV20BE:
401         case AV_PIX_FMT_YVYU422:
402         case AV_PIX_FMT_YUVA444P:
403         case AV_PIX_FMT_YUVA422P:
404         case AV_PIX_FMT_YUV420P12BE:
405         case AV_PIX_FMT_YUV420P12LE:
406         case AV_PIX_FMT_YUV420P14BE:
407         case AV_PIX_FMT_YUV420P14LE:
408         case AV_PIX_FMT_YUV422P12BE:
409         case AV_PIX_FMT_YUV422P12LE:
410         case AV_PIX_FMT_YUV422P14BE:
411         case AV_PIX_FMT_YUV422P14LE:
412         case AV_PIX_FMT_YUV444P12BE:
413         case AV_PIX_FMT_YUV444P12LE:
414         case AV_PIX_FMT_YUV444P14BE:
415         case AV_PIX_FMT_YUV444P14LE:
416         case AV_PIX_FMT_YUVJ411P:
417                 return true;
418         default:
419                 return false;
420         }
421 }
422
423 bool
424 FFmpegExaminer::has_video () const
425 {
426         return static_cast<bool> (_video_stream);
427 }
428
429 VideoRange
430 FFmpegExaminer::range () const
431 {
432         switch (color_range()) {
433         case AVCOL_RANGE_MPEG:
434         case AVCOL_RANGE_UNSPECIFIED:
435                 return VIDEO_RANGE_VIDEO;
436         case AVCOL_RANGE_JPEG:
437         default:
438                 return VIDEO_RANGE_FULL;
439         }
440 }