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