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