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