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