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