MythTV  master
avformatdecoder.cpp
Go to the documentation of this file.
1 // C++ headers
2 #include <algorithm>
3 #include <cassert>
4 #include <cmath>
5 #include <cstdint>
6 #include <iostream>
7 #include <unistd.h>
8 
9 #include <QFileInfo>
10 #if QT_VERSION < QT_VERSION_CHECK(6,0,0)
11 #include <QTextCodec>
12 #else
13 #include <QStringDecoder>
14 #endif
15 
16 #ifdef USING_MEDIACODEC
17 extern "C" {
18 #include "libavcodec/jni.h"
19 }
20 #include <QtAndroidExtras>
21 #endif
22 
23 extern "C" {
24 #include "libavutil/avutil.h"
25 #include "libavutil/error.h"
26 #include "libavutil/log.h"
27 #include "libavcodec/avcodec.h"
28 #include "libavformat/avformat.h"
29 #include "libavformat/avio.h"
30 #include "libavformat/internal.h"
31 #include "libswscale/swscale.h"
32 #include "libavformat/isom.h"
33 #include "ivtv_myth.h"
34 #include "libavutil/imgutils.h"
35 #include "libavutil/display.h"
36 }
37 
38 #ifdef _WIN32
39  #undef mkdir
40 #endif
41 
42 // MythTV headers
43 #include "mythtvexp.h"
44 #include "mythconfig.h"
45 #include "avformatdecoder.h"
46 #include "audiooutput.h"
47 #include "audiooutpututil.h"
48 #include "io/mythmediabuffer.h"
49 #include "mythplayer.h"
50 #include "remoteencoder.h"
51 #include "programinfo.h"
52 #include "mythcorecontext.h"
53 #include "mythdbcon.h"
54 #include "iso639.h"
55 #include "mpegtables.h"
56 #include "atscdescriptors.h"
57 #include "dvbdescriptors.h"
58 #include "captions/cc608decoder.h"
59 #include "captions/cc708decoder.h"
62 #include "interactivetv.h"
63 #include "mythvideoprofile.h"
64 #include "mythuihelper.h"
65 #include "DVD/mythdvdbuffer.h"
66 #include "Bluray/mythbdbuffer.h"
67 #include "mythavutil.h"
68 #include "mythhdrvideometadata.h"
69 
70 #include "lcddevice.h"
71 
72 #include "audiooutput.h"
73 
74 #ifdef _MSC_VER
75 // MSVC isn't C99 compliant...
76 # ifdef AV_TIME_BASE_Q
77 # undef AV_TIME_BASE_Q
78 # endif
79 #define AV_TIME_BASE_Q GetAVTimeBaseQ()
80 
81 __inline AVRational GetAVTimeBaseQ()
82 {
83  AVRational av = {1, AV_TIME_BASE};
84  return av;
85 }
86 #endif
87 
88 #define LOC QString("AFD: ")
89 
90 // Maximum number of sequential invalid data packet errors before we try
91 // switching to software decoder. Packet errors are often seen when using
92 // hardware contexts and, for example, seeking. Hence this needs to be high and
93 // is probably best removed as it is treating the symptoms and not the cause.
94 // See also comment in MythCodecMap::freeCodecContext re trying to free an
95 // active hardware context when it is errored.
96 #define SEQ_PKT_ERR_MAX 50
97 
98 static const int max_video_queue_size = 220;
99 
100 static int cc608_parity(uint8_t byte);
101 static int cc608_good_parity(const CC608Parity &parity_table, uint16_t data);
102 static void cc608_build_parity_table(CC608Parity &parity_table);
103 
104 static bool silence_ffmpeg_logging = false;
105 
106 static QSize get_video_dim(const AVCodecContext &ctx)
107 {
108  return {ctx.width >> ctx.lowres, ctx.height >> ctx.lowres};
109 }
110 static float get_aspect(const AVCodecContext &ctx)
111 {
112  float aspect_ratio = 0.0F;
113 
114  if (ctx.sample_aspect_ratio.num && ctx.height)
115  {
116  aspect_ratio = av_q2d(ctx.sample_aspect_ratio) *
117  static_cast<double>(ctx.width);
118  aspect_ratio /= (float) ctx.height;
119  }
120 
121  if (aspect_ratio <= 0.0F || aspect_ratio > 6.0F)
122  {
123  if (ctx.height)
124  aspect_ratio = (float)ctx.width / (float)ctx.height;
125  else
126  aspect_ratio = 4.0F / 3.0F;
127  }
128 
129  return aspect_ratio;
130 }
131 static float get_aspect(AVCParser &p)
132 {
133  static constexpr float kDefaultAspect = 4.0F / 3.0F;
134  int asp = p.aspectRatio();
135  switch (asp)
136  {
137  case 0: return kDefaultAspect;
138  case 2: return 4.0F / 3.0F;
139  case 3: return 16.0F / 9.0F;
140  case 4: return 2.21F;
141  default: break;
142  }
143 
144  float aspect_ratio = asp * 0.000001F;
145  if (aspect_ratio <= 0.0F || aspect_ratio > 6.0F)
146  {
147  if (p.pictureHeight() && p.pictureWidth())
148  {
149  aspect_ratio =
150  (float) p.pictureWidth() /(float) p.pictureHeight();
151  }
152  else
153  {
154  aspect_ratio = kDefaultAspect;
155  }
156  }
157  return aspect_ratio;
158 }
159 
160 
161 int get_avf_buffer(struct AVCodecContext *c, AVFrame *pic, int flags);
162 #ifdef USING_DXVA2
163 int get_avf_buffer_dxva2(struct AVCodecContext *c, AVFrame *pic, int flags);
164 #endif
165 
166 // currently unused
167 //static int determinable_frame_size(struct AVCodecContext *avctx)
168 //{
169 // if (/*avctx->codec_id == AV_CODEC_ID_AAC ||*/
170 // avctx->codec_id == AV_CODEC_ID_MP1 ||
171 // avctx->codec_id == AV_CODEC_ID_MP2 ||
172 // avctx->codec_id == AV_CODEC_ID_MP3/* ||
173 // avctx->codec_id == AV_CODEC_ID_CELT*/)
174 // return 1;
175 // return 0;
176 //}
177 
178 #define FAIL(errmsg) do { \
179  LOG(VB_PLAYBACK, LOG_INFO, LOC + (errmsg)); \
180  return false; \
181 } while (false)
182 
183 static bool StreamHasRequiredParameters(AVCodecContext *Context, AVStream *Stream)
184 {
185  switch (Stream->codecpar->codec_type)
186  {
187  // We fail on video first as this is generally the most serious error
188  // and if we have video, we usually have everything else
189  case AVMEDIA_TYPE_VIDEO:
190  if (!Context)
191  FAIL("No codec for video stream");
192  if (!Stream->codecpar->width || !Stream->codecpar->height)
193  FAIL("Unspecified video size");
194  if (Stream->codecpar->format == AV_PIX_FMT_NONE)
195  FAIL("Unspecified video pixel format");
196  if (Context->codec_id == AV_CODEC_ID_RV30 || Context->codec_id == AV_CODEC_ID_RV40)
197  if (!Stream->sample_aspect_ratio.num && !Context->sample_aspect_ratio.num && !Stream->codec_info_nb_frames)
198  FAIL("No frame in rv30/40 and no sar");
199  break;
200  case AVMEDIA_TYPE_AUDIO:
201  if (!Context)
202  FAIL("No codec for audio stream");
203 
204  // These checks are currently disabled as they continually fail but
205  // codec initialisation is fine - which just delays live tv startup.
206  // The worst offender appears to be audio description channel...
207 
208  //if (!Stream->codecpar->frame_size && determinable_frame_size(avctx))
209  // FAIL("Unspecified audio frame size");
210  //if (Stream->codecpar->format == AV_SAMPLE_FMT_NONE)
211  // FAIL("Unspecified audio sample format");
212  //if (!Stream->codecpar->sample_rate)
213  // FAIL("Unspecified audio sample rate");
214  //if (!Stream->codecpar->channels)
215  // FAIL("Unspecified number of audio channels");
216  if (!Stream->nb_decoded_frames && Context->codec_id == AV_CODEC_ID_DTS)
217  FAIL("No decodable DTS frames");
218  break;
219 
220  case AVMEDIA_TYPE_SUBTITLE:
221  if (Stream->codecpar->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !Stream->codecpar->width)
222  FAIL("Unspecified subtitle size");
223  break;
224  case AVMEDIA_TYPE_DATA:
225  if (Stream->codecpar->codec_id == AV_CODEC_ID_NONE)
226  return true;
227  break;
228  default:
229  break;
230  }
231 
232  if (Stream->codecpar->codec_id == AV_CODEC_ID_NONE)
233  FAIL("Unknown codec");
234  return true;
235 }
236 
237 static void myth_av_log(void *ptr, int level, const char* fmt, va_list vl)
238 {
240  return;
241 
242  if (VERBOSE_LEVEL_NONE)
243  return;
244 
245  static QString s_fullLine("");
246  static QMutex s_stringLock;
247  uint64_t verbose_mask = VB_LIBAV;
248  LogLevel_t verbose_level = LOG_EMERG;
249 
250  // determine mythtv debug level from av log level
251  switch (level)
252  {
253  case AV_LOG_PANIC:
254  verbose_level = LOG_EMERG;
255  verbose_mask |= VB_GENERAL;
256  break;
257  case AV_LOG_FATAL:
258  verbose_level = LOG_CRIT;
259  verbose_mask |= VB_GENERAL;
260  break;
261  case AV_LOG_ERROR:
262  verbose_level = LOG_ERR;
263  break;
264  case AV_LOG_WARNING:
265  verbose_level = LOG_WARNING;
266  break;
267  case AV_LOG_INFO:
268  verbose_level = LOG_INFO;
269  break;
270  case AV_LOG_VERBOSE:
271  case AV_LOG_DEBUG:
272  case AV_LOG_TRACE:
273  verbose_level = LOG_DEBUG;
274  break;
275  default:
276  return;
277  }
278 
279  if (!VERBOSE_LEVEL_CHECK(verbose_mask, verbose_level))
280  return;
281 
282  s_stringLock.lock();
283  if (s_fullLine.isEmpty() && ptr) {
284  AVClass* avc = *(AVClass**)ptr;
285  s_fullLine = QString("[%1 @ %2] ")
286  .arg(avc->item_name(ptr))
287  .arg((quintptr)avc, QT_POINTER_SIZE * 2, 16, QChar('0'));
288  }
289 
290  s_fullLine += QString::vasprintf(fmt, vl);
291  if (s_fullLine.endsWith("\n"))
292  {
293  LOG(verbose_mask, verbose_level, s_fullLine.trimmed());
294  s_fullLine.truncate(0);
295  }
296  s_stringLock.unlock();
297 }
298 
299 static int get_canonical_lang(const char *lang_cstr)
300 {
301  if (lang_cstr[0] == '\0' || lang_cstr[1] == '\0')
302  {
303  return iso639_str3_to_key("und");
304  }
305  if (lang_cstr[2] == '\0')
306  {
307  QString tmp2 = lang_cstr;
308  QString tmp3 = iso639_str2_to_str3(tmp2);
309  int lang = iso639_str3_to_key(tmp3);
310  return iso639_key_to_canonical_key(lang);
311  }
312  int lang = iso639_str3_to_key(lang_cstr);
313  return iso639_key_to_canonical_key(lang);
314 }
315 
317  const ProgramInfo &pginfo,
318  PlayerFlags flags)
319  : DecoderBase(parent, pginfo),
320  m_isDbIgnored(gCoreContext->IsDatabaseIgnored()),
321  m_avcParser(new AVCParser()),
322  m_playerFlags(flags),
323  // Closed Caption & Teletext decoders
324  m_ccd608(new CC608Decoder(parent->GetCC608Reader())),
325  m_ccd708(new CC708Decoder(parent->GetCC708Reader())),
326  m_ttd(new TeletextDecoder(parent->GetTeletextReader()))
327 {
328  // this will be deleted and recreated once decoder is set up
330 
331  m_audioSamples = (uint8_t *)av_mallocz(AudioOutput::kMaxSizeBuffer);
333 
334  av_log_set_callback(myth_av_log);
335 
336  m_audioIn.m_sampleSize = -32;// force SetupAudioStream to run once
338 
340 
342  m_audioReadAhead = gCoreContext->GetDurSetting<std::chrono::milliseconds>("AudioReadAhead", 100ms);
343 
344  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("PlayerFlags: 0x%1, AudioReadAhead: %2 msec")
345  .arg(m_playerFlags, 0, 16).arg(m_audioReadAhead.count()));
346 }
347 
349 {
350  while (!m_storedPackets.isEmpty())
351  {
352  AVPacket *pkt = m_storedPackets.takeFirst();
353  av_packet_unref(pkt);
354  delete pkt;
355  }
356 
357  CloseContext();
358  delete m_ccd608;
359  delete m_ccd708;
360  delete m_ttd;
361  delete m_avcParser;
362  delete m_mythCodecCtx;
363 
364  sws_freeContext(m_swsCtx);
365 
366  av_freep(&m_audioSamples);
367 
368  delete m_avfRingBuffer;
369 
370  if (LCD *lcd = LCD::Get())
371  {
372  lcd->setAudioFormatLEDs(AUDIO_AC3, false);
373  lcd->setVideoFormatLEDs(VIDEO_MPG, false);
374  lcd->setVariousLEDs(VARIOUS_HDTV, false);
375  lcd->setVariousLEDs(VARIOUS_SPDIF, false);
376  lcd->setSpeakerLEDs(SPEAKER_71, false); // should clear any and all speaker LEDs
377  }
378 }
379 
381 {
382  return &m_codecMap;
383 }
384 
386 {
387  if (m_ic)
388  {
389  m_avCodecLock.lock();
390  for (uint i = 0; i < m_ic->nb_streams; i++)
391  {
392  AVStream *st = m_ic->streams[i];
394  }
395  m_avCodecLock.unlock();
396  }
397 }
398 
400 {
401  if (m_ic)
402  {
403  CloseCodecs();
404 
405  AVInputFormat *fmt = m_ic->iformat;
406  m_ic->iformat->flags |= AVFMT_NOFILE;
407 
408  av_free(m_ic->pb->buffer);
409  av_free(m_ic->pb);
410  avformat_close_input(&m_ic);
411  m_ic = nullptr;
412  fmt->flags &= ~AVFMT_NOFILE;
413  }
414  m_avcParser->Reset();
415 }
416 
417 static int64_t lsb3full(int64_t lsb, int64_t base_ts, int lsb_bits)
418 {
419  int64_t mask = (lsb_bits < 64) ? (1LL<<lsb_bits)-1 : -1LL;
420  return ((lsb - base_ts)&mask);
421 }
422 
423 std::chrono::milliseconds AvFormatDecoder::NormalizeVideoTimecode(std::chrono::milliseconds timecode)
424 {
425  int64_t start_pts = 0;
426 
427  AVStream *st = nullptr;
428  for (uint i = 0; i < m_ic->nb_streams; i++)
429  {
430  AVStream *st1 = m_ic->streams[i];
431  if (st1 && st1->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
432  {
433  st = st1;
434  break;
435  }
436  }
437  if (!st)
438  return 0ms;
439 
440  if (m_ic->start_time != AV_NOPTS_VALUE)
441  {
442  start_pts = av_rescale(m_ic->start_time,
443  st->time_base.den,
444  AV_TIME_BASE * (int64_t)st->time_base.num);
445  }
446 
447  int64_t pts = av_rescale(timecode.count() / 1000.0,
448  st->time_base.den,
449  st->time_base.num);
450 
451  // adjust for start time and wrap
452  pts = lsb3full(pts, start_pts, st->pts_wrap_bits);
453 
454  return millisecondsFromFloat(av_q2d(st->time_base) * pts * 1000);
455 }
456 
457 std::chrono::milliseconds AvFormatDecoder::NormalizeVideoTimecode(AVStream *st,
458  std::chrono::milliseconds timecode)
459 {
460  int64_t start_pts = 0;
461 
462  if (m_ic->start_time != AV_NOPTS_VALUE)
463  {
464  start_pts = av_rescale(m_ic->start_time,
465  st->time_base.den,
466  AV_TIME_BASE * (int64_t)st->time_base.num);
467  }
468 
469  int64_t pts = av_rescale(timecode.count() / 1000.0,
470  st->time_base.den,
471  st->time_base.num);
472 
473  // adjust for start time and wrap
474  pts = lsb3full(pts, start_pts, st->pts_wrap_bits);
475 
476  return millisecondsFromFloat(av_q2d(st->time_base) * pts * 1000);
477 }
478 
480 {
481  if (m_ic && m_ic->nb_chapters > 1)
482  return m_ic->nb_chapters;
483  return 0;
484 }
485 
486 void AvFormatDecoder::GetChapterTimes(QList<std::chrono::seconds> &times)
487 {
488  int total = GetNumChapters();
489  if (!total)
490  return;
491 
492  for (int i = 0; i < total; i++)
493  {
494  int num = m_ic->chapters[i]->time_base.num;
495  int den = m_ic->chapters[i]->time_base.den;
496  int64_t start = m_ic->chapters[i]->start;
497  long double total_secs = (long double)start * (long double)num /
498  (long double)den;
499  times.push_back(std::chrono::seconds((long long)total_secs));
500  }
501 }
502 
503 int AvFormatDecoder::GetCurrentChapter(long long framesPlayed)
504 {
505  if (!GetNumChapters())
506  return 0;
507 
508  for (int i = (m_ic->nb_chapters - 1); i > -1 ; i--)
509  {
510  int num = m_ic->chapters[i]->time_base.num;
511  int den = m_ic->chapters[i]->time_base.den;
512  int64_t start = m_ic->chapters[i]->start;
513  long double total_secs = (long double)start * (long double)num /
514  (long double)den;
515  auto framenum = (long long)(total_secs * m_fps);
516  if (framesPlayed >= framenum)
517  {
518  LOG(VB_PLAYBACK, LOG_INFO, LOC +
519  QString("GetCurrentChapter(selected chapter %1 framenum %2)")
520  .arg(i + 1).arg(framenum));
521  return i + 1;
522  }
523  }
524  return 0;
525 }
526 
527 long long AvFormatDecoder::GetChapter(int chapter)
528 {
529  if (chapter < 1 || chapter > GetNumChapters())
530  return -1;
531 
532  int num = m_ic->chapters[chapter - 1]->time_base.num;
533  int den = m_ic->chapters[chapter - 1]->time_base.den;
534  int64_t start = m_ic->chapters[chapter - 1]->start;
535  long double total_secs = (long double)start * (long double)num /
536  (long double)den;
537  auto framenum = (long long)(total_secs * m_fps);
538  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("GetChapter %1: framenum %2")
539  .arg(chapter).arg(framenum));
540  return framenum;
541 }
542 
543 bool AvFormatDecoder::DoRewind(long long desiredFrame, bool discardFrames)
544 {
545  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("DoRewind(%1, %2 discard frames)")
546  .arg(desiredFrame).arg( discardFrames ? "do" : "don't" ));
547 
549  return DecoderBase::DoRewind(desiredFrame, discardFrames);
550 
551  m_doRewind = true;
552 
553  // avformat-based seeking
554  return DoFastForward(desiredFrame, discardFrames);
555 }
556 
557 bool AvFormatDecoder::DoFastForward(long long desiredFrame, bool discardFrames)
558 {
559  LOG(VB_PLAYBACK, LOG_INFO, LOC +
560  QString("DoFastForward(%1 (%2), %3 discard frames)")
561  .arg(desiredFrame).arg(m_framesPlayed)
562  .arg((discardFrames) ? "do" : "don't"));
563 
565  return DecoderBase::DoFastForward(desiredFrame, discardFrames);
566 
567  bool oldrawstate = m_getRawFrames;
568  m_getRawFrames = false;
569 
570  AVStream *st = nullptr;
571  for (uint i = 0; i < m_ic->nb_streams; i++)
572  {
573  AVStream *st1 = m_ic->streams[i];
574  if (st1 && st1->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
575  {
576  st = st1;
577  break;
578  }
579  }
580 
581  int seekDelta = desiredFrame - m_framesPlayed;
582 
583  // avoid using av_frame_seek if we are seeking frame-by-frame when paused
584  if (seekDelta >= 0 && seekDelta < 2 && !m_doRewind && m_parent->GetPlaySpeed() == 0.0F)
585  {
586  SeekReset(m_framesPlayed, seekDelta, false, true);
588  m_getRawFrames = oldrawstate;
589  return true;
590  }
591 
592  long long ts = 0;
593  if (m_ic->start_time != AV_NOPTS_VALUE)
594  ts = m_ic->start_time;
595 
596  // convert framenumber to normalized timestamp
597  long double seekts = desiredFrame * AV_TIME_BASE / m_fps;
598  ts += (long long)seekts;
599 
600  // XXX figure out how to do snapping in this case
601  bool exactseeks = DecoderBase::GetSeekSnap() == 0U;
602 
603  int flags = (m_doRewind || exactseeks) ? AVSEEK_FLAG_BACKWARD : 0;
604 
605  if (av_seek_frame(m_ic, -1, ts, flags) < 0)
606  {
607  LOG(VB_GENERAL, LOG_ERR, LOC +
608  QString("av_seek_frame(ic, -1, %1, 0) -- error").arg(ts));
609  m_getRawFrames = oldrawstate;
610  return false;
611  }
612 
613  int normalframes = 0;
614 
615  if (st && st->cur_dts != AV_NOPTS_VALUE)
616  {
617 
618  int64_t adj_cur_dts = st->cur_dts;
619 
620  if (m_ic->start_time != AV_NOPTS_VALUE)
621  {
622  int64_t st1 = av_rescale(m_ic->start_time,
623  st->time_base.den,
624  AV_TIME_BASE * (int64_t)st->time_base.num);
625  adj_cur_dts = lsb3full(adj_cur_dts, st1, st->pts_wrap_bits);
626  }
627 
628  int64_t adj_seek_dts = av_rescale(seekts,
629  st->time_base.den,
630  AV_TIME_BASE * (int64_t)st->time_base.num);
631 
632  int64_t max_dts = (st->pts_wrap_bits < 64) ? (1LL<<st->pts_wrap_bits)-1 : -1LL;
633 
634  // When seeking near the start of a stream the current dts is sometimes
635  // less than the start time which causes lsb3full to return adj_cur_dts
636  // close to the maximum dts value. If so, set adj_cur_dts to zero.
637  if (adj_seek_dts < max_dts / 64 && adj_cur_dts > max_dts / 2)
638  adj_cur_dts = 0;
639 
640  long long newts = av_rescale(adj_cur_dts,
641  (int64_t)AV_TIME_BASE *
642  (int64_t)st->time_base.num,
643  st->time_base.den);
644 
645  m_lastKey = (long long)((newts*(long double)m_fps)/AV_TIME_BASE);
647  m_fpsSkip = 0;
649 
650  normalframes = (exactseeks) ? desiredFrame - m_framesPlayed : 0;
651  normalframes = std::max(normalframes, 0);
652  m_noDtsHack = false;
653  }
654  else
655  {
656  LOG(VB_GENERAL, LOG_INFO, LOC + "No DTS Seeking Hack!");
657  m_noDtsHack = true;
658  m_framesPlayed = desiredFrame;
659  m_fpsSkip = 0;
660  m_framesRead = desiredFrame;
661  normalframes = 0;
662  }
663 
664  SeekReset(m_lastKey, normalframes, true, discardFrames);
665 
666  if (discardFrames)
668 
669  m_doRewind = false;
670 
671  m_getRawFrames = oldrawstate;
672 
673  return true;
674 }
675 
676 void AvFormatDecoder::SeekReset(long long newKey, uint skipFrames,
677  bool doflush, bool discardFrames)
678 {
679  if (!m_ringBuffer)
680  return; // nothing to reset...
681 
682  LOG(VB_PLAYBACK, LOG_INFO, LOC +
683  QString("SeekReset(%1, %2, %3 flush, %4 discard)")
684  .arg(newKey).arg(skipFrames)
685  .arg((doflush) ? "do" : "don't",
686  (discardFrames) ? "do" : "don't"));
687 
688  DecoderBase::SeekReset(newKey, skipFrames, doflush, discardFrames);
689 
690  QMutexLocker locker(&m_avCodecLock);
691 
692  // Discard all the queued up decoded frames
693  if (discardFrames)
694  {
695  bool releaseall = m_mythCodecCtx ? (m_mythCodecCtx->DecoderWillResetOnFlush() ||
696  m_mythCodecCtx->DecoderNeedsReset(nullptr)) : false;
697  m_parent->DiscardVideoFrames(doflush, doflush && releaseall);
698  }
699 
700  if (doflush)
701  {
702  m_lastAPts = 0ms;
703  m_lastVPts = 0ms;
704  m_lastCcPtsu = 0us;
705  m_faultyPts = m_faultyDts = 0;
708  m_ptsDetected = false;
709  m_reorderedPtsDetected = false;
710 
711  ff_read_frame_flush(m_ic);
712 
713  // Only reset the internal state if we're using our seeking,
714  // not when using libavformat's seeking
716  {
717  m_ic->pb->pos = m_ringBuffer->GetReadPosition();
718  m_ic->pb->buf_ptr = m_ic->pb->buffer;
719  m_ic->pb->buf_end = m_ic->pb->buffer;
720  m_ic->pb->eof_reached = 0;
721  }
722 
723  // Flush the avcodec buffers
724  LOG(VB_PLAYBACK, LOG_INFO, LOC + "SeekReset() flushing");
725  for (uint i = 0; i < m_ic->nb_streams; i++)
726  {
727  AVCodecContext *enc = m_codecMap.FindCodecContext(m_ic->streams[i]);
728  // note that contexts that have not been opened have
729  // enc->internal = nullptr and cause a segfault in
730  // avcodec_flush_buffers
731  if (enc && enc->internal)
732  avcodec_flush_buffers(enc);
733  }
734 
735  // Free up the stored up packets
736  while (!m_storedPackets.isEmpty())
737  {
738  AVPacket *pkt = m_storedPackets.takeFirst();
739  av_packet_unref(pkt);
740  delete pkt;
741  }
742 
743  m_prevGopPos = 0;
744  m_gopSet = false;
745  if (!m_ringBuffer->IsDVD())
746  {
747  if (!m_noDtsHack)
748  {
750  m_fpsSkip = 0;
752  }
753 
754  m_noDtsHack = false;
755  }
756  }
757 
758  // Skip all the desired number of skipFrames
759 
760  // Some seeks can be very slow. The most common example comes
761  // from HD-PVR recordings, where keyframes are 128 frames apart
762  // and decoding (even hardware decoding) may not be much faster
763  // than realtime, causing some exact seeks to take 2-4 seconds.
764  // If exact seeking is not required, we take some shortcuts.
765  // First, we impose an absolute maximum time we are willing to
766  // spend (maxSeekTimeMs) on the forward frame-by-frame skip.
767  // After that much time has elapsed, we give up and stop the
768  // frame-by-frame seeking. Second, after skipping a few frames,
769  // we predict whether the situation is hopeless, i.e. the total
770  // skipping would take longer than giveUpPredictionMs, and if so,
771  // stop skipping right away.
772  bool exactSeeks = GetSeekSnap() == 0U;
773  static constexpr std::chrono::milliseconds maxSeekTimeMs { 200ms };
774  int profileFrames = 0;
776  for (; (skipFrames > 0 && !m_atEof &&
777  (exactSeeks || begin.elapsed() < maxSeekTimeMs));
778  --skipFrames, ++profileFrames)
779  {
780  // TODO this won't work well in conjunction with the MythTimer
781  // above...
782  QElapsedTimer getframetimer;
783  getframetimer.start();
784  bool retry = true;
785  while (retry && !getframetimer.hasExpired(100))
786  {
787  retry = false;
788  GetFrame(kDecodeVideo, retry);
789  if (retry)
790  std::this_thread::sleep_for(1ms);
791  }
792 
794  {
796  m_decodedVideoFrame = nullptr;
797  }
798  if (!exactSeeks && profileFrames >= 5 && profileFrames < 10)
799  {
800  const int giveUpPredictionMs = 400;
801  int remainingTimeMs =
802  skipFrames * (float)begin.elapsed().count() / profileFrames;
803  if (remainingTimeMs > giveUpPredictionMs)
804  {
805  LOG(VB_PLAYBACK, LOG_DEBUG,
806  QString("Frame-by-frame seeking would take "
807  "%1 ms to finish, skipping.").arg(remainingTimeMs));
808  break;
809  }
810  }
811  }
812 
813  if (doflush)
814  {
815  m_firstVPts = 0ms;
816  m_firstVPtsInuse = true;
817  }
818 }
819 
821 {
822  if (!eof && m_ic && m_ic->pb)
823  {
824  LOG(VB_GENERAL, LOG_NOTICE, LOC +
825  QString("Resetting byte context eof (livetv %1 was eof %2)")
826  .arg(m_livetv).arg(m_ic->pb->eof_reached));
827  m_ic->pb->eof_reached = 0;
828  }
829  DecoderBase::SetEof(eof);
830 }
831 
832 void AvFormatDecoder::Reset(bool reset_video_data, bool seek_reset,
833  bool reset_file)
834 {
835  LOG(VB_PLAYBACK, LOG_INFO, LOC +
836  QString("Reset: Video %1, Seek %2, File %3")
837  .arg(reset_video_data).arg(seek_reset).arg(reset_file));
838 
839  if (seek_reset)
840  SeekReset(0, 0, true, false);
841 
842  DecoderBase::Reset(reset_video_data, false, reset_file);
843 
844  if (reset_video_data)
845  {
846  m_seenGop = false;
847  m_seqCount = 0;
848  }
849 }
850 
851 bool AvFormatDecoder::CanHandle(TestBufferVec & testbuf, const QString &filename)
852 {
853  AVProbeData probe;
854  memset(&probe, 0, sizeof(AVProbeData));
855 
856  QByteArray fname = filename.toLatin1();
857  probe.filename = fname.constData();
858  probe.buf = (unsigned char *)testbuf.data();
859  probe.buf_size = testbuf.size();
860 
861  int score = AVPROBE_SCORE_MAX/4;
862 
863  if (testbuf.size() + AVPROBE_PADDING_SIZE > kDecoderProbeBufferSize)
864  {
865  probe.buf_size = kDecoderProbeBufferSize - AVPROBE_PADDING_SIZE;
866  score = 0;
867  }
868  else if (testbuf.size()*2 >= kDecoderProbeBufferSize)
869  {
870  score--;
871  }
872 
873  memset(probe.buf + probe.buf_size, 0, AVPROBE_PADDING_SIZE);
874 
875  return av_probe_input_format2(&probe, static_cast<int>(true), &score) != nullptr;
876 }
877 
879 {
880  int buf_size = m_ringBuffer->BestBufferSize();
881  bool streamed = m_ringBuffer->IsStreamed();
883  m_readContext.flags = AVIO_FLAG_READ;
884  m_readContext.is_streamed = static_cast<int>(streamed);
885  m_readContext.max_packet_size = 0;
886  m_readContext.priv_data = m_avfRingBuffer;
887  auto *buffer = (unsigned char *)av_malloc(buf_size);
888  m_ic->pb = avio_alloc_context(buffer, buf_size, 0,
889  &m_readContext,
893 
894  // We can always seek during LiveTV
895  m_ic->pb->seekable = static_cast<int>(!streamed || forceseek);
896  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Buffer size: %1 Streamed %2 Seekable %3 Available %4")
897  .arg(buf_size).arg(streamed).arg(m_ic->pb->seekable).arg(m_ringBuffer->GetReadBufAvail()));
898 }
899 
900 extern "C" void HandleStreamChange(void *data)
901 {
902  auto *decoder = reinterpret_cast<AvFormatDecoder*>(data);
903 
904  int cnt = decoder->m_ic->nb_streams;
905 
906  LOG(VB_PLAYBACK, LOG_INFO, LOC +
907  QString("streams_changed 0x%1 -- stream count %2")
908  .arg((uint64_t)data,0,16).arg(cnt));
909 
910  decoder->m_streamsChanged = true;
911 }
912 
914 {
915  m_avCodecLock.lock();
916  int retval = avformat_find_stream_info(m_ic, nullptr);
917  m_avCodecLock.unlock();
918  silence_ffmpeg_logging = false;
919  // ffmpeg 3.0 is returning -1 code when there is a channel
920  // change or some encoding error just after the start
921  // of the file, but is has found the correct stream info
922  // Set rc to 0 so that playing can continue.
923  if (retval == -1)
924  retval = 0;
925  return retval;
926 }
927 
943  TestBufferVec & testbuf)
944 {
945  CloseContext();
946 
948 
949  // Process frames immediately unless we're decoding
950  // a DVD, in which case don't so that we don't show
951  // anything whilst probing the data streams.
953 
954  delete m_avfRingBuffer;
956 
957  AVInputFormat *fmt = nullptr;
958  QString fnames = m_ringBuffer->GetFilename();
959  QByteArray fnamea = fnames.toLatin1();
960  const char *filename = fnamea.constData();
961 
962  AVProbeData probe;
963  memset(&probe, 0, sizeof(AVProbeData));
964  probe.filename = filename;
965  probe.buf = reinterpret_cast<unsigned char *>(testbuf.data());
966  if (testbuf.size() + AVPROBE_PADDING_SIZE <= kDecoderProbeBufferSize)
967  probe.buf_size = testbuf.size();
968  else
969  probe.buf_size = kDecoderProbeBufferSize - AVPROBE_PADDING_SIZE;
970  memset(probe.buf + probe.buf_size, 0, AVPROBE_PADDING_SIZE);
971 
972  fmt = av_probe_input_format(&probe, static_cast<int>(true));
973  if (!fmt)
974  {
975  LOG(VB_GENERAL, LOG_ERR, LOC + QString("Probe failed for '%1'").arg(filename));
976  return -1;
977  }
978 
979  if (strcmp(fmt->name, "mpegts") == 0 &&
980  gCoreContext->GetBoolSetting("FFMPEGTS", false))
981  {
982  AVInputFormat *fmt2 = av_find_input_format("mpegts-ffmpeg");
983  if (fmt2)
984  {
985  fmt = fmt2;
986  LOG(VB_GENERAL, LOG_INFO, LOC + "Using FFmpeg MPEG-TS demuxer (forced)");
987  }
988  }
989 
990  int err = 0;
991  bool scancomplete = false;
992  int remainingscans = 5;
993 
994  while (!scancomplete && remainingscans--)
995  {
996  bool found = false;
997 
998  // With live tv, the ringbufer may contain insufficient data for complete
999  // initialisation so we try a few times with a slight pause each time to
1000  // allow extra data to become available. In the worst case scenarios, the
1001  // stream may not have a keyframe for 4-5 seconds.
1002  // As a last resort, we will try and fallback to the original FFmpeg MPEG-TS
1003  // demuxer if it is not already used.
1004  // For regular videos, this shouldn't be an issue as the complete file
1005  // should be available - though we try a little harder for streamed formats
1006  int retries = m_livetv || m_ringBuffer->IsStreamed() ? 50 : 10;
1007 
1008  while (!found && --retries)
1009  {
1010  m_ic = avformat_alloc_context();
1011  if (!m_ic)
1012  {
1013  LOG(VB_GENERAL, LOG_ERR, LOC + "Could not allocate format context.");
1014  return -1;
1015  }
1016 
1017  m_avfRingBuffer->SetInInit(false);
1019 
1020  err = avformat_open_input(&m_ic, filename, fmt, nullptr);
1021  if (err < 0)
1022  {
1023  std::string error;
1024  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Failed to open input ('%1')")
1025  .arg(av_make_error_stdstring(error, err)));
1026 
1027  // note - m_ic (AVFormatContext) is freed on failure
1028  if (retries > 1)
1029  {
1030  // wait a little to buffer more data
1031  // 50*0.1 = 5 seconds max
1032  QThread::usleep(100000);
1033  // resets the read position
1034  m_avfRingBuffer->SetInInit(false);
1035  continue;
1036  }
1037 
1038  if (strcmp(fmt->name, "mpegts") == 0)
1039  {
1040  fmt = av_find_input_format("mpegts-ffmpeg");
1041  if (fmt)
1042  {
1043  LOG(VB_GENERAL, LOG_ERR, LOC + "Attempting to use original FFmpeg MPEG-TS demuxer.");
1044  // resets the read position
1045  m_avfRingBuffer->SetInInit(false);
1046  continue;
1047  }
1048  break;
1049  }
1050  }
1051  found = true;
1052  }
1053 
1054  if (err < 0)
1055  {
1056  LOG(VB_GENERAL, LOG_ERR, LOC + "Fatal error opening input. Aborting");
1057  m_ic = nullptr;
1058  return -1;
1059  }
1060 
1061  // With certain streams, we don't get a complete stream analysis and the video
1062  // codec/frame format is not fully detected. This can have various consequences - from
1063  // failed playback to not enabling hardware decoding (as the frame formt is not valid).
1064  // Bump the duration (FFmpeg defaults to 5 seconds) to 60 seconds. This should
1065  // not impact performance as in the vast majority of cases the scan is completed
1066  // within a second or two (seconds in this case referring to stream duration - not the time
1067  // it takes to complete the scan).
1068  m_ic->max_analyze_duration = 60 * AV_TIME_BASE;
1069 
1071  err = FindStreamInfo();
1072  if (err < 0)
1073  {
1074  LOG(VB_GENERAL, LOG_ERR, LOC + QString("Could not find codec parameters for '%1'").arg(filename));
1075  CloseContext();
1076  return -1;
1077  }
1078  m_avfRingBuffer->SetInInit(false);
1079 
1080  // final sanity check that scanned streams are valid for live tv
1081  scancomplete = true;
1082  for (uint i = 0; m_livetv && (i < m_ic->nb_streams); i++)
1083  {
1084  if (!StreamHasRequiredParameters(m_codecMap.GetCodecContext(m_ic->streams[i]), m_ic->streams[i]))
1085  {
1086  scancomplete = false;
1087  if (remainingscans)
1088  {
1089  CloseContext();
1090  LOG(VB_PLAYBACK, LOG_INFO, LOC + "Stream scan incomplete - retrying");
1091  QThread::usleep(250000); // wait 250ms
1092  }
1093  break;
1094  }
1095  }
1096  }
1097 
1098  if (!scancomplete)
1099  LOG(VB_GENERAL, LOG_WARNING, LOC + "Scan incomplete - playback may not work");
1100 
1101  m_ic->streams_changed = HandleStreamChange;
1102  m_ic->stream_change_data = this;
1103 
1104  fmt->flags &= ~AVFMT_NOFILE;
1105 
1106  if (!m_livetv && !m_ringBuffer->IsDisc())
1107  {
1108  // generate timings based on the video stream to avoid bogus ffmpeg
1109  // values for duration and bitrate
1111  }
1112 
1113  // FLAC, MP3 or M4A file may contains an artwork image, a single frame MJPEG,
1114  // we need to ignore it as we don't handle single frames or images in place of video
1115  // TODO: display single frame
1116  QString extension = QFileInfo(fnames).suffix();
1117  if (strcmp(fmt->name, "mp3") == 0 || strcmp(fmt->name, "flac") == 0 ||
1118  strcmp(fmt->name, "ogg") == 0 ||
1119  (extension.compare("m4a", Qt::CaseInsensitive) == 0))
1120  {
1121  novideo = true;
1122  }
1123 
1124  // Scan for the initial A/V streams
1125  err = ScanStreams(novideo);
1126  if (-1 == err)
1127  {
1128  CloseContext();
1129  return err;
1130  }
1131 
1132  AutoSelectTracks(); // This is needed for transcoder
1133 
1134 #ifdef USING_MHEG
1135  {
1136  int initialAudio = -1;
1137  int initialVideo = -1;
1138  if (m_itv || (m_itv = m_parent->GetInteractiveTV()))
1139  m_itv->GetInitialStreams(initialAudio, initialVideo);
1140  if (initialAudio >= 0)
1141  SetAudioByComponentTag(initialAudio);
1142  if (initialVideo >= 0)
1143  SetVideoByComponentTag(initialVideo);
1144  }
1145 #endif // USING_MHEG
1146 
1147  // Try to get a position map from the recorder if we don't have one yet.
1149  {
1151  {
1154  {
1155  m_hasFullPositionMap = true;
1156  m_gopSet = true;
1157  }
1158  }
1159  }
1160 
1161  // If watching pre-recorded television or video use the marked duration
1162  // from the db if it exists, else ffmpeg duration
1163  std::chrono::seconds dur = 0s;
1164 
1165  if (m_playbackInfo)
1166  {
1167  dur = duration_cast<std::chrono::seconds>(m_playbackInfo->QueryTotalDuration());
1168  }
1169 
1170  if (dur == 0s)
1171  {
1172  if ((m_ic->duration == AV_NOPTS_VALUE) &&
1173  (!m_livetv && !m_ringBuffer->IsDisc()))
1174  av_estimate_timings(m_ic, 0);
1175 
1176  dur = duration_cast<std::chrono::seconds>(av_duration(m_ic->duration));
1177  }
1178 
1179  if (dur > 0s && !m_livetv && !m_watchingRecording)
1180  {
1181  m_parent->SetDuration(dur);
1182  }
1183 
1184  // If we don't have a position map, set up ffmpeg for seeking
1186  {
1187  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1188  "Recording has no position -- using libavformat seeking.");
1189 
1190  if (dur > 0s)
1191  {
1192  m_parent->SetFileLength(dur, (int)(dur.count() * m_fps));
1193  }
1194  else
1195  {
1196  // the pvr-250 seems to over report the bitrate by * 2
1197  float bytespersec = (float)m_bitrate / 8 / 2;
1198  float secs = m_ringBuffer->GetRealFileSize() * 1.0F / bytespersec;
1200  (int)(secs * static_cast<float>(m_fps)));
1201  }
1202 
1203  // we will not see a position map from db or remote encoder,
1204  // set the gop interval to 15 frames. if we guess wrong, the
1205  // auto detection will change it.
1206  m_keyframeDist = 15;
1208 
1209  if (strcmp(fmt->name, "avi") == 0)
1210  {
1211  // avi keyframes are too irregular
1212  m_keyframeDist = 1;
1213  }
1214 
1215  m_dontSyncPositionMap = true;
1216  m_ic->build_index = 1;
1217  }
1218  // we have a position map, disable libavformat's seek index
1219  else
1220  m_ic->build_index = 0;
1221 
1222  av_dump_format(m_ic, 0, filename, 0);
1223 
1224  // print some useful information if playback debugging is on
1226  LOG(VB_PLAYBACK, LOG_INFO, LOC + "Position map found");
1227  else if (m_recordingHasPositionMap)
1228  LOG(VB_PLAYBACK, LOG_INFO, LOC + "Partial position map found");
1229  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1230  QString("Successfully opened decoder for file: \"%1\". novideo(%2)")
1231  .arg(filename).arg(novideo));
1232 
1233  // Print AVChapter information
1234  for (unsigned int i=0; i < m_ic->nb_chapters; i++)
1235  {
1236  int num = m_ic->chapters[i]->time_base.num;
1237  int den = m_ic->chapters[i]->time_base.den;
1238  int64_t start = m_ic->chapters[i]->start;
1239  auto total_secs = static_cast<long double>(start) * static_cast<long double>(num) /
1240  static_cast<long double>(den);
1241  auto msec = millisecondsFromFloat(total_secs * 1000);
1242  auto framenum = static_cast<long long>(total_secs * static_cast<long double>(m_fps));
1243  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1244  QString("Chapter %1 found @ [%2]->%3")
1245  .arg(i + 1, 2,10,QChar('0'))
1246  .arg(MythFormatTime(msec, "HH:mm:ss.zzz"))
1247  .arg(framenum));
1248  }
1249 
1250  if (qEnvironmentVariableIsSet("FORCE_DTS_TIMESTAMPS"))
1251  m_forceDtsTimestamps = true;
1252 
1253  if (m_ringBuffer->IsDVD())
1254  {
1255  // Reset DVD playback and clear any of
1256  // our buffers so that none of the data
1257  // parsed so far to determine decoders
1258  // gets shown.
1260  return -1;
1262 
1263  Reset(true, true, true);
1264 
1265  // Now we're ready to process and show frames
1266  m_processFrames = true;
1267  }
1268 
1269 
1270  // Return true if recording has position map
1271  return static_cast<int>(m_recordingHasPositionMap);
1272 }
1273 
1274 float AvFormatDecoder::GetVideoFrameRate(AVStream *Stream, AVCodecContext *Context, bool Sanitise)
1275 {
1276  double avg_fps = 0.0;
1277  double codec_fps = 0.0;
1278  double container_fps = 0.0;
1279  double estimated_fps = 0.0;
1280 
1281  if (Stream->avg_frame_rate.den && Stream->avg_frame_rate.num)
1282  avg_fps = av_q2d(Stream->avg_frame_rate); // MKV default_duration
1283 
1284  if (Context->time_base.den && Context->time_base.num) // tbc
1285  codec_fps = 1.0 / av_q2d(Context->time_base) / Context->ticks_per_frame;
1286  // Some formats report fps waaay too high. (wrong time_base)
1287  if (codec_fps > 121.0 && (Context->time_base.den > 10000) &&
1288  (Context->time_base.num == 1))
1289  {
1290  Context->time_base.num = 1001; // seems pretty standard
1291  if (av_q2d(Context->time_base) > 0)
1292  codec_fps = 1.0 / av_q2d(Context->time_base);
1293  }
1294  if (Stream->time_base.den && Stream->time_base.num) // tbn
1295  container_fps = 1.0 / av_q2d(Stream->time_base);
1296  if (Stream->r_frame_rate.den && Stream->r_frame_rate.num) // tbr
1297  estimated_fps = av_q2d(Stream->r_frame_rate);
1298 
1299  // build a list of possible rates, best first
1300  vector<double> rates;
1301 
1302  // matroska demuxer sets the default_duration to avg_frame_rate
1303  // mov,mp4,m4a,3gp,3g2,mj2 demuxer sets avg_frame_rate
1304  if ((QString(m_ic->iformat->name).contains("matroska") ||
1305  QString(m_ic->iformat->name).contains("mov")) &&
1306  avg_fps < 121.0 && avg_fps > 3.0)
1307  {
1308  rates.emplace_back(avg_fps);
1309  }
1310 
1311  if (QString(m_ic->iformat->name).contains("avi") &&
1312  container_fps < 121.0 && container_fps > 3.0)
1313  {
1314  // avi uses container fps for timestamps
1315  rates.emplace_back(container_fps);
1316  }
1317 
1318  if (codec_fps < 121.0 && codec_fps > 3.0)
1319  rates.emplace_back(codec_fps);
1320 
1321  if (container_fps < 121.0 && container_fps > 3.0)
1322  rates.emplace_back(container_fps);
1323 
1324  if (avg_fps < 121.0 && avg_fps > 3.0)
1325  rates.emplace_back(avg_fps);
1326 
1327  // certain H.264 interlaced streams are detected at 2x using estimated (i.e. wrong)
1328  if (estimated_fps < 121.0 && estimated_fps > 3.0)
1329  rates.emplace_back(estimated_fps);
1330 
1331  // last resort
1332  rates.emplace_back(30000.0 / 1001.0);
1333 
1334  auto FuzzyEquals = [](double First, double Second) { return abs(First - Second) < 0.03; };
1335 
1336  // debug
1337  if (!FuzzyEquals(rates.front(), m_fps))
1338  {
1339  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1340  QString("Selected FPS: %1 (Avg:%2 Mult:%3 Codec:%4 Container:%5 Estimated:%6)")
1341  .arg(static_cast<double>(rates.front())).arg(avg_fps)
1342  .arg(m_fpsMultiplier).arg(codec_fps).arg(container_fps).arg(estimated_fps));
1343  }
1344 
1345  auto IsStandard = [&FuzzyEquals](double Rate)
1346  {
1347  // List of known, standards based frame rates
1348  static const vector<double> s_normRates =
1349  {
1350  24000.0 / 1001.0, 23.976, 24.0, 25.0, 30000.0 / 1001.0,
1351  29.97, 30.0, 50.0, 60000.0 / 1001.0, 59.94, 60.0, 100.0,
1352  120000.0 / 1001.0, 119.88, 120.0
1353  };
1354 
1355  if (Rate > 1.0 && Rate < 121.0)
1356  {
1357  for (auto rate : s_normRates)
1358  if (FuzzyEquals(rate, Rate))
1359  return true;
1360  }
1361  return false;
1362  };
1363 
1364  // If the first choice rate is unusual, see if there is something more 'usual'
1365  double detected = rates.front();
1366  if (Sanitise && !IsStandard(detected))
1367  {
1368  for (auto rate : rates)
1369  {
1370  if (IsStandard(rate))
1371  {
1372  LOG(VB_GENERAL, LOG_INFO, LOC + QString("%1 is non-standard - using %2 instead.")
1373  .arg(rates.front()).arg(rate));
1374 
1375  // The most common problem here is mpegts files where the average
1376  // rate is slightly out and the estimated rate is the fallback.
1377  // As noted above, however, the estimated rate is sometimes twice
1378  // the actual for interlaced content. Try and detect and fix this
1379  // so that we don't throw out deinterlacing and video mode switching.
1380  // Assume anything under 30 may be interlaced - with +-10% error.
1381  if (rate > 33.0 && detected < 33.0)
1382  {
1383  double half = rate / 2.0;
1384  if (qAbs(half - detected) < (half * 0.1))
1385  {
1386  LOG(VB_GENERAL, LOG_INFO, LOC +
1387  QString("Assuming %1 is a better choice than %2")
1388  .arg(half).arg(rate));
1389  return static_cast<float>(half);
1390  }
1391  }
1392  return static_cast<float>(rate);
1393  }
1394  }
1395  }
1396 
1397  return static_cast<float>(detected);
1398 }
1399 
1400 #ifdef USING_DXVA2
1401 // Declared separately to allow attribute
1402 static enum AVPixelFormat get_format_dxva2(struct AVCodecContext *,
1403  const enum AVPixelFormat *);
1404 
1405 enum AVPixelFormat get_format_dxva2(struct AVCodecContext *avctx,
1406  const enum AVPixelFormat *valid_fmts)
1407 {
1408  AvFormatDecoder *nd = (AvFormatDecoder *)(avctx->opaque);
1409  if (nd && nd->GetPlayer())
1410  {
1411  static uint8_t *dummy[1] = { nullptr };
1412  avctx->hwaccel_context =
1413  (dxva_context*)nd->GetPlayer()->GetDecoderContext(nullptr, dummy[0]);
1414  }
1415 
1416  while (*valid_fmts != AV_PIX_FMT_NONE) {
1417  if (avctx->hwaccel_context and (*valid_fmts == AV_PIX_FMT_DXVA2_VLD))
1418  return AV_PIX_FMT_DXVA2_VLD;
1419  if (not avctx->hwaccel_context and (*valid_fmts == AV_PIX_FMT_YUV420P))
1420  return AV_PIX_FMT_YUV420P;
1421  valid_fmts++;
1422  }
1423  return AV_PIX_FMT_NONE;
1424 }
1425 #endif
1426 
1427 int AvFormatDecoder::GetMaxReferenceFrames(AVCodecContext *Context)
1428 {
1429  switch (Context->codec_id)
1430  {
1431  case AV_CODEC_ID_H264:
1432  {
1433  int result = 16;
1434  if (Context->extradata && (Context->extradata_size >= 7))
1435  {
1436  uint8_t offset = 0;
1437  if (Context->extradata[0] == 1)
1438  offset = 9; // avCC
1439  else if (AV_RB24(Context->extradata) == 0x01) // Annex B - 3 byte startcode 0x000001
1440  offset = 4;
1441  else if (AV_RB32(Context->extradata) == 0x01) // Annex B - 4 byte startcode 0x00000001
1442  offset= 5;
1443 
1444  if (offset)
1445  {
1446  AVCParser parser;
1447  bool dummy = false;
1448  parser.parse_SPS(Context->extradata + offset,
1449  static_cast<uint>(Context->extradata_size - offset), dummy, result);
1450  }
1451  }
1452  return result;
1453  }
1454  case AV_CODEC_ID_H265: return 16;
1455  case AV_CODEC_ID_VP9: return 8;
1456  case AV_CODEC_ID_VP8: return 3;
1457  default: break;
1458  }
1459  return 2;
1460 }
1461 
1462 void AvFormatDecoder::InitVideoCodec(AVStream *stream, AVCodecContext *enc,
1463  bool selectedStream)
1464 {
1465  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1466  QString("InitVideoCodec ID:%1 Type:%2 Size:%3x%4")
1467  .arg(ff_codec_id_string(enc->codec_id),
1468  ff_codec_type_string(enc->codec_type))
1469  .arg(enc->width).arg(enc->height));
1470 
1471  if (m_ringBuffer && m_ringBuffer->IsDVD())
1472  m_directRendering = false;
1473 
1474  enc->opaque = static_cast<void*>(this);
1475  enc->get_buffer2 = get_avf_buffer;
1476  enc->slice_flags = 0;
1477 
1478  enc->err_recognition = AV_EF_COMPLIANT;
1479  enc->workaround_bugs = FF_BUG_AUTODETECT;
1480  enc->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
1481  enc->idct_algo = FF_IDCT_AUTO;
1482  enc->debug = 0;
1483  // enc->error_rate = 0;
1484 
1485  const AVCodec *codec1 = enc->codec;
1486 
1487  if (selectedStream)
1488  m_directRendering = true;
1489 
1490  // retrieve rotation information
1491  uint8_t* displaymatrix = av_stream_get_side_data(stream, AV_PKT_DATA_DISPLAYMATRIX, nullptr);
1492  if (displaymatrix)
1493  m_videoRotation = static_cast<int>(-av_display_rotation_get(reinterpret_cast<int32_t*>(displaymatrix)));
1494  else
1495  m_videoRotation = 0;
1496 
1497  // retrieve 3D type
1498  uint8_t* stereo3d = av_stream_get_side_data(stream, AV_PKT_DATA_STEREO3D, nullptr);
1499  if (stereo3d)
1500  {
1501  auto * avstereo = reinterpret_cast<AVStereo3D*>(stereo3d);
1502  m_stereo3D = avstereo->type;
1503  }
1504 
1505  delete m_mythCodecCtx;
1507  m_mythCodecCtx->InitVideoCodec(enc, selectedStream, m_directRendering);
1508  if (m_mythCodecCtx->HwDecoderInit(enc) < 0)
1509  {
1510  // force it to switch to software decoding
1512  m_streamsChanged = true;
1513  }
1514  else
1515  {
1516  // Note: This is never going to work as expected in all circumstances.
1517  // It will not account for changes in the stream and/or display. For
1518  // MediaCodec, Android will do its own thing (and judging by the Android logs,
1519  // shouldn't double rate the deinterlacing if the display cannot support it).
1520  // NVDEC will probably move to the FFmpeg YADIF CUDA deinterlacer - which
1521  // will avoid the issue (video player deinterlacing) and maybe disable
1522  // decoder VAAPI deinterlacing. If we get it wrong and the display cannot
1523  // keep up, the player should just drop frames.
1524 
1525  // FIXME - need a better way to handle this
1526  bool doublerate = true;//m_parent->CanSupportDoubleRate();
1528  }
1529 
1530  if (codec1 && ((AV_CODEC_ID_MPEG2VIDEO == codec1->id) ||
1531  (AV_CODEC_ID_MPEG1VIDEO == codec1->id)))
1532  {
1534  {
1535  int total_blocks = (enc->height + 15) / 16;
1536  enc->skip_top = (total_blocks + 3) / 4;
1537  enc->skip_bottom = (total_blocks + 3) / 4;
1538  }
1539 
1540  if (FlagIsSet(kDecodeLowRes))
1541  enc->lowres = 2; // 1 = 1/2 size, 2 = 1/4 size
1542  }
1543  else if (codec1 && (AV_CODEC_ID_H264 == codec1->id) && FlagIsSet(kDecodeNoLoopFilter))
1544  {
1545  enc->flags &= ~AV_CODEC_FLAG_LOOP_FILTER;
1546  enc->skip_loop_filter = AVDISCARD_ALL;
1547  }
1548 
1550  enc->skip_idct = AVDISCARD_ALL;
1551 
1552  if (selectedStream)
1553  {
1554  // m_fps is now set 'correctly' in ScanStreams so this additional call
1555  // to GetVideoFrameRate may now be redundant
1556  m_fps = GetVideoFrameRate(stream, enc, true);
1557  QSize dim = get_video_dim(*enc);
1558  int width = m_currentWidth = dim.width();
1559  int height = m_currentHeight = dim.height();
1560  m_currentAspect = get_aspect(*enc);
1561 
1562  if (!width || !height)
1563  {
1564  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1565  "InitVideoCodec invalid dimensions, resetting decoder.");
1566  width = 640;
1567  height = 480;
1568  m_fps = 29.97F;
1569  m_currentAspect = 4.0F / 3.0F;
1570  }
1571 
1573  const AVCodec *codec2 = enc->codec;
1574  QString codecName;
1575  if (codec2)
1576  codecName = codec2->name;
1577  m_parent->SetVideoParams(width, height, static_cast<double>(m_fps),
1579  kScan_Detect, codecName);
1580  if (LCD *lcd = LCD::Get())
1581  {
1582  LCDVideoFormatSet video_format = VIDEO_MPG;
1583 
1584  switch (enc->codec_id)
1585  {
1586  case AV_CODEC_ID_H263:
1587  case AV_CODEC_ID_MPEG4:
1588  case AV_CODEC_ID_MSMPEG4V1:
1589  case AV_CODEC_ID_MSMPEG4V2:
1590  case AV_CODEC_ID_MSMPEG4V3:
1591  case AV_CODEC_ID_H263P:
1592  case AV_CODEC_ID_H263I:
1593  video_format = VIDEO_DIVX;
1594  break;
1595  case AV_CODEC_ID_WMV1:
1596  case AV_CODEC_ID_WMV2:
1597  video_format = VIDEO_WMV;
1598  break;
1599 #if 0
1600  case AV_CODEC_ID_XVID:
1601  video_format = VIDEO_XVID;
1602  break;
1603 #endif
1604  default:
1605  video_format = VIDEO_MPG;
1606  break;
1607  }
1608 
1609  lcd->setVideoFormatLEDs(video_format, true);
1610 
1611  if(height >= 720)
1612  lcd->setVariousLEDs(VARIOUS_HDTV, true);
1613  else
1614  lcd->setVariousLEDs(VARIOUS_HDTV, false);
1615  }
1616  }
1617 }
1618 
1619 // CC Parity checking
1620 // taken from xine-lib libspucc
1621 
1622 static int cc608_parity(uint8_t byte)
1623 {
1624  int ones = 0;
1625 
1626  for (int i = 0; i < 7; i++)
1627  {
1628  if (byte & (1 << i))
1629  ones++;
1630  }
1631 
1632  return ones & 1;
1633 }
1634 
1635 // CC Parity checking
1636 // taken from xine-lib libspucc
1637 
1638 static void cc608_build_parity_table(CC608Parity &parity_table)
1639 {
1640  for (uint8_t byte = 0; byte <= 127; byte++)
1641  {
1642  int parity_v = cc608_parity(byte);
1643  /* CC uses odd parity (i.e., # of 1's in byte is odd.) */
1644  parity_table[byte] = parity_v;
1645  parity_table[byte | 0x80] = (parity_v == 0 ? 1 : 0);
1646  }
1647 }
1648 
1649 // CC Parity checking
1650 // taken from xine-lib libspucc
1651 
1652 static int cc608_good_parity(const CC608Parity &parity_table, uint16_t data)
1653 {
1654  bool ret = (parity_table[data & 0xff] != 0)
1655  && (parity_table[(data & 0xff00) >> 8] != 0);
1656  if (!ret)
1657  {
1658  LOG(VB_VBI, LOG_ERR, LOC +
1659  QString("VBI: Bad parity in EIA-608 data (%1)") .arg(data,0,16));
1660  }
1661  return ret ? 1 : 0;
1662 }
1663 
1665 {
1666  QMutexLocker locker(&m_trackLock);
1667 
1668  m_ccX08InPmt.fill(false);
1669  m_pmtTracks.clear();
1670  m_pmtTrackTypes.clear();
1671 
1672  // Figure out languages of ATSC captions
1673  if (!m_ic->cur_pmt_sect)
1674  {
1675  LOG(VB_GENERAL, LOG_DEBUG, LOC +
1676  "ScanATSCCaptionStreams() called with no PMT");
1677  return;
1678  }
1679 
1680  const ProgramMapTable pmt(PSIPTable(m_ic->cur_pmt_sect));
1681 
1682  bool video_found = false;
1683  uint i = 0;
1684  for (i = 0; i < pmt.StreamCount(); i++)
1685  {
1686  // MythTV remaps OpenCable Video to normal video during recording
1687  // so "dvb" is the safest choice for system info type, since this
1688  // will ignore other uses of the same stream id in DVB countries.
1689  if (pmt.IsVideo(i, "dvb"))
1690  {
1691  video_found = true;
1692  break;
1693  }
1694  }
1695  if (!video_found)
1696  return;
1697 
1699  pmt.StreamInfo(i), pmt.StreamInfoLength(i),
1701 
1702  const desc_list_t desc_list2 = MPEGDescriptor::ParseOnlyInclude(
1703  pmt.ProgramInfo(), pmt.ProgramInfoLength(),
1705 
1706  desc_list.insert(desc_list.end(), desc_list2.begin(), desc_list2.end());
1707 
1708  for (auto & desc : desc_list)
1709  {
1710  const CaptionServiceDescriptor csd(desc);
1711  if (!csd.IsValid())
1712  continue;
1713 
1714  LOG(VB_VBI, LOG_DEBUG, LOC + csd.toString());
1715 
1716  for (uint k = 0; k < csd.ServicesCount(); k++)
1717  {
1718  int lang = csd.CanonicalLanguageKey(k);
1719  int type = csd.Type(k) ? 1 : 0;
1720  if (type)
1721  {
1722  StreamInfo si(av_index, lang, 0/*lang_idx*/,
1723  csd.CaptionServiceNumber(k),
1724  static_cast<int>(csd.EasyReader(k)),
1725  csd.WideAspectRatio(k));
1726  uint key = csd.CaptionServiceNumber(k) + 4;
1727  m_ccX08InPmt[key] = true;
1728  m_pmtTracks.push_back(si);
1729  m_pmtTrackTypes.push_back(kTrackTypeCC708);
1730  }
1731  else
1732  {
1733  int line21 = csd.Line21Field(k) ? 3 : 1;
1734  StreamInfo si(av_index, lang, 0/*lang_idx*/, line21, 0);
1735  m_ccX08InPmt[line21-1] = true;
1736  m_pmtTracks.push_back(si);
1737  m_pmtTrackTypes.push_back(kTrackTypeCC608);
1738  }
1739  }
1740  }
1741 }
1742 
1744 {
1745  QMutexLocker locker(&m_trackLock);
1746 
1747  m_tracks[kTrackTypeCC608].clear();
1748  m_tracks[kTrackTypeCC708].clear();
1749  m_ccX08InTracks.fill(false);
1750 
1751  uint pidx = 0;
1752  uint sidx = 0;
1753  std::array<std::map<int,uint>,2> lang_cc_cnt;
1754  while (true)
1755  {
1756  bool pofr = pidx >= (uint)m_pmtTracks.size();
1757  bool sofr = sidx >= (uint)m_streamTracks.size();
1758  if (pofr && sofr)
1759  break;
1760 
1761  // choose lowest available next..
1762  // stream_id's of 608 and 708 streams alias, but this
1763  // is ok as we just want each list to be ordered.
1764  StreamInfo const *si = nullptr;
1765  int type = 0; // 0 if 608, 1 if 708
1766  bool isp = true; // if true use m_pmtTracks next, else stream_tracks
1767 
1768  if (pofr && !sofr)
1769  isp = false; // NOLINT(bugprone-branch-clone)
1770  else if (!pofr && sofr)
1771  isp = true;
1772  else if (m_streamTracks[sidx] < m_pmtTracks[pidx])
1773  isp = false;
1774 
1775  if (isp)
1776  {
1777  si = &m_pmtTracks[pidx];
1778  type = kTrackTypeCC708 == m_pmtTrackTypes[pidx] ? 1 : 0;
1779  pidx++;
1780  }
1781  else
1782  {
1783  si = &m_streamTracks[sidx];
1784  type = kTrackTypeCC708 == m_streamTrackTypes[sidx] ? 1 : 0;
1785  sidx++;
1786  }
1787 
1788  StreamInfo nsi(*si);
1789  int lang_indx = lang_cc_cnt[type][nsi.m_language];
1790  lang_cc_cnt[type][nsi.m_language]++;
1791  nsi.m_language_index = lang_indx;
1792  m_tracks[(type) ? kTrackTypeCC708 : kTrackTypeCC608].push_back(nsi);
1793  int key = nsi.m_stream_id + ((type) ? 4 : -1);
1794  if (key < 0)
1795  {
1796  LOG(VB_GENERAL, LOG_ERR, LOC + "in_tracks key too small");
1797  }
1798  else
1799  {
1800  m_ccX08InTracks[key] = true;
1801  }
1802  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1803  QString("%1 caption service #%2 is in the %3 language.")
1804  .arg((type) ? "EIA-708" : "EIA-608")
1805  .arg(nsi.m_stream_id)
1806  .arg(iso639_key_toName(nsi.m_language)));
1807  }
1808 }
1809 
1811 {
1812  QMutexLocker locker(&m_trackLock);
1813 
1814  // ScanStreams() calls m_tracks[kTrackTypeTeletextCaptions].clear()
1815  if (!m_ic->cur_pmt_sect || !m_tracks[kTrackTypeTeletextCaptions].empty())
1816  return;
1817 
1818  const ProgramMapTable pmt(PSIPTable(m_ic->cur_pmt_sect));
1819 
1820  for (uint i = 0; i < pmt.StreamCount(); i++)
1821  {
1822  if (pmt.StreamType(i) != StreamID::PrivData)
1823  continue;
1824 
1826  pmt.StreamInfo(i), pmt.StreamInfoLength(i),
1828 
1829  for (const auto *desc : desc_list)
1830  {
1831  const TeletextDescriptor td(desc);
1832  if (!td.IsValid())
1833  continue;
1834  for (uint k = 0; k < td.StreamCount(); k++)
1835  {
1836  int type = td.TeletextType(k);
1837  int language = td.CanonicalLanguageKey(k);
1838  int magazine = td.TeletextMagazineNum(k);
1839  if (magazine == 0)
1840  magazine = 8;
1841  int pagenum = td.TeletextPageNum(k);
1842  int lang_idx = (magazine << 8) | pagenum;
1843  StreamInfo si(av_index, language, lang_idx, 0, 0);
1844  if (type == 2 || type == 1)
1845  {
1846  TrackType track = (type == 2) ? kTrackTypeTeletextCaptions :
1848  m_tracks[track].push_back(si);
1849  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1850  QString("Teletext stream #%1 (%2) is in the %3 language"
1851  " on page %4 %5.")
1852  .arg(QString::number(k),
1853  (type == 2) ? "Caption" : "Menu",
1854  iso639_key_toName(language),
1855  QString::number(magazine),
1856  QString::number(pagenum)));
1857  }
1858  }
1859  }
1860 
1861  // Assume there is only one multiplexed teletext stream in PMT..
1862  if (!m_tracks[kTrackTypeTeletextCaptions].empty())
1863  break;
1864  }
1865 }
1866 
1867 void AvFormatDecoder::ScanRawTextCaptions(int av_stream_index)
1868 {
1869  QMutexLocker locker(&m_trackLock);
1870 
1871  AVDictionaryEntry *metatag =
1872  av_dict_get(m_ic->streams[av_stream_index]->metadata, "language", nullptr,
1873  0);
1874  bool forced = (m_ic->streams[av_stream_index]->disposition & AV_DISPOSITION_FORCED) != 0;
1875  int lang = metatag ? get_canonical_lang(metatag->value) :
1876  iso639_str3_to_key("und");
1877  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1878  QString("Text Subtitle track #%1 is A/V stream #%2 "
1879  "and is in the %3 language(%4), forced=%5.")
1880  .arg(m_tracks[kTrackTypeRawText].size()).arg(av_stream_index)
1881  .arg(iso639_key_toName(lang)).arg(lang).arg(forced));
1882  StreamInfo si(av_stream_index, lang, 0, 0, 0, false, false, forced);
1883  m_tracks[kTrackTypeRawText].push_back(si);
1884 }
1885 
1891 {
1892  if (!m_ic || !m_ic->cur_pmt_sect)
1893  return;
1894 
1895  if (!m_itv && ! (m_itv = m_parent->GetInteractiveTV()))
1896  return;
1897 
1898  const ProgramMapTable pmt(PSIPTable(m_ic->cur_pmt_sect));
1899 
1900  for (uint i = 0; i < pmt.StreamCount(); i++)
1901  {
1902  if (! StreamID::IsObjectCarousel(pmt.StreamType(i)))
1903  continue;
1904 
1905  LOG(VB_DSMCC, LOG_NOTICE, QString("ScanDSMCCStreams Found Object Carousel in Stream %1").arg(QString::number(i)));
1906 
1908  pmt.StreamInfo(i), pmt.StreamInfoLength(i),
1910 
1911  for (const auto *desc : desc_list)
1912  {
1913  desc++; // Skip tag
1914  uint length = *desc++;
1915  const unsigned char *endDesc = desc+length;
1916  uint dataBroadcastId = desc[0]<<8 | desc[1];
1917  LOG(VB_DSMCC, LOG_NOTICE, QString("ScanDSMCCStreams dataBroadcastId %1").arg(QString::number(dataBroadcastId)));
1918  if (dataBroadcastId != 0x0106) // ETSI/UK Profile
1919  continue;
1920  desc += 2; // Skip data ID
1921  while (desc != endDesc)
1922  {
1923  uint appTypeCode = desc[0]<<8 | desc[1];
1924  desc += 3; // Skip app type code and boot priority hint
1925  uint appSpecDataLen = *desc++;
1926 #ifdef USING_MHEG
1927  LOG(VB_DSMCC, LOG_NOTICE, QString("ScanDSMCCStreams AppTypeCode %1").arg(QString::number(appTypeCode)));
1928  if (appTypeCode == 0x101) // UK MHEG profile
1929  {
1930  const unsigned char *subDescEnd = desc + appSpecDataLen;
1931  while (desc < subDescEnd)
1932  {
1933  uint sub_desc_tag = *desc++;
1934  uint sub_desc_len = *desc++;
1935  // Network boot info sub-descriptor.
1936  if (sub_desc_tag == 1)
1937  m_itv->SetNetBootInfo(desc, sub_desc_len);
1938  desc += sub_desc_len;
1939  }
1940  }
1941  else
1942 #else
1943  (void) appTypeCode;
1944 #endif // USING_MHEG
1945  {
1946  desc += appSpecDataLen;
1947  }
1948  }
1949  }
1950  }
1951 }
1952 
1954 {
1955  QMutexLocker avlocker(&m_avCodecLock);
1956  QMutexLocker locker(&m_trackLock);
1957 
1958  bool unknownbitrate = false;
1959  int scanerror = 0;
1960  m_bitrate = 0;
1961 
1962  m_tracks[kTrackTypeAttachment].clear();
1963  m_tracks[kTrackTypeAudio].clear();
1964  m_tracks[kTrackTypeSubtitle].clear();
1967  m_tracks[kTrackTypeRawText].clear();
1968  if (!novideo)
1969  {
1970  // we will rescan video streams
1971  m_tracks[kTrackTypeVideo].clear();
1972  m_selectedTrack[kTrackTypeVideo].m_av_stream_index = -1;
1973  m_fps = 0;
1974  }
1975  std::map<int,uint> lang_sub_cnt;
1976  uint subtitleStreamCount = 0;
1977  std::map<int,uint> lang_aud_cnt;
1978  uint audioStreamCount = 0;
1979 
1980  if (m_ringBuffer && m_ringBuffer->IsDVD() &&
1982  {
1985  }
1986 
1987  for (uint strm = 0; strm < m_ic->nb_streams; strm++)
1988  {
1989  AVCodecParameters *par = m_ic->streams[strm]->codecpar;
1990  AVCodecContext *enc = nullptr;
1991 
1992  QString codectype(ff_codec_type_string(par->codec_type));
1993  if (par->codec_type == AVMEDIA_TYPE_VIDEO)
1994  codectype += QString("(%1x%2)").arg(par->width).arg(par->height);
1995  LOG(VB_PLAYBACK, LOG_INFO, LOC +
1996  QString("Stream #%1: ID: 0x%2 Codec ID: %3 Type: %4 Bitrate: %5")
1997  .arg(strm).arg(static_cast<uint64_t>(m_ic->streams[strm]->id), 0, 16)
1998  .arg(ff_codec_id_string(par->codec_id),
1999  codectype).arg(par->bit_rate));
2000 
2001  switch (par->codec_type)
2002  {
2003  case AVMEDIA_TYPE_VIDEO:
2004  {
2005  // reset any potentially errored hardware decoders
2007  {
2008  if (m_codecMap.FindCodecContext(m_ic->streams[strm]))
2009  {
2010  AVCodecContext* ctx = m_codecMap.GetCodecContext(m_ic->streams[strm]);
2011  if (ctx && (ctx->hw_frames_ctx || ctx->hw_device_ctx))
2012  m_codecMap.FreeCodecContext(m_ic->streams[strm]);
2013  }
2014  }
2015 
2016  if (!par->codec_id)
2017  {
2018  LOG(VB_GENERAL, LOG_ERR, LOC +
2019  QString("Stream #%1 has an unknown video "
2020  "codec id, skipping.").arg(strm));
2021  continue;
2022  }
2023 
2024  // ffmpeg does not return a bitrate for several codecs and
2025  // formats. Typically the same streams do not have a duration either
2026  // - so we cannot estimate a bitrate (which would be subject
2027  // to significant error anyway if there were multiple video streams).
2028  // So we need to guesstimate a value that avoids low bitrate optimisations
2029  // (which typically kick in around 500,000) and provides a read
2030  // chunk size large enough to avoid starving the decoder of data.
2031  // Trying to read a 20Mbs stream with a 16KB chunk size does not work:)
2032  if (par->bit_rate == 0)
2033  {
2034  static const int s_baseBitrate = 1000000;
2035  int multiplier = 1;
2036  if (par->width && par->height)
2037  {
2038  static const int s_baseSize = 1920 * 1080;
2039  multiplier = ((par->width * par->height) + s_baseSize - 1) / s_baseSize;
2040  if (multiplier < 1)
2041  multiplier = 1;
2042  }
2043  par->bit_rate = s_baseBitrate * multiplier;
2044  unknownbitrate = true;
2045  }
2046  m_bitrate += par->bit_rate;
2047 
2048  break;
2049  }
2050  case AVMEDIA_TYPE_AUDIO:
2051  {
2052  enc = m_codecMap.FindCodecContext(m_ic->streams[strm]);
2053  if (enc && enc->internal)
2054  {
2055  LOG(VB_GENERAL, LOG_WARNING, LOC +
2056  QString("Warning, audio codec 0x%1 id(%2) "
2057  "type (%3) already open, leaving it alone.")
2058  .arg(reinterpret_cast<unsigned long long>(enc), 0, 16)
2059  .arg(ff_codec_id_string(enc->codec_id),
2060  ff_codec_type_string(enc->codec_type)));
2061  }
2062  LOG(VB_GENERAL, LOG_INFO, LOC +
2063  QString("codec %1 has %2 channels")
2064  .arg(ff_codec_id_string(par->codec_id))
2065  .arg(par->channels));
2066 
2067  m_bitrate += par->bit_rate;
2068  break;
2069  }
2070  case AVMEDIA_TYPE_SUBTITLE:
2071  {
2072  if (par->codec_id == AV_CODEC_ID_DVB_TELETEXT)
2073  ScanTeletextCaptions(static_cast<int>(strm));
2074  if (par->codec_id == AV_CODEC_ID_TEXT)
2075  ScanRawTextCaptions(static_cast<int>(strm));
2076  m_bitrate += par->bit_rate;
2077 
2078  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("subtitle codec (%1)")
2079  .arg(ff_codec_type_string(par->codec_type)));
2080  break;
2081  }
2082  case AVMEDIA_TYPE_DATA:
2083  {
2084  ScanTeletextCaptions(static_cast<int>(strm));
2085  m_bitrate += par->bit_rate;
2086  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("data codec (%1)")
2087  .arg(ff_codec_type_string(par->codec_type)));
2088  break;
2089  }
2090  case AVMEDIA_TYPE_ATTACHMENT:
2091  {
2092  if (par->codec_id == AV_CODEC_ID_TTF)
2093  m_tracks[kTrackTypeAttachment].emplace_back(
2094  static_cast<int>(strm), 0, 0, m_ic->streams[strm]->id, 0);
2095  m_bitrate += par->bit_rate;
2096  LOG(VB_PLAYBACK, LOG_INFO, LOC +
2097  QString("Attachment codec (%1)")
2098  .arg(ff_codec_type_string(par->codec_type)));
2099  break;
2100  }
2101  default:
2102  {
2103  m_bitrate += par->bit_rate;
2104  LOG(VB_PLAYBACK, LOG_ERR, LOC +
2105  QString("Unknown codec type (%1)")
2106  .arg(ff_codec_type_string(par->codec_type)));
2107  break;
2108  }
2109  }
2110 
2111  if (par->codec_type != AVMEDIA_TYPE_AUDIO &&
2112  par->codec_type != AVMEDIA_TYPE_SUBTITLE)
2113  continue;
2114 
2115  // skip DVB teletext and text subs, there is no libavcodec decoder
2116  if (par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
2117  (par->codec_id == AV_CODEC_ID_DVB_TELETEXT ||
2118  par->codec_id == AV_CODEC_ID_TEXT))
2119  continue;
2120 
2121  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Looking for decoder for %1")
2122  .arg(ff_codec_id_string(par->codec_id)));
2123 
2124  if (par->codec_id == AV_CODEC_ID_PROBE)
2125  {
2126  LOG(VB_GENERAL, LOG_ERR, LOC +
2127  QString("Probing of stream #%1 unsuccesful, ignoring.").arg(strm));
2128  continue;
2129  }
2130 
2131  if (!enc)
2132  enc = m_codecMap.GetCodecContext(m_ic->streams[strm]);
2133 
2134  const AVCodec *codec = nullptr;
2135  if (enc)
2136  codec = enc->codec;
2137  else
2138  {
2139  LOG(VB_GENERAL, LOG_ERR, LOC +
2140  QString("Could not find decoder for codec (%1), ignoring.")
2141  .arg(ff_codec_id_string(par->codec_id)));
2142 
2143  // Nigel's bogus codec-debug. Dump the list of codecs & decoders,
2144  // and have one last attempt to find a decoder. This is usually
2145  // only caused by build problems, where libavcodec needs a rebuild
2146  if (VERBOSE_LEVEL_CHECK(VB_LIBAV, LOG_ANY))
2147  {
2148  void *opaque = nullptr;
2149  const AVCodec *p = av_codec_iterate(&opaque);
2150  int i = 1;
2151  while (p)
2152  {
2153  QString msg;
2154 
2155  if (p->name[0] != '\0')
2156  msg = QString("Codec %1:").arg(p->name);
2157  else
2158  msg = QString("Codec %1, null name,").arg(strm);
2159 
2160  if (p->decode == nullptr)
2161  msg += "decoder is null";
2162 
2163  LOG(VB_LIBAV, LOG_INFO, LOC + msg);
2164 
2165  if (p->id == par->codec_id)
2166  {
2167  codec = p;
2168  break;
2169  }
2170 
2171  LOG(VB_LIBAV, LOG_INFO, LOC +
2172  QString("Codec 0x%1 != 0x%2") .arg(p->id, 0, 16)
2173  .arg(par->codec_id, 0, 16));
2174  p = av_codec_iterate(&opaque);
2175  ++i;
2176  }
2177  }
2178  if (codec)
2179  enc = m_codecMap.GetCodecContext(m_ic->streams[strm], codec);
2180  else
2181  continue;
2182  }
2183  if (!enc)
2184  continue;
2185 
2186  if (enc->codec && par->codec_id != enc->codec_id)
2187  {
2188  LOG(VB_PLAYBACK, LOG_INFO, LOC +
2189  QString("Already opened codec not matching (%1 vs %2). Reopening")
2190  .arg(ff_codec_id_string(enc->codec_id),
2191  ff_codec_id_string(enc->codec->id)));
2192  m_codecMap.FreeCodecContext(m_ic->streams[strm]);
2193  enc = m_codecMap.GetCodecContext(m_ic->streams[strm]);
2194  }
2195  if (!OpenAVCodec(enc, codec))
2196  continue;
2197  if (!enc)
2198  continue;
2199 
2200  if (!IsValidStream(m_ic->streams[strm]->id))
2201  {
2202  /* Hide this stream if it's not valid in this context.
2203  * This can happen, for example, on a Blu-ray disc if there
2204  * are more physical streams than there is metadata about them.
2205  * (e.g. Despicable Me)
2206  */
2207  LOG(VB_PLAYBACK, LOG_INFO, LOC +
2208  QString("Stream 0x%1 is not valid in this context - skipping")
2209  .arg(m_ic->streams[strm]->id, 4, 16));
2210  continue;
2211  }
2212 
2213  if (par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2214  {
2215  bool forced = (m_ic->streams[strm]->disposition & AV_DISPOSITION_FORCED) != 0;
2216  int lang = GetSubtitleLanguage(subtitleStreamCount, strm);
2217  uint lang_indx = lang_sub_cnt[lang]++;
2218  subtitleStreamCount++;
2219 
2220  m_tracks[kTrackTypeSubtitle].emplace_back(
2221  static_cast<int>(strm), lang, lang_indx, m_ic->streams[strm]->id, 0, 0, false, false, forced);
2222 
2223  LOG(VB_PLAYBACK, LOG_INFO, LOC +
2224  QString("Subtitle track #%1 is A/V stream #%2 "
2225  "and is in the %3 language(%4).")
2226  .arg(m_tracks[kTrackTypeSubtitle].size()).arg(strm)
2227  .arg(iso639_key_toName(lang)).arg(lang));
2228  }
2229 
2230  if (par->codec_type == AVMEDIA_TYPE_AUDIO)
2231  {
2232  int lang = GetAudioLanguage(audioStreamCount, strm);
2234  int channels = par->channels;
2235  uint lang_indx = lang_aud_cnt[lang]++;
2236  audioStreamCount++;
2237 
2238  if (enc->avcodec_dual_language)
2239  {
2240  m_tracks[kTrackTypeAudio].emplace_back(
2241  static_cast<int>(strm), lang, lang_indx, m_ic->streams[strm]->id, channels,
2242  false, false, false, type);
2243  lang_indx = lang_aud_cnt[lang]++;
2244  m_tracks[kTrackTypeAudio].emplace_back(
2245  static_cast<int>(strm), lang, lang_indx, m_ic->streams[strm]->id, channels,
2246  true, false, false, type);
2247  }
2248  else
2249  {
2250  int logical_stream_id = 0;
2251  if (m_ringBuffer && m_ringBuffer->IsDVD())
2252  {
2253  logical_stream_id = m_ringBuffer->DVD()->GetAudioTrackNum(m_ic->streams[strm]->id);
2254  channels = m_ringBuffer->DVD()->GetNumAudioChannels(logical_stream_id);
2255  }
2256  else
2257  logical_stream_id = m_ic->streams[strm]->id;
2258 
2259  if (logical_stream_id == -1)
2260  {
2261  // This stream isn't mapped, so skip it
2262  continue;
2263  }
2264 
2265  m_tracks[kTrackTypeAudio].emplace_back(
2266  static_cast<int>(strm), lang, lang_indx, logical_stream_id, channels,
2267  false, false, false, type);
2268  }
2269 
2270  LOG(VB_AUDIO, LOG_INFO, LOC +
2271  QString("Audio Track #%1, of type (%2) is A/V stream #%3 (id=0x%4) "
2272  "and has %5 channels in the %6 language(%7).")
2273  .arg(m_tracks[kTrackTypeAudio].size()).arg(toString(type))
2274  .arg(strm).arg(m_ic->streams[strm]->id,0,16).arg(enc->channels)
2275  .arg(iso639_key_toName(lang)).arg(lang));
2276  }
2277  }
2278 
2279  // Now find best video track to play
2280  m_resetHardwareDecoders = false;
2281  if (!novideo && m_ic)
2282  {
2283  for(;;)
2284  {
2285  AVCodec *codec = nullptr;
2286  LOG(VB_PLAYBACK, LOG_INFO, LOC + "Trying to select best video track");
2287 
2288  /*
2289  * Find the "best" stream in the file.
2290  *
2291  * The best stream is determined according to various heuristics as
2292  * the most likely to be what the user expects. If the decoder parameter
2293  * is not nullptr, av_find_best_stream will find the default decoder
2294  * for the stream's codec; streams for which no decoder can be found
2295  * are ignored.
2296  *
2297  * If av_find_best_stream returns successfully and decoder_ret is not nullptr,
2298  * then *decoder_ret is guaranteed to be set to a valid AVCodec.
2299  */
2300  int selTrack = av_find_best_stream(m_ic, AVMEDIA_TYPE_VIDEO,
2301  -1, -1, &codec, 0);
2302 
2303  if (selTrack < 0)
2304  {
2305  LOG(VB_PLAYBACK, LOG_INFO, LOC + "No video track found/selected.");
2306  break;
2307  }
2308 
2309  AVStream *stream = m_ic->streams[selTrack];
2311  m_codecMap.FreeCodecContext(stream);
2312  AVCodecContext *enc = m_codecMap.GetCodecContext(stream, codec);
2313  StreamInfo si(selTrack, 0, 0, 0, 0);
2314 
2315  m_tracks[kTrackTypeVideo].push_back(si);
2317 
2318  QString codectype(ff_codec_type_string(enc->codec_type));
2319  if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
2320  codectype += QString("(%1x%2)").arg(enc->width).arg(enc->height);
2321  LOG(VB_PLAYBACK, LOG_INFO, LOC +
2322  QString("Selected track #%1: ID: 0x%2 Codec ID: %3 Profile: %4 Type: %5 Bitrate: %6")
2323  .arg(selTrack).arg(static_cast<uint64_t>(stream->id), 0, 16)
2324  .arg(ff_codec_id_string(enc->codec_id),
2325  avcodec_profile_name(enc->codec_id, enc->profile),
2326  codectype,
2327  QString::number(enc->bit_rate)));
2328 
2329  // If ScanStreams has been called on a stream change triggered by a
2330  // decoder error - because the decoder does not handle resolution
2331  // changes gracefully (NVDEC and maybe MediaCodec) - then the stream/codec
2332  // will still contain the old resolution but the AVCodecContext will
2333  // have been updated. This causes mayhem for a second or two.
2334  if ((enc->width != stream->codecpar->width) || (enc->height != stream->codecpar->height))
2335  {
2336  LOG(VB_GENERAL, LOG_INFO, LOC + QString(
2337  "Video resolution mismatch: Context: %1x%2 Stream: %3x%4 Codec: %5 Stream change: %6")
2338  .arg(enc->width).arg(enc->height)
2339  .arg(stream->codecpar->width).arg(stream->codecpar->height)
2341  }
2342 
2343  m_avcParser->Reset();
2344 
2345  QSize dim = get_video_dim(*enc);
2346  int width = std::max(dim.width(), 16);
2347  int height = std::max(dim.height(), 16);
2348  QString dec = "ffmpeg";
2349  uint thread_count = 1;
2350  QString codecName;
2351  if (enc->codec)
2352  codecName = enc->codec->name;
2353  // framerate appears to never be set - which is probably why
2354  // GetVideoFrameRate never uses it:)
2355  // So fallback to the GetVideoFrameRate call which should then ensure
2356  // the video display profile gets an accurate frame rate - instead of 0
2357  if (enc->framerate.den && enc->framerate.num)
2358  m_fps = float(enc->framerate.num) / float(enc->framerate.den);
2359  else
2360  m_fps = GetVideoFrameRate(stream, enc, true);
2361 
2362  bool foundgpudecoder = false;
2363  QStringList unavailabledecoders;
2364  bool allowgpu = FlagIsSet(kDecodeAllowGPU);
2365 
2367  {
2368  // TODO this could be improved by appending the decoder that has
2369  // failed to the unavailable list - but that could lead to circular
2370  // failures if there are 2 or more hardware decoders that fail
2371  if (FlagIsSet(kDecodeAllowGPU) && (dec != "ffmpeg"))
2372  {
2373  LOG(VB_GENERAL, LOG_WARNING, LOC + QString(
2374  "GPU/hardware decoder '%1' failed - forcing software decode")
2375  .arg(dec));
2376  }
2377  m_averrorCount = 0;
2378  allowgpu = false;
2379  }
2380 
2381  while (unavailabledecoders.size() < 10)
2382  {
2383  if (!m_isDbIgnored)
2384  {
2385  if (!unavailabledecoders.isEmpty())
2386  {
2387  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Unavailable decoders: %1")
2388  .arg(unavailabledecoders.join(",")));
2389  }
2390  m_videoDisplayProfile.SetInput(QSize(width, height), m_fps, codecName, unavailabledecoders);
2392  thread_count = m_videoDisplayProfile.GetMaxCPUs();
2393  bool skip_loop_filter = m_videoDisplayProfile.IsSkipLoopEnabled();
2394  if (!skip_loop_filter)
2395  enc->skip_loop_filter = AVDISCARD_NONKEY;
2396  }
2397 
2399  uint version = mpeg_version(enc->codec_id);
2400  if (version)
2401  m_videoCodecId = static_cast<MythCodecID>(kCodec_MPEG1 + version - 1);
2402 
2403  if (version && allowgpu && dec != "ffmpeg")
2404  {
2405  // We need to set this so that MythyCodecContext can callback
2406  // to the player in use to check interop support.
2407  enc->opaque = static_cast<void*>(this);
2408  MythCodecID hwcodec = MythCodecContext::FindDecoder(dec, stream, &enc, &codec);
2409  if (hwcodec != kCodec_NONE)
2410  {
2411  // the context may have changed
2412  enc->opaque = static_cast<void*>(this);
2413  m_videoCodecId = hwcodec;
2414  foundgpudecoder = true;
2415  }
2416  else
2417  {
2418  // hardware decoder is not available - try the next best profile
2419  unavailabledecoders.append(dec);
2420  continue;
2421  }
2422  }
2423 
2424  // default to mpeg2
2425  if (m_videoCodecId == kCodec_NONE)
2426  {
2427  LOG(VB_GENERAL, LOG_ERR, LOC + "Unknown video codec - defaulting to MPEG2");
2429  }
2430 
2431  break;
2432  }
2433 
2434  // N.B. MediaCodec and NVDEC require frame timing
2435  m_useFrameTiming = false;
2438  {
2439  m_useFrameTiming = true;
2440  }
2441 
2443  thread_count = 1;
2444 
2445  if (HAVE_THREADS)
2446  {
2447  // All of our callbacks are thread safe. This should improve
2448  // concurrency with software decode
2449  enc->thread_safe_callbacks = 1;
2450 
2451  // Only use a single thread for hardware decoding. There is no
2452  // performance improvement with multithreaded hardware decode
2453  // and asynchronous callbacks create issues with decoders that
2454  // use AVHWFrameContext where we need to release video resources
2455  // before they are recreated
2456  if (!foundgpudecoder)
2457  {
2458  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Using %1 CPUs for decoding")
2459  .arg(HAVE_THREADS ? thread_count : 1));
2460  enc->thread_count = static_cast<int>(thread_count);
2461  }
2462  }
2463 
2464  InitVideoCodec(stream, enc, true);
2465 
2466  ScanATSCCaptionStreams(selTrack);
2468 
2469  LOG(VB_GENERAL, LOG_INFO, LOC + QString("Using %1 for video decoding").arg(GetCodecDecoderName()));
2470  m_mythCodecCtx->SetDecoderOptions(enc, codec);
2471  if (!OpenAVCodec(enc, codec))
2472  {
2473  scanerror = -1;
2474  break;
2475  }
2476  break;
2477  }
2478  }
2479 
2480  if (m_ic && (static_cast<uint>(m_ic->bit_rate) > m_bitrate))
2481  m_bitrate = static_cast<uint>(m_ic->bit_rate);
2482 
2483  if (m_bitrate > 0)
2484  {
2485  m_bitrate = (m_bitrate + 999) / 1000;
2486  if (m_ringBuffer)
2488  }
2489 
2490  // update RingBuffer buffer size
2491  if (m_ringBuffer)
2492  {
2493  m_ringBuffer->SetBufferSizeFactors(unknownbitrate,
2494  m_ic && QString(m_ic->iformat->name).contains("matroska"));
2495  }
2496 
2498 
2499  // Select a new track at the next opportunity.
2500  ResetTracks();
2501 
2502  // We have to do this here to avoid the NVP getting stuck
2503  // waiting on audio.
2504  if (m_audio->HasAudioIn() && m_tracks[kTrackTypeAudio].empty())
2505  {
2506  m_audio->SetAudioParams(FORMAT_NONE, -1, -1, AV_CODEC_ID_NONE, -1, false);
2507  m_audio->ReinitAudio();
2508  if (m_ringBuffer && m_ringBuffer->IsDVD())
2509  m_audioIn = AudioInfo();
2510  }
2511 
2512  // if we don't have a video stream we still need to make sure some
2513  // video params are set properly
2514  if (m_selectedTrack[kTrackTypeVideo].m_av_stream_index == -1)
2515  {
2516  m_fps = 23.97F; // minimum likey display refresh rate
2517  // N.B. we know longer need a 'dummy' frame to render overlays into
2518  m_parent->SetVideoParams(0, 0, 23.97, 1.0F, false, 0);
2519  }
2520 
2521  if (m_parent->IsErrored())
2522  scanerror = -1;
2523 
2524  ScanDSMCCStreams();
2525 
2526  return scanerror;
2527 }
2528 
2529 bool AvFormatDecoder::OpenAVCodec(AVCodecContext *avctx, const AVCodec *codec)
2530 {
2531  m_avCodecLock.lock();
2532 #ifdef USING_MEDIACODEC
2533  if (QString("mediacodec") == codec->wrapper_name)
2534  av_jni_set_java_vm(QAndroidJniEnvironment::javaVM(), nullptr);
2535 #endif
2536  int ret = avcodec_open2(avctx, codec, nullptr);
2537  m_avCodecLock.unlock();
2538  if (ret < 0)
2539  {
2540  std::string error;
2541  LOG(VB_GENERAL, LOG_ERR, LOC +
2542  QString("Could not open codec 0x%1, id(%2) type(%3) "
2543  "ignoring. reason %4").arg((uint64_t)avctx,0,16)
2544  .arg(ff_codec_id_string(avctx->codec_id),
2545  ff_codec_type_string(avctx->codec_type),
2547  return false;
2548  }
2549 
2550  LOG(VB_GENERAL, LOG_INFO, LOC +
2551  QString("Opened codec 0x%1, id(%2) type(%3)")
2552  .arg((uint64_t)avctx,0,16)
2553  .arg(ff_codec_id_string(avctx->codec_id),
2554  ff_codec_type_string(avctx->codec_type)));
2555  return true;
2556 }
2557 
2559 {
2561 }
2562 
2563 bool AvFormatDecoder::DoRewindSeek(long long desiredFrame)
2564 {
2565  return DecoderBase::DoRewindSeek(desiredFrame);
2566 }
2567 
2568 void AvFormatDecoder::DoFastForwardSeek(long long desiredFrame, bool &needflush)
2569 {
2570  DecoderBase::DoFastForwardSeek(desiredFrame, needflush);
2571 }
2572 
2575 {
2576  QMutexLocker locker(&m_trackLock);
2577  for (const auto & si : m_tracks[kTrackTypeTeletextCaptions])
2578  if (si.m_language_index == Index)
2579  return si.m_language;
2580  return iso639_str3_to_key("und");
2581 }
2582 
2584 int AvFormatDecoder::GetSubtitleLanguage(uint /*unused*/, uint StreamIndex)
2585 {
2586  AVDictionaryEntry *metatag = av_dict_get(m_ic->streams[StreamIndex]->metadata, "language", nullptr, 0);
2587  return metatag ? get_canonical_lang(metatag->value) : iso639_str3_to_key("und");
2588 }
2589 
2592 {
2593  // This doesn't strictly need write lock but it is called internally while
2594  // write lock is held. All other (external) uses are safe
2595  QMutexLocker locker(&m_trackLock);
2596 
2597  int ret = -1;
2598  for (int i = 0; i < m_pmtTrackTypes.size(); i++)
2599  {
2600  if ((m_pmtTrackTypes[i] == TrackType) && (m_pmtTracks[i].m_stream_id == ServiceNum))
2601  {
2602  ret = m_pmtTracks[i].m_language;
2603  if (!iso639_is_key_undefined(ret))
2604  return ret;
2605  }
2606  }
2607 
2608  for (int i = 0; i < m_streamTrackTypes.size(); i++)
2609  {
2610  if ((m_streamTrackTypes[i] == TrackType) && (m_streamTracks[i].m_stream_id == ServiceNum))
2611  {
2612  ret = m_streamTracks[i].m_language;
2613  if (!iso639_is_key_undefined(ret))
2614  return ret;
2615  }
2616  }
2617 
2618  return ret;
2619 }
2620 
2621 int AvFormatDecoder::GetAudioLanguage(uint AudioIndex, uint StreamIndex)
2622 {
2623  return GetSubtitleLanguage(AudioIndex, StreamIndex);
2624 }
2625 
2627 {
2629  AVStream *stream = m_ic->streams[StreamIndex];
2630 
2631  if (m_ic->cur_pmt_sect) // mpeg-ts
2632  {
2633  const ProgramMapTable pmt(PSIPTable(m_ic->cur_pmt_sect));
2634  switch (pmt.GetAudioType(StreamIndex))
2635  {
2636  case 0x01 : type = kAudioTypeCleanEffects; break;
2637  case 0x02 : type = kAudioTypeHearingImpaired; break;
2638  case 0x03 : type = kAudioTypeAudioDescription; break;
2639  case 0x00 :
2640  default: type = kAudioTypeNormal;
2641  }
2642  }
2643  else // all other containers
2644  {
2645  // We only support labelling/filtering of these two types for now
2646  if (stream->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2648  else if (stream->disposition & AV_DISPOSITION_COMMENT)
2650  else if (stream->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2652  else if (stream->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2654  }
2655 
2656  return type;
2657 }
2658 
2672 {
2673  QMutexLocker locker(&m_trackLock);
2674 
2675  // Find the position of the streaminfo in m_tracks[kTrackTypeAudio]
2676  auto current = m_tracks[kTrackTypeAudio].begin();
2677  for (; current != m_tracks[kTrackTypeAudio].end(); ++current)
2678  {
2679  if (current->m_av_stream_index == streamIndex)
2680  break;
2681  }
2682 
2683  if (current == m_tracks[kTrackTypeAudio].end())
2684  {
2685  LOG(VB_GENERAL, LOG_WARNING, LOC +
2686  QString("Invalid stream index passed to "
2687  "SetupAudioStreamSubIndexes: %1").arg(streamIndex));
2688 
2689  return;
2690  }
2691 
2692  // Remove the extra substream or duplicate the current substream
2693  auto next = current + 1;
2694  if (current->m_av_substream_index == -1)
2695  {
2696  // Split stream in two (Language I + Language II)
2697  StreamInfo lang1 = *current;
2698  StreamInfo lang2 = *current;
2699  lang1.m_av_substream_index = 0;
2700  lang2.m_av_substream_index = 1;
2701  *current = lang1;
2702  m_tracks[kTrackTypeAudio].insert(next, lang2);
2703  return;
2704  }
2705 
2706  if ((next == m_tracks[kTrackTypeAudio].end()) ||
2707  (next->m_av_stream_index != streamIndex))
2708  {
2709  QString msg = QString(
2710  "Expected substream 1 (Language I) of stream %1\n\t\t\t"
2711  "following substream 0, found end of list or another stream.")
2712  .arg(streamIndex);
2713 
2714  LOG(VB_GENERAL, LOG_WARNING, LOC + msg);
2715 
2716  return;
2717  }
2718 
2719  // Remove extra stream info
2720  StreamInfo stream = *current;
2721  stream.m_av_substream_index = -1;
2722  *current = stream;
2723  m_tracks[kTrackTypeAudio].erase(next);
2724 }
2725 
2731 {
2732  if (!m_audio->HasAudioIn())
2733  return;
2734 
2735  m_avCodecLock.lock();
2736  for (uint i = 0; i < m_ic->nb_streams;)
2737  {
2738  AVStream *st = m_ic->streams[i];
2739  AVCodecContext *avctx = m_codecMap.FindCodecContext(st);
2740  if (avctx && avctx->codec_type == AVMEDIA_TYPE_AUDIO)
2741  {
2743  av_remove_stream(m_ic, st->id, 0);
2744  i--;
2745  }
2746  else
2747  i++;
2748  }
2749  m_avCodecLock.unlock();
2750 }
2751 
2752 int get_avf_buffer(struct AVCodecContext *c, AVFrame *pic, int flags)
2753 {
2754  auto *decoder = static_cast<AvFormatDecoder*>(c->opaque);
2756  if (!std::any_of(decoder->m_renderFormats->cbegin(), decoder->m_renderFormats->cend(),
2757  [&type](auto Format) { return type == Format; }))
2758  {
2759  decoder->m_directRendering = false;
2760  return avcodec_default_get_buffer2(c, pic, flags);
2761  }
2762 
2763  decoder->m_directRendering = true;
2764  MythVideoFrame *frame = decoder->GetPlayer()->GetNextVideoFrame();
2765  if (!frame)
2766  return -1;
2767 
2768  // We pre-allocate frames to certain alignments. If the coded size differs from
2769  // those alignments then re-allocate the frame. Changes in frame type (e.g.
2770  // YV12 to NV12) are always reallocated.
2771  int width = (frame->m_width + MYTH_WIDTH_ALIGNMENT - 1) & ~(MYTH_WIDTH_ALIGNMENT - 1);
2772  int height = (frame->m_height + MYTH_HEIGHT_ALIGNMENT - 1) & ~(MYTH_HEIGHT_ALIGNMENT - 1);
2773 
2774  if ((frame->m_type != type) || (pic->width > width) || (pic->height > height))
2775  {
2776  if (!VideoBuffers::ReinitBuffer(frame, type, decoder->m_videoCodecId, pic->width, pic->height))
2777  return -1;
2778  // NB the video frame may now have a new size which is currenly not an issue
2779  // as the underlying size has already been passed through to the player.
2780  // But may cause issues down the line. We should add coded_width/height to
2781  // VideoFrame as well to ensure consistentency through the rendering
2782  // pipeline.
2783  // NB remember to compare coded width/height - not 'true' values - otherwsie
2784  // we continually re-allocate the frame.
2785  //frame->width = c->width;
2786  //frame->height = c->height;
2787  }
2788 
2789  frame->m_colorshifted = false;
2791  for (uint i = 0; i < 3; i++)
2792  {
2793  pic->data[i] = (i < max) ? (frame->m_buffer + frame->m_offsets[i]) : nullptr;
2794  pic->linesize[i] = frame->m_pitches[i];
2795  }
2796 
2797  pic->opaque = frame;
2798  pic->reordered_opaque = c->reordered_opaque;
2799 
2800  // Set release method
2801  AVBufferRef *buffer = av_buffer_create(reinterpret_cast<uint8_t*>(frame), 0,
2802  [](void* Opaque, uint8_t* Data)
2803  {
2804  auto *avfd = static_cast<AvFormatDecoder*>(Opaque);
2805  auto *vf = reinterpret_cast<MythVideoFrame*>(Data);
2806  if (avfd && avfd->GetPlayer())
2807  avfd->GetPlayer()->DeLimboFrame(vf);
2808  }
2809  , decoder, 0);
2810  pic->buf[0] = buffer;
2811 
2812  return 0;
2813 }
2814 
2815 #ifdef USING_DXVA2
2816 int get_avf_buffer_dxva2(struct AVCodecContext *c, AVFrame *pic, int /*flags*/)
2817 {
2818  AvFormatDecoder *nd = (AvFormatDecoder *)(c->opaque);
2819  VideoFrame *frame = nd->GetPlayer()->GetNextVideoFrame();
2820 
2821  for (int i = 0; i < 4; i++)
2822  {
2823  pic->data[i] = nullptr;
2824  pic->linesize[i] = 0;
2825  }
2826  pic->opaque = frame;
2827  frame->pix_fmt = c->pix_fmt;
2828  pic->reordered_opaque = c->reordered_opaque;
2829  pic->data[0] = (uint8_t*)frame->buf;
2830  pic->data[3] = (uint8_t*)frame->buf;
2831 
2832  // Set release method
2833  AVBufferRef *buffer =
2834  av_buffer_create((uint8_t*)frame, 0, release_avf_buffer, nd, 0);
2835  pic->buf[0] = buffer;
2836 
2837  return 0;
2838 }
2839 #endif
2840 
2841 void AvFormatDecoder::DecodeDTVCC(const uint8_t *buf, uint buf_size, bool scte)
2842 {
2843  if (!buf_size)
2844  return;
2845 
2846  // closed caption data
2847  //cc_data() {
2848  // reserved 1 0.0 1
2849  // process_cc_data_flag 1 0.1 bslbf
2850  bool process_cc_data = (buf[0] & 0x40) != 0;
2851  if (!process_cc_data)
2852  return; // early exit if process_cc_data_flag false
2853 
2854  // additional_data_flag 1 0.2 bslbf
2855  //bool additional_data = buf[0] & 0x20;
2856  // cc_count 5 0.3 uimsbf
2857  uint cc_count = buf[0] & 0x1f;
2858  // em_data 8 1.0
2859 
2860  if (buf_size < 2+(3*cc_count))
2861  return;
2862 
2863  DecodeCCx08(buf+2, cc_count*3, scte);
2864 }
2865 
2866 void AvFormatDecoder::DecodeCCx08(const uint8_t *buf, uint buf_size, bool scte)
2867 {
2868  if (buf_size < 3)
2869  return;
2870 
2871  bool had_608 = false;
2872  bool had_708 = false;
2873  for (uint cur = 0; cur + 2 < buf_size; cur += 3)
2874  {
2875  uint cc_code = buf[cur];
2876  bool cc_valid = (cc_code & 0x04) != 0U;
2877 
2878  uint data1 = buf[cur+1];
2879  uint data2 = buf[cur+2];
2880  uint data = (data2 << 8) | data1;
2881  uint cc_type = cc_code & 0x03;
2882 
2883  if (!cc_valid)
2884  {
2885  if (cc_type >= 0x2)
2887  continue;
2888  }
2889 
2890  if (scte || cc_type <= 0x1) // EIA-608 field-1/2
2891  {
2892  uint field = 0;
2893  if (cc_type == 0x2)
2894  {
2895  // SCTE repeated field
2896  field = (m_lastScteField == 0 ? 1 : 0);
2897  m_invertScteField = (m_invertScteField == 0 ? 1 : 0);
2898  }
2899  else
2900  {
2901  field = cc_type ^ m_invertScteField;
2902  }
2903 
2905  {
2906  // in film mode, we may start at the wrong field;
2907  // correct if XDS start/cont/end code is detected
2908  // (must be field 2)
2909  if (scte && field == 0 &&
2910  (data1 & 0x7f) <= 0x0f && (data1 & 0x7f) != 0x00)
2911  {
2912  if (cc_type == 1)
2913  m_invertScteField = 0;
2914  field = 1;
2915 
2916  // flush decoder
2917  m_ccd608->FormatCC(0ms, -1, -1);
2918  }
2919 
2920  had_608 = true;
2921  m_ccd608->FormatCCField(duration_cast<std::chrono::milliseconds>(m_lastCcPtsu), field, data);
2922 
2923  m_lastScteField = field;
2924  }
2925  }
2926  else
2927  {
2928  had_708 = true;
2929  m_ccd708->decode_cc_data(cc_type, data1, data2);
2930  }
2931  }
2932  UpdateCaptionTracksFromStreams(had_608, had_708);
2933 }
2934 
2936  bool check_608, bool check_708)
2937 {
2938  bool need_change_608 = false;
2939  CC608Seen seen_608;
2940  if (check_608)
2941  {
2942  m_ccd608->GetServices(15s, seen_608);
2943  for (uint i = 0; i < 4; i++)
2944  {
2945  need_change_608 |= (seen_608[i] && !m_ccX08InTracks[i]) ||
2946  (!seen_608[i] && m_ccX08InTracks[i] && !m_ccX08InPmt[i]);
2947  }
2948  }
2949 
2950  bool need_change_708 = false;
2951  cc708_seen_flags seen_708;
2952  if (check_708 || need_change_608)
2953  {
2954  m_ccd708->services(15s, seen_708);
2955  for (uint i = 1; i < 64 && !need_change_608 && !need_change_708; i++)
2956  {
2957  need_change_708 |= (seen_708[i] && !m_ccX08InTracks[i+4]) ||
2958  (!seen_708[i] && m_ccX08InTracks[i+4] && !m_ccX08InPmt[i+4]);
2959  }
2960  if (need_change_708 && !check_608)
2961  m_ccd608->GetServices(15s, seen_608);
2962  }
2963 
2964  if (!need_change_608 && !need_change_708)
2965  return;
2966 
2967  m_trackLock.lock();
2968 
2970 
2971  m_streamTracks.clear();
2972  m_streamTrackTypes.clear();
2973  int av_index = m_selectedTrack[kTrackTypeVideo].m_av_stream_index;
2974  int lang = iso639_str3_to_key("und");
2975  for (uint i = 1; i < 64; i++)
2976  {
2977  if (seen_708[i] && !m_ccX08InPmt[i+4])
2978  {
2979  StreamInfo si(av_index, lang, 0/*lang_idx*/, i, 0, false/*easy*/, true/*wide*/);
2980  m_streamTracks.push_back(si);
2982  }
2983  }
2984  for (uint i = 0; i < 4; i++)
2985  {
2986  if (seen_608[i] && !m_ccX08InPmt[i])
2987  {
2988  if (0==i)
2990  else if (2==i)
2992  else
2993  lang = iso639_str3_to_key("und");
2994 
2995  StreamInfo si(av_index, lang, 0/*lang_idx*/, i+1, 0, false/*easy*/, false/*wide*/);
2996  m_streamTracks.push_back(si);
2998  }
2999  }
3000  m_trackLock.unlock();
3002 }
3003 
3005  AVPacket *pkt, bool can_reliably_parse_keyframes)
3006 {
3007  if (m_prevGopPos != 0 && m_keyframeDist != 1)
3008  {
3009  int tempKeyFrameDist = m_framesRead - 1 - m_prevGopPos;
3010  bool reset_kfd = false;
3011 
3012  if (!m_gopSet || m_livetv) // gopset: we've seen 2 keyframes
3013  {
3014  LOG(VB_PLAYBACK, LOG_INFO, LOC +
3015  "gopset not set, syncing positionMap");
3016  SyncPositionMap();
3017  if (tempKeyFrameDist > 0 && !m_livetv)
3018  {
3019  LOG(VB_PLAYBACK, LOG_INFO, LOC +
3020  QString("Initial key frame distance: %1.")
3021  .arg(m_keyframeDist));
3022  m_gopSet = true;
3023  reset_kfd = true;
3024  }
3025  }
3026  else if (m_keyframeDist != tempKeyFrameDist && tempKeyFrameDist > 0)
3027  {
3028  LOG(VB_PLAYBACK, LOG_INFO, LOC +
3029  QString("Key frame distance changed from %1 to %2.")
3030  .arg(m_keyframeDist).arg(tempKeyFrameDist));
3031  reset_kfd = true;
3032  }
3033 
3034  if (reset_kfd)
3035  {
3036  m_keyframeDist = tempKeyFrameDist;
3038 
3040 
3041 #if 0
3042  // also reset length
3043  QMutexLocker locker(&m_positionMapLock);
3044  if (!m_positionMap.empty())
3045  {
3046  long long index = m_positionMap.back().index;
3047  long long totframes = index * m_keyframeDist;
3048  uint length = (uint)((totframes * 1.0F) / m_fps);
3049  m_parent->SetFileLength(length, totframes);
3050  }
3051 #endif
3052  }
3053  }
3054 
3056 
3057  if (can_reliably_parse_keyframes &&
3059  {
3060  long long last_frame = 0;
3061  {
3062  QMutexLocker locker(&m_positionMapLock);
3063  if (!m_positionMap.empty())
3064  last_frame = m_positionMap.back().index;
3065  }
3066 
3067 #if 0
3068  LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
3069  QString("framesRead: %1 last_frame: %2 keyframedist: %3")
3070  .arg(m_framesRead) .arg(last_frame) .arg(m_keyframeDist));
3071 #endif
3072 
3073  // if we don't have an entry, fill it in with what we've just parsed
3074  if (m_framesRead > last_frame && m_keyframeDist > 0)
3075  {
3076  long long startpos = pkt->pos;
3077 
3078  LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
3079  QString("positionMap[ %1 ] == %2.")
3080  .arg(m_framesRead).arg(startpos));
3081 
3082  PosMapEntry entry = {m_framesRead, m_framesRead, startpos};
3083 
3084  QMutexLocker locker(&m_positionMapLock);
3085  // Create a dummy positionmap entry for frame 0 so that
3086  // seeking will work properly. (See
3087  // DecoderBase::FindPosition() which subtracts
3088  // DecoderBase::indexOffset from each frame number.)
3089  if (m_positionMap.empty())
3090  {
3091  PosMapEntry dur = {0, 0, 0};
3092  m_positionMap.push_back(dur);
3093  }
3094  m_positionMap.push_back(entry);
3096  {
3098  llround(m_totalDuration.num * 1000.0 / m_totalDuration.den);
3100  }
3101  }
3102 
3103 #if 0
3104  // If we are > 150 frames in and saw no positionmap at all, reset
3105  // length based on the actual bitrate seen so far
3107  {
3108  m_bitrate = (int)((pkt->pos * 8 * m_fps) / (m_framesRead - 1));
3109  float bytespersec = (float)m_bitrate / 8;
3110  float secs = m_ringBuffer->GetRealFileSize() * 1.0F / bytespersec;
3111  m_parent->SetFileLength((int)(secs), (int)(secs * m_fps));
3112  }
3113 #endif
3114  }
3115 }
3116 
3117 #define SEQ_START 0x000001b3
3118 #define GOP_START 0x000001b8
3119 #define PICTURE_START 0x00000100
3120 #define SLICE_MIN 0x00000101
3121 #define SLICE_MAX 0x000001af
3122 #define SEQ_END_CODE 0x000001b7
3123 
3124 void AvFormatDecoder::MpegPreProcessPkt(AVStream *stream, AVPacket *pkt)
3125 {
3126  AVCodecContext *context = m_codecMap.GetCodecContext(stream);
3127  const uint8_t *bufptr = pkt->data;
3128  const uint8_t *bufend = pkt->data + pkt->size;
3129 
3130  while (bufptr < bufend)
3131  {
3132  bufptr = avpriv_find_start_code(bufptr, bufend, &m_startCodeState);
3133 
3134  float aspect_override = -1.0F;
3135  if (m_ringBuffer->IsDVD())
3136  aspect_override = m_ringBuffer->DVD()->GetAspectOverride();
3137 
3139  continue;
3140 
3141  if (SEQ_START == m_startCodeState)
3142  {
3143  if (bufptr + 11 >= pkt->data + pkt->size)
3144  continue; // not enough valid data...
3145  const auto *seq = reinterpret_cast<const SequenceHeader*>(bufptr);
3146 
3147  int width = static_cast<int>(seq->width()) >> context->lowres;
3148  int height = static_cast<int>(seq->height()) >> context->lowres;
3149  float aspect = seq->aspect(context->codec_id == AV_CODEC_ID_MPEG1VIDEO);
3150  if (stream->sample_aspect_ratio.num)
3151  aspect = static_cast<float>(av_q2d(stream->sample_aspect_ratio) * width / height);
3152  if (aspect_override > 0.0F)
3153  aspect = aspect_override;
3154  float seqFPS = seq->fps();
3155 
3156  bool changed = (width != m_currentWidth );
3157  changed |= (height != m_currentHeight);
3158  changed |= (seqFPS > static_cast<float>(m_fps)+0.01F) ||
3159  (seqFPS < static_cast<float>(m_fps)-0.01F);
3160 
3161  // some hardware decoders (e.g. VAAPI MPEG2) will reset when the aspect
3162  // ratio changes
3163  bool forceaspectchange = !qFuzzyCompare(m_currentAspect + 10.0F, aspect + 10.0F) &&
3165  m_currentAspect = aspect;
3166 
3167  if (changed || forceaspectchange)
3168  {
3169  // N.B. We now set the default scan to kScan_Ignore as interlaced detection based on frame
3170  // size and rate is extremely error prone and FFmpeg gets it right far more often.
3171  // As for H.264, if a decoder deinterlacer is in operation - the stream must be progressive
3172  bool doublerate = false;
3173  bool decoderdeint = m_mythCodecCtx && m_mythCodecCtx->IsDeinterlacing(doublerate, true);
3174  m_parent->SetVideoParams(width, height, static_cast<double>(seqFPS), m_currentAspect,
3175  forceaspectchange, 2,
3176  decoderdeint ? kScan_Progressive : kScan_Ignore);
3177 
3178  if (context->hw_frames_ctx)
3179  if (context->internal)
3180  avcodec_flush_buffers(context);
3181 
3182  m_currentWidth = width;
3183  m_currentHeight = height;
3184  m_fps = seqFPS;
3185 
3186  m_gopSet = false;
3187  m_prevGopPos = 0;
3188  m_firstVPts = m_lastAPts = m_lastVPts = 0ms;
3189  m_lastCcPtsu = 0us;
3190  m_firstVPtsInuse = true;
3191  m_faultyPts = m_faultyDts = 0;
3194  m_ptsDetected = false;
3195  m_reorderedPtsDetected = false;
3196 
3197  // fps debugging info
3198  float avFPS = GetVideoFrameRate(stream, context);
3199  if ((seqFPS > avFPS+0.01F) || (seqFPS < avFPS-0.01F))
3200  {
3201  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("avFPS(%1) != seqFPS(%2)")
3202  .arg(static_cast<double>(avFPS)).arg(static_cast<double>(seqFPS)));
3203  }
3204  }
3205 
3206  m_seqCount++;
3207 
3208  if (!m_seenGop && m_seqCount > 1)
3209  {
3210  HandleGopStart(pkt, true);
3211  pkt->flags |= AV_PKT_FLAG_KEY;
3212  }
3213  }
3214  else if (GOP_START == m_startCodeState)
3215  {
3216  HandleGopStart(pkt, true);
3217  m_seenGop = true;
3218  pkt->flags |= AV_PKT_FLAG_KEY;
3219  }
3220  }
3221 }
3222 
3223 // Returns the number of frame starts identified in the packet.
3224 int AvFormatDecoder::H264PreProcessPkt(AVStream *stream, AVPacket *pkt)
3225 {
3226  AVCodecContext *context = m_codecMap.GetCodecContext(stream);
3227  const uint8_t *buf = pkt->data;
3228  const uint8_t *buf_end = pkt->data + pkt->size;
3229  int num_frames = 0;
3230 
3231  // The parser only understands Annex B/bytestream format - so check for avCC
3232  // format (starts with 0x01) and rely on FFmpeg keyframe detection
3233  if (context->extradata && (context->extradata_size >= 7) && (context->extradata[0] == 0x01))
3234  {
3235  if (pkt->flags & AV_PKT_FLAG_KEY)
3236  HandleGopStart(pkt, false);
3237  return 1;
3238  }
3239 
3240  while (buf < buf_end)
3241  {
3242  buf += m_avcParser->addBytes(buf, static_cast<unsigned int>(buf_end - buf), 0);
3243 
3244  if (m_avcParser->stateChanged())
3245  {
3247  {
3248  if (m_avcParser->onFrameStart())
3249  ++num_frames;
3250 
3251  if (!m_avcParser->onKeyFrameStart())
3252  continue;
3253  }
3254  else
3255  {
3256  continue;
3257  }
3258  }
3259  else
3260  {
3261  continue;
3262  }
3263 
3265  float aspect = get_aspect(*m_avcParser);
3266  int width = static_cast<int>(m_avcParser->pictureWidthCropped());
3267  int height = static_cast<int>(m_avcParser->pictureHeightCropped());
3268  double seqFPS = m_avcParser->frameRate();
3269 
3270  bool res_changed = ((width != m_currentWidth) || (height != m_currentHeight));
3271  bool fps_changed = (seqFPS > 0.0) && ((seqFPS > static_cast<double>(m_fps) + 0.01) ||
3272  (seqFPS < static_cast<double>(m_fps) - 0.01));
3273  bool forcechange = !qFuzzyCompare(aspect + 10.0F, m_currentAspect) &&
3275  m_currentAspect = aspect;
3276 
3277  if (fps_changed || res_changed || forcechange)
3278  {
3279  // N.B. we now set the default scan to kScan_Ignore as interlaced detection based on frame
3280  // size and rate is extremely error prone and FFmpeg gets it right far more often.
3281  // N.B. if a decoder deinterlacer is in use - the stream must be progressive
3282  bool doublerate = false;
3283  bool decoderdeint = m_mythCodecCtx ? m_mythCodecCtx->IsDeinterlacing(doublerate, true) : false;
3284  m_parent->SetVideoParams(width, height, seqFPS, m_currentAspect, forcechange,
3285  static_cast<int>(m_avcParser->getRefFrames()),
3286  decoderdeint ? kScan_Progressive : kScan_Ignore);
3287 
3288  // the SetVideoParams call above will have released all held frames
3289  // when using a hardware frames context - but for H264 (as opposed to mpeg2)
3290  // the codec will still hold references for reference frames (decoded picture buffer).
3291  // Flushing the context will release these references and the old
3292  // hardware context is released correctly before a new one is created.
3293  // TODO check what is needed here when a device context is used
3294  // TODO check whether any codecs need to be flushed for a frame rate change (e.g. mediacodec?)
3295  if (context->hw_frames_ctx && (forcechange || res_changed))
3296  if (context->internal)
3297  avcodec_flush_buffers(context);
3298 
3299  m_currentWidth = width;
3300  m_currentHeight = height;
3301 
3302  if (seqFPS > 0.0)
3303  m_fps = static_cast<float>(seqFPS);
3304 
3305  m_gopSet = false;
3306  m_prevGopPos = 0;
3307  m_firstVPts = m_lastAPts = m_lastVPts = 0ms;
3308  m_lastCcPtsu = 0us;
3309  m_firstVPtsInuse = true;
3310  m_faultyPts = m_faultyDts = 0;
3313  m_ptsDetected = false;
3314  m_reorderedPtsDetected = false;
3315 
3316  // fps debugging info
3317  auto avFPS = static_cast<double>(GetVideoFrameRate(stream, context));
3318  if ((seqFPS > avFPS + 0.01) || (seqFPS < avFPS - 0.01))
3319  {
3320  LOG(VB_PLAYBACK, LOG_INFO, LOC +
3321  QString("avFPS(%1) != seqFPS(%2)").arg(avFPS).arg(seqFPS));
3322  }
3323  }
3324 
3325  HandleGopStart(pkt, true);
3326  pkt->flags |= AV_PKT_FLAG_KEY;
3327  }
3328 
3329  return num_frames;
3330 }
3331 
3332 bool AvFormatDecoder::PreProcessVideoPacket(AVStream *curstream, AVPacket *pkt)
3333 {
3334  AVCodecContext *context = m_codecMap.GetCodecContext(curstream);
3335  int num_frames = 1;
3336 
3337  if (CODEC_IS_FFMPEG_MPEG(context->codec_id))
3338  {
3339  MpegPreProcessPkt(curstream, pkt);
3340  }
3341  else if (CODEC_IS_H264(context->codec_id))
3342  {
3343  num_frames = H264PreProcessPkt(curstream, pkt);
3344  }
3345  else
3346  {
3347  if (pkt->flags & AV_PKT_FLAG_KEY)
3348  {
3349  HandleGopStart(pkt, false);
3350  m_seenGop = true;
3351  }
3352  else
3353  {
3354  m_seqCount++;
3355  if (!m_seenGop && m_seqCount > 1)
3356  {
3357  HandleGopStart(pkt, false);
3358  }
3359  }
3360  }
3361 
3362  if (m_framesRead == 0 && !m_justAfterChange &&
3363  !(pkt->flags & AV_PKT_FLAG_KEY))
3364  {
3365  av_packet_unref(pkt);
3366  return false;
3367  }
3368 
3369  m_framesRead += num_frames;
3370 
3372  {
3373  // The ffmpeg libraries represent a frame interval of a
3374  // 59.94fps video as 1501/90000 seconds, when it should
3375  // actually be 1501.5/90000 seconds.
3376  AVRational pkt_dur = AVRationalInit(pkt->duration);
3377  pkt_dur = av_mul_q(pkt_dur, curstream->time_base);
3378  if (pkt_dur.num == 1501 && pkt_dur.den == 90000)
3379  pkt_dur = AVRationalInit(1001, 60000); // 1501.5/90000
3380  m_totalDuration = av_add_q(m_totalDuration, pkt_dur);
3381  }
3382 
3383  m_justAfterChange = false;
3384 
3385  if (m_exitAfterDecoded)
3386  m_gotVideoFrame = true;
3387 
3388  return true;
3389 }
3390 
3391 bool AvFormatDecoder::ProcessVideoPacket(AVStream *curstream, AVPacket *pkt, bool &Retry)
3392 {
3393  int ret = 0;
3394  int gotpicture = 0;
3395  AVCodecContext *context = m_codecMap.GetCodecContext(curstream);
3396  MythAVFrame mpa_pic;
3397  if (!mpa_pic)
3398  return false;
3399  mpa_pic->reordered_opaque = AV_NOPTS_VALUE;
3400 
3401  if (pkt->pts != AV_NOPTS_VALUE)
3402  m_ptsDetected = true;
3403 
3404  bool sentPacket = false;
3405  int ret2 = 0;
3406 
3407  m_avCodecLock.lock();
3408  if (!m_useFrameTiming)
3409  context->reordered_opaque = pkt->pts;
3410 
3411  // SUGGESTION
3412  // Now that avcodec_decode_video2 is deprecated and replaced
3413  // by 2 calls (receive frame and send packet), this could be optimized
3414  // into separate routines or separate threads.
3415  // Also now that it always consumes a whole buffer some code
3416  // in the caller may be able to be optimized.
3417 
3418  // FilteredReceiveFrame will call avcodec_receive_frame and
3419  // apply any codec-dependent filtering
3420  ret = m_mythCodecCtx->FilteredReceiveFrame(context, mpa_pic);
3421 
3422  if (ret == 0)
3423  gotpicture = 1;
3424  else
3425  gotpicture = 0;
3426  if (ret == AVERROR(EAGAIN))
3427  ret = 0;
3428  // If we got a picture do not send the packet until we have
3429  // all available pictures
3430  if (ret==0 && !gotpicture)
3431  {
3432  ret2 = avcodec_send_packet(context, pkt);
3433  if (ret2 == AVERROR(EAGAIN))
3434  {
3435  Retry = true;
3436  ret2 = 0;
3437  }
3438  else
3439  {
3440  sentPacket = true;
3441  }
3442  }
3443  m_avCodecLock.unlock();
3444 
3445  if (ret < 0 || ret2 < 0)
3446  {
3447  std::string error;
3448  if (ret < 0)
3449  {
3450  LOG(VB_GENERAL, LOG_ERR, LOC +
3451  QString("video avcodec_receive_frame error: %1 (%2) gotpicture:%3")
3452  .arg(av_make_error_stdstring(error, ret))
3453  .arg(ret).arg(gotpicture));
3454  }
3455 
3456  if (ret2 < 0)
3457  {
3458  LOG(VB_GENERAL, LOG_ERR, LOC +
3459  QString("video avcodec_send_packet error: %1 (%2) gotpicture:%3")
3460  .arg(av_make_error_stdstring(error, ret2))
3461  .arg(ret2).arg(gotpicture));
3462  }
3463 
3465  {
3466  // If erroring on GPU assist, try switching to software decode
3468  m_parent->SetErrored(QObject::tr("Video Decode Error"));
3469  else
3470  m_streamsChanged = true;
3471  }
3472 
3473  if (m_mythCodecCtx->DecoderNeedsReset(context))
3474  {
3475  LOG(VB_GENERAL, LOG_INFO, LOC + "Decoder needs reset");
3477  }
3478 
3479  if (ret == AVERROR_EXTERNAL || ret2 == AVERROR_EXTERNAL)
3480  {
3481  LOG(VB_PLAYBACK, LOG_INFO, LOC + "FFmpeg external library error - assuming streams changed");
3482  m_streamsChanged = true;
3483  }
3484 
3485  return false;
3486  }
3487 
3488  // averror_count counts sequential errors, so if you have a successful
3489  // packet then reset it
3490  m_averrorCount = 0;
3491  if (gotpicture)
3492  {
3493  LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
3494  QString("video timecodes packet-pts:%1 frame-pts:%2 packet-dts: %3 frame-dts:%4")
3495  .arg(pkt->pts).arg(mpa_pic->pts).arg(pkt->pts)
3496  .arg(mpa_pic->pkt_dts));
3497 
3498  if (!m_useFrameTiming)
3499  {
3500  int64_t pts = 0;
3501 
3502  // Detect faulty video timestamps using logic from ffplay.
3503  if (pkt->dts != AV_NOPTS_VALUE)
3504  {
3505  if (pkt->dts <= m_lastDtsForFaultDetection)
3506  m_faultyDts += 1;
3507  m_lastDtsForFaultDetection = pkt->dts;
3508  }
3509  if (mpa_pic->reordered_opaque != AV_NOPTS_VALUE)
3510  {
3511  if (mpa_pic->reordered_opaque <= m_lastPtsForFaultDetection)
3512  m_faultyPts += 1;
3513  m_lastPtsForFaultDetection = mpa_pic->reordered_opaque;
3514  m_reorderedPtsDetected = true;
3515  }
3516 
3517  // Explicity use DTS for DVD since they should always be valid for every
3518  // frame and fixups aren't enabled for DVD.
3519  // Select reordered_opaque (PTS) timestamps if they are less faulty or the
3520  // the DTS timestamp is missing. Also use fixups for missing PTS instead of
3521  // DTS to avoid oscillating between PTS and DTS. Only select DTS if PTS is
3522  // more faulty or never detected.
3524  {
3525  if (pkt->dts != AV_NOPTS_VALUE)
3526  pts = pkt->dts;
3527  m_ptsSelected = false;
3528  }
3530  {
3531  if (mpa_pic->reordered_opaque != AV_NOPTS_VALUE)
3532  pts = mpa_pic->reordered_opaque;
3533  m_ptsSelected = true;
3534  }
3535  else if (pkt->dts != AV_NOPTS_VALUE)
3536  {
3537  pts = pkt->dts;
3538  m_ptsSelected = false;
3539  }
3540 
3541  LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_DEBUG, LOC +
3542  QString("video packet timestamps reordered %1 pts %2 dts %3 (%4)")
3543  .arg(mpa_pic->reordered_opaque).arg(pkt->pts).arg(pkt->dts)
3544  .arg((m_forceDtsTimestamps) ? "dts forced" :
3545  (m_ptsSelected) ? "reordered" : "dts"));
3546 
3547  mpa_pic->reordered_opaque = pts;
3548  }
3549  ProcessVideoFrame(curstream, mpa_pic);
3550  }
3551 
3552  if (!sentPacket)
3553  {
3554  // MythTV logic expects that only one frame is processed
3555  // Save the packet for later and return.
3556  auto *newPkt = new AVPacket;
3557  memset(newPkt, 0, sizeof(AVPacket));
3558  av_init_packet(newPkt);
3559  av_packet_ref(newPkt, pkt);
3560  m_storedPackets.prepend(newPkt);
3561  }
3562  return true;
3563 }
3564 
3565 bool AvFormatDecoder::ProcessVideoFrame(AVStream *Stream, AVFrame *AvFrame)
3566 {
3567 
3568  auto * context = m_codecMap.GetCodecContext(Stream);
3569 
3570  // We need to mediate between ATSC and SCTE data when both are present. If
3571  // both are present, we generally want to prefer ATSC. However, there may
3572  // be large sections of the recording where ATSC is used and other sections
3573  // where SCTE is used. In that case, we want to allow a natural transition
3574  // from ATSC back to SCTE. We do this by allowing 10 consecutive SCTE
3575  // frames, without an intervening ATSC frame, to cause a switch back to
3576  // considering SCTE frames. The number 10 is somewhat arbitrarily chosen.
3577 
3578  uint cc_len = static_cast<uint>(std::max(AvFrame->scte_cc_len,0));
3579  uint8_t *cc_buf = AvFrame->scte_cc_buf;
3580  bool scte = true;
3581 
3582  // If we saw SCTE, then decrement a nonzero ignore_scte count.
3583  if (cc_len > 0 && m_ignoreScte)
3584  --m_ignoreScte;
3585 
3586  // If both ATSC and SCTE caption data are available, prefer ATSC
3587  if ((AvFrame->atsc_cc_len > 0) || m_ignoreScte)
3588  {
3589  cc_len = static_cast<uint>(std::max(AvFrame->atsc_cc_len, 0));
3590  cc_buf = AvFrame->atsc_cc_buf;
3591  scte = false;
3592  // If we explicitly saw ATSC, then reset ignore_scte count.
3593  if (cc_len > 0)
3594  m_ignoreScte = 10;
3595  }
3596 
3597  // Decode CEA-608 and CEA-708 captions
3598  for (uint i = 0; i < cc_len; i += ((cc_buf[i] & 0x1f) * 3) + 2)
3599  DecodeDTVCC(cc_buf + i, cc_len - i, scte);
3600 
3601  // look for A53 captions
3602  if (cc_len == 0)
3603  {
3604  auto * side_data = av_frame_get_side_data(AvFrame, AV_FRAME_DATA_A53_CC);
3605  if (side_data && (side_data->size > 0))
3606  DecodeCCx08(side_data->data, static_cast<uint>(side_data->size), false);
3607  }
3608 
3609  auto * frame = static_cast<MythVideoFrame*>(AvFrame->opaque);
3610  if (frame)
3612 
3614  {
3615  // Do nothing, we just want the pts, captions, subtites, etc.
3616  // So we can release the unconverted blank video frame to the
3617  // display queue.
3618  if (frame)
3619  frame->m_directRendering = false;
3620  }
3621  else if (!m_directRendering)
3622  {
3623  MythVideoFrame *oldframe = frame;
3624  frame = m_parent->GetNextVideoFrame();
3625  frame->m_directRendering = false;
3626 
3627  if (!m_mythCodecCtx->RetrieveFrame(context, frame, AvFrame))
3628  {
3629  AVFrame tmppicture;
3630  av_image_fill_arrays(tmppicture.data, tmppicture.linesize,
3631  frame->m_buffer, AV_PIX_FMT_YUV420P, AvFrame->width,
3632  AvFrame->height, IMAGE_ALIGN);
3633  tmppicture.data[0] = frame->m_buffer + frame->m_offsets[0];
3634  tmppicture.data[1] = frame->m_buffer + frame->m_offsets[1];
3635  tmppicture.data[2] = frame->m_buffer + frame->m_offsets[2];
3636  tmppicture.linesize[0] = frame->m_pitches[0];
3637  tmppicture.linesize[1] = frame->m_pitches[1];
3638  tmppicture.linesize[2] = frame->m_pitches[2];
3639 
3640  QSize dim = get_video_dim(*context);
3641  m_swsCtx = sws_getCachedContext(m_swsCtx, AvFrame->width,
3642  AvFrame->height, static_cast<AVPixelFormat>(AvFrame->format),
3643  AvFrame->width, AvFrame->height,
3644  AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR,
3645  nullptr, nullptr, nullptr);
3646  if (!m_swsCtx)
3647  {
3648  LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to allocate sws context");
3649  return false;
3650  }
3651  sws_scale(m_swsCtx, AvFrame->data, AvFrame->linesize, 0, dim.height(),
3652  tmppicture.data, tmppicture.linesize);
3653  }
3654 
3655  // Discard any old VideoFrames
3656  if (oldframe)
3657  {
3658  // Set the frame flags, but then discard it
3659  // since we are not using it for display.
3660  oldframe->m_interlaced = AvFrame->interlaced_frame;
3661  oldframe->m_topFieldFirst = AvFrame->top_field_first != 0;
3662  oldframe->m_colorspace = AvFrame->colorspace;
3663  oldframe->m_colorrange = AvFrame->color_range;
3664  oldframe->m_colorprimaries = AvFrame->color_primaries;
3665  oldframe->m_colortransfer = AvFrame->color_trc;
3666  oldframe->m_chromalocation = AvFrame->chroma_location;
3667  oldframe->m_frameNumber = m_framesPlayed;
3668  oldframe->m_frameCounter = m_frameCounter++;
3669  oldframe->m_aspect = m_currentAspect;
3670  oldframe->m_rotation = m_videoRotation;
3671  oldframe->m_stereo3D = m_stereo3D;
3672 
3673  oldframe->m_dummy = false;
3674  oldframe->m_pauseFrame = false;
3675  oldframe->m_interlacedReverse = false;
3676  oldframe->m_newGOP = false;
3677  oldframe->m_deinterlaceInuse = DEINT_NONE;
3678  oldframe->m_deinterlaceInuse2x = false;
3679  oldframe->m_alreadyDeinterlaced = false;
3680 
3681  m_parent->DiscardVideoFrame(oldframe);
3682  }
3683  }
3684 
3685  if (!frame)
3686  {
3687  LOG(VB_GENERAL, LOG_ERR, LOC + "NULL videoframe - direct rendering not "
3688  "correctly initialized.");
3689  return false;
3690  }
3691 
3692  std::chrono::milliseconds pts = 0ms;
3693  if (m_useFrameTiming)
3694  {
3695  long long av_pts = AvFrame->pts;
3696  if (av_pts == AV_NOPTS_VALUE)
3697  av_pts = AvFrame->pkt_dts;
3698  if (av_pts == AV_NOPTS_VALUE)
3699  av_pts = AvFrame->reordered_opaque;
3700  if (av_pts == AV_NOPTS_VALUE)
3701  {
3702  LOG(VB_GENERAL, LOG_ERR, LOC + "No PTS found - unable to process video.");
3703  return false;
3704  }
3705  pts = millisecondsFromFloat(av_q2d(Stream->time_base) * av_pts * 1000);
3706  }
3707  else
3708  pts = millisecondsFromFloat(av_q2d(Stream->time_base) * AvFrame->reordered_opaque * 1000);
3709 
3710  std::chrono::milliseconds temppts = pts;
3711  // Validate the video pts against the last pts. If it's
3712  // a little bit smaller, equal or missing, compute
3713  // it from the last. Otherwise assume a wraparound.
3714  if (!m_ringBuffer->IsDVD() &&
3715  temppts <= m_lastVPts &&
3716  (temppts + millisecondsFromFloat(1000 / m_fps) > m_lastVPts ||
3717  temppts <= 0ms))
3718  {
3719  temppts = m_lastVPts;
3720  temppts += millisecondsFromFloat(1000 / m_fps);
3721  // MPEG2/H264 frames can be repeated, update pts accordingly
3722  temppts += millisecondsFromFloat(AvFrame->repeat_pict * 500 / m_fps);
3723  }
3724 
3725  // Calculate actual fps from the pts values.
3726  std::chrono::milliseconds ptsdiff = temppts - m_lastVPts;
3727  double calcfps = 1000.0 / ptsdiff.count();
3728  if (calcfps < 121.0 && calcfps > 3.0)
3729  {
3730  // If fps has doubled due to frame-doubling deinterlace
3731  // Set fps to double value.
3732  double fpschange = calcfps / static_cast<double>(m_fps);
3733  int prior = m_fpsMultiplier;
3734  if (fpschange > 1.9 && fpschange < 2.1)
3735  m_fpsMultiplier = 2;
3736  if (fpschange > 0.9 && fpschange < 1.1)
3737  m_fpsMultiplier = 1;
3738  if (m_fpsMultiplier != prior)
3739  m_parent->SetFrameRate(static_cast<double>(m_fps));
3740  }
3741 
3742  LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
3743  QString("video timecode %1 %2 %3 %4%5")
3744  .arg(m_useFrameTiming ? AvFrame->pts : AvFrame->reordered_opaque)
3745  .arg(pts.count()).arg(temppts.count()).arg(m_lastVPts.count())
3746  .arg((pts != temppts) ? " fixup" : ""));
3747 
3748  frame->m_interlaced = AvFrame->interlaced_frame;
3749  frame->m_topFieldFirst = AvFrame->top_field_first != 0;
3750  frame->m_newGOP = m_nextDecodedFrameIsKeyFrame;
3751  frame->m_repeatPic = AvFrame->repeat_pict != 0;
3752  frame->m_displayTimecode = NormalizeVideoTimecode(Stream, std::chrono::milliseconds(temppts));
3753  frame->m_frameNumber = m_framesPlayed;
3754  frame->m_frameCounter = m_frameCounter++;
3755  frame->m_aspect = m_currentAspect;
3756  frame->m_colorspace = AvFrame->colorspace;
3757  frame->m_colorrange = AvFrame->color_range;
3758  frame->m_colorprimaries = AvFrame->color_primaries;
3759  frame->m_colortransfer = AvFrame->color_trc;
3760  frame->m_chromalocation = AvFrame->chroma_location;
3761  frame->m_pixFmt = AvFrame->format;
3762  frame->m_deinterlaceInuse = DEINT_NONE;
3763  frame->m_rotation = m_videoRotation;
3764  frame->m_stereo3D = m_stereo3D;
3765 
3766  frame->m_dummy = false;
3767  frame->m_pauseFrame = false;
3768  frame->m_deinterlaceInuse2x = false;
3769  frame->m_alreadyDeinterlaced = false;
3770  frame->m_interlacedReverse = false;
3771 
3772  // Retrieve HDR metadata
3773  MythHDRVideoMetadata::Populate(frame, AvFrame);
3774 
3775  m_parent->ReleaseNextVideoFrame(frame, std::chrono::milliseconds(temppts));
3776  m_mythCodecCtx->PostProcessFrame(context, frame);
3777 
3779  m_decodedVideoFrame = frame;
3780  m_gotVideoFrame = true;
3781  if (++m_fpsSkip >= m_fpsMultiplier)
3782  {
3783  ++m_framesPlayed;
3784  m_fpsSkip = 0;
3785  }
3786 
3787  m_lastVPts = temppts;
3788  if ((m_firstVPts == 0ms) && m_firstVPtsInuse)
3789  m_firstVPts = temppts;
3790 
3791  return true;
3792 }
3793 
3800  const AVStream *stream, const AVPacket *pkt)
3801 {
3802  (void) stream;
3803 
3804  const uint8_t *buf = pkt->data;
3805  uint64_t linemask = 0;
3806  std::chrono::microseconds utc = m_lastCcPtsu;
3807 
3808  // [i]tv0 means there is a linemask
3809  // [I]TV0 means there is no linemask and all lines are present
3810  if ((buf[0]=='t') && (buf[1]=='v') && (buf[2] == '0'))
3811  {
3813  memcpy(&linemask, buf + 3, 8);
3814  buf += 11;
3815  }
3816  else if ((buf[0]=='T') && (buf[1]=='V') && (buf[2] == '0'))
3817  {
3818  linemask = 0xffffffffffffffffLL;
3819  buf += 3;
3820  }
3821  else
3822  {
3823  LOG(VB_VBI, LOG_ERR, LOC + QString("Unknown VBI data stream '%1%2%3'")
3824  .arg(QChar(buf[0])).arg(QChar(buf[1])).arg(QChar(buf[2])));
3825  return;
3826  }
3827 
3828  static constexpr uint kMinBlank = 6;
3829  for (uint i = 0; i < 36; i++)
3830  {
3831  if (!((linemask >> i) & 0x1))
3832  continue;
3833 
3834  const uint line = ((i < 18) ? i : i-18) + kMinBlank;
3835  const uint field = (i<18) ? 0 : 1;
3836  const uint id2 = *buf & 0xf;
3837  switch (id2)
3838  {
3839  case VBI_TYPE_TELETEXT:
3840  // SECAM lines 6-23
3841  // PAL lines 6-22
3842  // NTSC lines 10-21 (rare)
3843  m_trackLock.lock();
3844  if (m_tracks[kTrackTypeTeletextMenu].empty())
3845  {
3846  StreamInfo si(pkt->stream_index, 0, 0, 0, 0);
3847  m_trackLock.lock();
3848  m_tracks[kTrackTypeTeletextMenu].push_back(si);
3849  m_trackLock.unlock();
3850  }
3851  m_trackLock.unlock();
3852  m_ttd->Decode(buf+1, VBI_IVTV);
3853  break;
3854  case VBI_TYPE_CC:
3855  // PAL line 22 (rare)
3856  // NTSC line 21
3857  if (21 == line)
3858  {
3859  int data = (buf[2] << 8) | buf[1];
3861  m_ccd608->FormatCCField(duration_cast<std::chrono::milliseconds>(utc), field, data);
3862  utc += 33367us;
3863  }
3864  break;
3865  case VBI_TYPE_VPS: // Video Programming System
3866  // PAL line 16
3867  m_ccd608->DecodeVPS(buf+1); // a.k.a. PDC
3868  break;
3869  case VBI_TYPE_WSS: // Wide Screen Signal
3870  // PAL line 23
3871  // NTSC line 20
3872  m_ccd608->DecodeWSS(buf+1);
3873  break;
3874  }
3875  buf += 43;
3876  }
3877  m_lastCcPtsu = utc;
3878  UpdateCaptionTracksFromStreams(true, false);
3879 }
3880 
3886  const AVStream* /*stream*/, const AVPacket *pkt)
3887 {
3888  const uint8_t *buf = pkt->data;
3889  const uint8_t *buf_end = pkt->data + pkt->size;
3890 
3891 
3892  while (buf < buf_end)
3893  {
3894  if (*buf == 0x10)
3895  {
3896  buf++; // skip
3897  }
3898  else if (*buf == 0x02)
3899  {
3900  buf += 4;
3901  if ((buf_end - buf) >= 42)
3902  m_ttd->Decode(buf, VBI_DVB);
3903  buf += 42;
3904  }
3905  else if (*buf == 0x03)
3906  {
3907  buf += 4;
3908  if ((buf_end - buf) >= 42)
3909  m_ttd->Decode(buf, VBI_DVB_SUBTITLE);
3910  buf += 42;
3911  }
3912  else if (*buf == 0xff)
3913  {
3914  buf += 3;
3915  }
3916  else
3917  {
3918  LOG(VB_VBI, LOG_ERR, LOC +
3919  QString("VBI: Unknown descriptor: %1").arg(*buf));
3920  buf += 46;
3921  }
3922  }
3923 }
3924 
3928 void AvFormatDecoder::ProcessDSMCCPacket(const AVStream *str, const AVPacket *pkt)
3929 {
3930 #ifdef USING_MHEG
3931  if (!m_itv && ! (m_itv = m_parent->GetInteractiveTV()))
3932  return;
3933 
3934  // The packet may contain several tables.
3935  uint8_t *data = pkt->data;
3936  int length = pkt->size;
3937  int componentTag = 0;
3938  int dataBroadcastId = 0;
3939  unsigned carouselId = 0;
3940  {
3941  m_avCodecLock.lock();
3942  componentTag = str->component_tag;
3943  dataBroadcastId = str->data_id;
3944  carouselId = (unsigned) str->carousel_id;
3945  m_avCodecLock.unlock();
3946  }
3947  while (length > 3)
3948  {
3949  uint16_t sectionLen = (((data[1] & 0xF) << 8) | data[2]) + 3;
3950 
3951  if (sectionLen > length) // This may well be filler
3952  return;
3953 
3954  m_itv->ProcessDSMCCSection(data, sectionLen,
3955  componentTag, carouselId,
3956  dataBroadcastId);
3957  length -= sectionLen;
3958  data += sectionLen;
3959  }
3960 #else
3961  Q_UNUSED(str);
3962  Q_UNUSED(pkt);
3963 #endif // USING_MHEG
3964 }
3965 
3966 bool AvFormatDecoder::ProcessSubtitlePacket(AVStream *curstream, AVPacket *pkt)
3967 {
3968  if (!m_parent->GetSubReader(pkt->stream_index))
3969  return true;
3970 
3971  long long pts = pkt->pts;
3972  if (pts == AV_NOPTS_VALUE)
3973  pts = pkt->dts;
3974  if (pts == AV_NOPTS_VALUE)
3975  {
3976  LOG(VB_GENERAL, LOG_ERR, LOC + "No PTS found - unable to process subtitle.");
3977  return false;
3978  }
3979  pts = static_cast<long long>(av_q2d(curstream->time_base) * pts * 1000);
3980 
3981  m_trackLock.lock();
3982  int subIdx = m_selectedTrack[kTrackTypeSubtitle].m_av_stream_index;
3983  bool isForcedTrack = m_selectedTrack[kTrackTypeSubtitle].m_forced;
3984  m_trackLock.unlock();
3985 
3986  int gotSubtitles = 0;
3987  AVSubtitle subtitle;
3988  memset(&subtitle, 0, sizeof(AVSubtitle));
3989 
3990  if (m_ringBuffer->IsDVD())
3991  {
3992  if (m_ringBuffer->DVD()->NumMenuButtons() > 0)
3993  {
3994  m_ringBuffer->DVD()->GetMenuSPUPkt(pkt->data, pkt->size,
3995  curstream->id, pts);
3996  }
3997  else
3998  {
3999  if (pkt->stream_index == subIdx)
4000  {
4001  m_avCodecLock.lock();
4002  m_ringBuffer->DVD()->DecodeSubtitles(&subtitle, &gotSubtitles,
4003  pkt->data, pkt->size, pts);
4004  m_avCodecLock.unlock();
4005  }
4006  }
4007  }
4008  else if (m_decodeAllSubtitles || pkt->stream_index == subIdx)
4009  {
4010  m_avCodecLock.lock();
4011  AVCodecContext *ctx = m_codecMap.GetCodecContext(curstream);
4012  avcodec_decode_subtitle2(ctx, &subtitle, &gotSubtitles, pkt);
4013  m_avCodecLock.unlock();
4014 
4015  subtitle.start_display_time += pts;
4016  subtitle.end_display_time += pts;
4017  }
4018 
4019  if (gotSubtitles)
4020  {
4021  if (isForcedTrack)
4022  subtitle.forced = static_cast<int>(true);
4023  LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
4024  QString("subtl timecode %1 %2 %3 %4")
4025  .arg(pkt->pts).arg(pkt->dts)
4026  .arg(subtitle.start_display_time)
4027  .arg(subtitle.end_display_time));
4028 
4029  bool forcedon = m_parent->GetSubReader(pkt->stream_index)->AddAVSubtitle(
4030  subtitle, curstream->codecpar->codec_id == AV_CODEC_ID_XSUB,
4032  m_parent->EnableForcedSubtitles(forcedon || isForcedTrack);
4033  }
4034 
4035  return true;
4036 }
4037 
4039 {
4040  if (!(m_decodeAllSubtitles || m_selectedTrack[kTrackTypeRawText].m_av_stream_index == Packet->stream_index))
4041  return false;
4042 
4043  auto id = static_cast<uint>(Packet->stream_index + 0x2000);
4044  if (!m_parent->GetSubReader(id))
4045  return false;
4046 
4047 #if QT_VERSION < QT_VERSION_CHECK(6,0,0)
4048  const auto * codec = QTextCodec::codecForName("utf-8");
4049  auto text = codec->toUnicode(reinterpret_cast<const char *>(Packet->data), Packet->size - 1);
4050 #else
4051  auto toUtf16 = QStringDecoder(QStringDecoder::Utf8);
4052  QString text = toUtf16.decode(Packet->data);
4053 #endif
4054 #if QT_VERSION < QT_VERSION_CHECK(5,14,0)
4055  auto list = text.split('\n', QString::SkipEmptyParts);
4056 #else
4057  auto list = text.split('\n', Qt::SkipEmptyParts);
4058 #endif
4059  m_parent->GetSubReader(id)->AddRawTextSubtitle(list, std::chrono::milliseconds(Packet->duration));
4060  return true;
4061 }
4062 
4063 bool AvFormatDecoder::ProcessDataPacket(AVStream *curstream, AVPacket *pkt,
4064  DecodeType decodetype)
4065 {
4066  enum AVCodecID codec_id = curstream->codecpar->codec_id;
4067 
4068  switch (codec_id)
4069  {
4070  case AV_CODEC_ID_MPEG2VBI:
4071  ProcessVBIDataPacket(curstream, pkt);
4072  break;
4073  case AV_CODEC_ID_DVB_VBI:
4074  ProcessDVBDataPacket(curstream, pkt);
4075  break;
4076  case AV_CODEC_ID_DSMCC_B:
4077  {
4078  ProcessDSMCCPacket(curstream, pkt);
4080  // Have to return regularly to ensure that the OSD is updated.
4081  // This applies both to MHEG and also channel browsing.
4082 #ifdef USING_MHEG
4083  if (!(decodetype & kDecodeVideo))
4085 #else
4086  Q_UNUSED(decodetype);
4087 #endif // USING_MHEG:
4088  break;
4089  }
4090  default:
4091  break;
4092  }
4093  return true;
4094 }
4095 
4096 int AvFormatDecoder::SetTrack(uint Type, int TrackNo)
4097 {
4098  QMutexLocker locker(&m_trackLock);
4099  int ret = DecoderBase::SetTrack(Type, TrackNo);
4100  if (kTrackTypeAudio == Type)
4101  {
4102  QString msg = SetupAudioStream() ? "" : "not ";
4103  LOG(VB_AUDIO, LOG_INFO, LOC + "Audio stream type " + msg + "changed.");
4104  }
4105  return ret;
4106 }
4107 
4109 {
4110  QMutexLocker locker(&m_trackLock);
4111 
4112  if (!m_ic || TrackNo >= m_tracks[type].size())
4113  return "";
4114 
4115  bool forced = m_tracks[type][TrackNo].m_forced;
4116  int lang_key = m_tracks[type][TrackNo].m_language;
4117  QString forcedString = forced ? QObject::tr(" (forced)") : "";
4118 
4119  int av_index = m_tracks[type][TrackNo].m_av_stream_index;
4120  AVStream *stream = m_ic->streams[av_index];
4121  AVDictionaryEntry *entry =
4122  stream ? av_dict_get(stream->metadata, "title", NULL, 0) : nullptr;
4123  QString user_title = entry ? QString(R"( "%1")").arg(entry->value) : "";
4124 
4125  if (kTrackTypeAudio == type)
4126  {
4127  QString msg = iso639_key_toName(lang_key);
4128 
4129  switch (m_tracks[type][TrackNo].m_audio_type)
4130  {
4131  case kAudioTypeNormal :
4132  {
4133  if (stream)
4134  {
4135  AVCodecParameters *par = stream->codecpar;
4136  AVCodecContext *ctx = m_codecMap.GetCodecContext(stream);
4137  if (par->codec_id == AV_CODEC_ID_MP3)
4138  msg += QString(" MP3");
4139  else if (ctx && ctx->codec)
4140  msg += QString(" %1").arg(ctx->codec->name).toUpper();
4141  if (!user_title.isEmpty())
4142  msg += user_title;
4143 
4144  int channels = 0;
4145  if (m_ringBuffer->IsDVD() || par->channels)
4146  channels = m_tracks[kTrackTypeAudio][TrackNo].m_orig_num_channels;
4147 
4148  if (channels == 0)
4149  msg += QString(" ?ch");
4150  else if((channels > 4) && !(channels & 1))
4151  msg += QString(" %1.1ch").arg(channels - 1);
4152  else
4153  msg += QString(" %1ch").arg(channels);
4154  }
4155  break;
4156  }
4158  case kAudioTypeCommentary :
4160  case kAudioTypeCleanEffects :
4161  case kAudioTypeSpokenSubs :
4162  default :
4163  if (!user_title.isEmpty())
4164  msg += user_title;
4165  else
4166  msg += QString(" (%1)")
4167  .arg(toString(m_tracks[type][TrackNo].m_audio_type));
4168  break;
4169  }
4170  return QString("%1: %2").arg(TrackNo + 1).arg(msg);
4171  }
4172  if (kTrackTypeSubtitle == type)
4173  {
4174  return QObject::tr("Subtitle") + QString(" %1: %2%3%4")
4175  .arg(QString::number(TrackNo + 1),
4176  iso639_key_toName(lang_key),
4177  user_title,
4178  forcedString);
4179  }
4180  if (forced && kTrackTypeRawText == type)
4181  return DecoderBase::GetTrackDesc(type, TrackNo) + forcedString;
4182  return DecoderBase::GetTrackDesc(type, TrackNo);
4183 }
4184 
4186 {
4187  return m_ttd->GetDecoderType();
4188 }
4189 
4190 QString AvFormatDecoder::GetXDS(const QString &Key) const
4191 {
4192  return m_ccd608->GetXDS(Key);
4193 }
4194 
4196 {
4197  QMutexLocker locker(&m_trackLock);
4198  if (TrackNo >= m_tracks[kTrackTypeSubtitle].size())
4199  return QByteArray();
4200 
4201  int index = m_tracks[kTrackTypeSubtitle][TrackNo].m_av_stream_index;
4202  AVCodecContext *ctx = m_codecMap.GetCodecContext(m_ic->streams[index]);
4203  return ctx ? QByteArray(reinterpret_cast<char*>(ctx->subtitle_header), ctx->subtitle_header_size) :
4204  QByteArray();
4205 }
4206 
4207 void AvFormatDecoder::GetAttachmentData(uint TrackNo, QByteArray &Filename, QByteArray &Data)
4208 {
4209  QMutexLocker locker(&m_trackLock);
4210  if (TrackNo >= m_tracks[kTrackTypeAttachment].size())
4211  return;
4212 
4213  int index = m_tracks[kTrackTypeAttachment][TrackNo].m_av_stream_index;
4214  AVDictionaryEntry *tag = av_dict_get(m_ic->streams[index]->metadata, "filename", nullptr, 0);
4215  if (tag)
4216  Filename = QByteArray(tag->value);
4217  AVCodecParameters *par = m_ic->streams[index]->codecpar;
4218  Data = QByteArray(reinterpret_cast<char*>(par->extradata), par->extradata_size);
4219 }
4220 
4222 {
4223  QMutexLocker locker(&m_trackLock);
4224  for (size_t i = 0; i < m_tracks[kTrackTypeAudio].size(); i++)
4225  {
4226  AVStream *stream = m_ic->streams[m_tracks[kTrackTypeAudio][i].m_av_stream_index];
4227  if (stream)
4228  if ((stream->component_tag == Tag) || ((Tag <= 0) && stream->component_tag <= 0))
4229  return SetTrack(kTrackTypeAudio, static_cast<int>(i)) != -1;
4230  }
4231  return false;
4232 }
4233 
4235 {
4236  QMutexLocker locker(&m_trackLock);
4237  for (uint i = 0; i < m_ic->nb_streams; i++)
4238  {
4239  AVStream *stream = m_ic->streams[i];
4240  if (stream)
4241  {
4242  if (stream->component_tag == Tag)
4243  {
4244  StreamInfo si(static_cast<int>(i), 0, 0, 0, 0);
4246  return true;
4247  }
4248  }
4249  }
4250  return false;
4251 }
4252 
4253 // documented in decoderbase.cpp
4255 {
4256  if (kTrackTypeAudio == type)
4257  return AutoSelectAudioTrack();
4258 
4260  return -1;
4261 
4263 }
4264 
4265 static vector<int> filter_lang(const sinfo_vec_t &tracks, int lang_key,
4266  const vector<int> &ftype)
4267 {
4268  vector<int> ret;
4269 
4270  for (int index : ftype)
4271  {
4272  if ((lang_key < 0) || tracks[index].m_language == lang_key)
4273  ret.push_back(index);
4274  }
4275 
4276  return ret;
4277 }
4278 
4279 static vector<int> filter_type(const sinfo_vec_t &tracks, AudioTrackType type)
4280 {
4281  vector<int> ret;
4282 
4283  for (size_t i = 0; i < tracks.size(); i++)
4284  {
4285  if (tracks[i].m_audio_type == type)
4286  ret.push_back(i);
4287  }
4288 
4289  return ret;
4290 }
4291 
4292 int AvFormatDecoder::filter_max_ch(const AVFormatContext *ic,
4293  const sinfo_vec_t &tracks,
4294  const vector<int> &fs,
4295  enum AVCodecID codecId,
4296  int profile)
4297 {
4298  int selectedTrack = -1;
4299  int max_seen = -1;
4300 
4301  for (int f : fs)
4302  {
4303  const int stream_index = tracks[f].m_av_stream_index;
4304  AVCodecParameters *par = ic->streams[stream_index]->codecpar;
4305  if ((codecId == AV_CODEC_ID_NONE || codecId == par->codec_id) &&
4306  (max_seen < par->channels))
4307  {
4308  if (codecId == AV_CODEC_ID_DTS && profile > 0)
4309  {
4310  // we cannot decode dts-hd, so only select it if passthrough
4311  if (!DoPassThrough(par, true) || par->profile != profile)
4312  continue;
4313  }
4314  selectedTrack = f;
4315  max_seen = par->channels;
4316  }
4317  }
4318 
4319  return selectedTrack;
4320 }
4321 
4369 {
4370  QMutexLocker locker(&m_trackLock);
4371 
4372  const sinfo_vec_t &atracks = m_tracks[kTrackTypeAudio];
4375  int &ctrack = m_currentTrack[kTrackTypeAudio];
4376 
4377  uint numStreams = atracks.size();
4378  if ((ctrack >= 0) && (ctrack < (int)numStreams))
4379  return ctrack; // audio already selected
4380 
4381 #if 0
4382  // enable this to print streams
4383  for (const auto & track : atracks)
4384  {
4385  int idx = track.m_av_stream_index;
4386  AVCodecContext *codec_ctx = m_ic->streams[idx]->codec;
4387  AudioInfo item(codec_ctx->codec_id, codec_ctx->bps,
4388  codec_ctx->sample_rate, codec_ctx->channels,
4389  DoPassThrough(codec_ctx, true));
4390  LOG(VB_AUDIO, LOG_DEBUG, LOC + " * " + item.toString());
4391  }
4392 #endif
4393 
4394  int selTrack = (1 == numStreams) ? 0 : -1;
4395  int wlang = wtrack.m_language;
4396 
4397  if ((selTrack < 0) && (wtrack.m_av_substream_index >= 0))
4398  {
4399  LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to reselect audio sub-stream");
4400  // Dual stream without language information: choose
4401  // the previous substream that was kept in wtrack,
4402  // ignoring the stream index (which might have changed).
4403  int substream_index = wtrack.m_av_substream_index;
4404 
4405  for (uint i = 0; i < numStreams; i++)
4406  {
4407  if (atracks[i].m_av_substream_index == substream_index)
4408  {
4409  selTrack = i;
4410  break;
4411  }
4412  }
4413  }
4414 
4415  if ((selTrack < 0) && wlang >= -1 && numStreams)
4416  {
4417  LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to reselect audio track");
4418  // Try to reselect user selected audio stream.
4419  // This should find the stream after a commercial
4420  // break and in some cases after a channel change.
4421  uint windx = wtrack.m_language_index;
4422  for (uint i = 0; i < numStreams; i++)
4423  {
4424  if (wlang == atracks[i].m_language)
4425  {
4426  selTrack = i;
4427 
4428  if (windx == atracks[i].m_language_index)
4429  break;
4430  }
4431  }
4432  }
4433 
4434  if (selTrack < 0 && numStreams)
4435  {
4436  LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to select audio track (w/lang)");
4437 
4438  // Filter out commentary and audio description tracks
4439  vector<int> ftype = filter_type(atracks, kAudioTypeNormal);
4440 
4441  if (ftype.empty())
4442  {
4443  LOG(VB_AUDIO, LOG_WARNING, "No audio tracks matched the type filter, "
4444  "so trying all tracks.");
4445  for (int i = 0; i < static_cast<int>(atracks.size()); i++)
4446  ftype.push_back(i);
4447  }
4448 
4449  // try to get the language track matching the frontend language.
4450  QString language_key_convert = iso639_str2_to_str3(gCoreContext->GetLanguage());
4451  uint language_key = iso639_str3_to_key(language_key_convert);
4452  uint canonical_key = iso639_key_to_canonical_key(language_key);
4453 
4454  vector<int> flang = filter_lang(atracks, canonical_key, ftype);
4455 
4456  if (m_audio->CanDTSHD())
4457  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS,
4458  FF_PROFILE_DTS_HD_MA);
4459  if (selTrack < 0)
4460  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_TRUEHD);
4461 
4462  if (selTrack < 0 && m_audio->CanDTSHD())
4463  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS,
4464  FF_PROFILE_DTS_HD_HRA);
4465  if (selTrack < 0)
4466  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_EAC3);
4467 
4468  if (selTrack < 0)
4469  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS);
4470 
4471  if (selTrack < 0)
4472  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_AC3);
4473 
4474  if (selTrack < 0)
4475  selTrack = filter_max_ch(m_ic, atracks, flang);
4476 
4477  // try to get best track for most preferred language
4478  // Set by the "Guide Data" language prefs in Appearance.
4479  if (selTrack < 0)
4480  {
4481  auto it = m_languagePreference.begin();
4482  for (; it != m_languagePreference.end() && selTrack < 0; ++it)
4483  {
4484  flang = filter_lang(atracks, *it, ftype);
4485 
4486  if (m_audio->CanDTSHD())
4487  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS,
4488  FF_PROFILE_DTS_HD_MA);
4489  if (selTrack < 0)
4490  selTrack = filter_max_ch(m_ic, atracks, flang,
4491  AV_CODEC_ID_TRUEHD);
4492 
4493  if (selTrack < 0 && m_audio->CanDTSHD())
4494  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS,
4495  FF_PROFILE_DTS_HD_HRA);
4496 
4497  if (selTrack < 0)
4498  selTrack = filter_max_ch(m_ic, atracks, flang,
4499  AV_CODEC_ID_EAC3);
4500 
4501  if (selTrack < 0)
4502  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS);
4503 
4504  if (selTrack < 0)
4505  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_AC3);
4506 
4507  if (selTrack < 0)
4508  selTrack = filter_max_ch(m_ic, atracks, flang);
4509  }
4510  }
4511 
4512  // could not select track based on user preferences (language)
4513  // try to select the default track
4514  if (selTrack < 0)
4515  {
4516  LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to select default track");
4517  for (size_t i = 0; i < atracks.size(); i++) {
4518  int idx = atracks[i].m_av_stream_index;
4519  if (m_ic->streams[idx]->disposition & AV_DISPOSITION_DEFAULT)
4520  {
4521  selTrack = i;
4522  break;
4523  }
4524  }
4525  }
4526 
4527  // try to get best track for any language
4528  if (selTrack < 0)
4529  {
4530  LOG(VB_AUDIO, LOG_INFO, LOC +
4531  "Trying to select audio track (wo/lang)");
4532  flang = filter_lang(atracks, -1, ftype);
4533 
4534  if (m_audio->CanDTSHD())
4535  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS,
4536  FF_PROFILE_DTS_HD_MA);
4537  if (selTrack < 0)
4538  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_TRUEHD);
4539 
4540  if (selTrack < 0 && m_audio->CanDTSHD())
4541  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS,
4542  FF_PROFILE_DTS_HD_HRA);
4543 
4544  if (selTrack < 0)
4545  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_EAC3);
4546 
4547  if (selTrack < 0)
4548  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_DTS);
4549 
4550  if (selTrack < 0)
4551  selTrack = filter_max_ch(m_ic, atracks, flang, AV_CODEC_ID_AC3);
4552 
4553  if (selTrack < 0)
4554  selTrack = filter_max_ch(m_ic, atracks, flang);
4555  }
4556  }
4557 
4558  if (selTrack < 0)
4559  {
4560  strack.m_av_stream_index = -1;
4561  if (ctrack != selTrack)
4562  {
4563  LOG(VB_AUDIO, LOG_INFO, LOC + "No suitable audio track exists.");
4564  ctrack = selTrack;
4565  }
4566  }
4567  else
4568  {
4569  ctrack = selTrack;
4570  strack = atracks[selTrack];
4571 
4572  if (wtrack.m_av_stream_index < 0)
4573  wtrack = strack;
4574 
4575  LOG(VB_AUDIO, LOG_INFO, LOC + QString("Selected track %1 (A/V Stream #%2)")
4576  .arg(static_cast<uint>(ctrack)).arg(strack.m_av_stream_index));
4577  }
4578 
4579  SetupAudioStream();
4580  return selTrack;
4581 }
4582 
4583 static void extract_mono_channel(uint channel, AudioInfo *audioInfo,
4584  char *buffer, int bufsize)
4585 {
4586  // Only stereo -> mono (left or right) is supported
4587  if (audioInfo->m_channels != 2)
4588  return;
4589 
4590  if (channel >= (uint)audioInfo->m_channels)
4591  return;
4592 
4593  const uint samplesize = audioInfo->m_sampleSize;
4594  const uint samples = bufsize / samplesize;
4595  const uint halfsample = samplesize >> 1;
4596 
4597  const char *from = (channel == 1) ? buffer + halfsample : buffer;
4598  char *to = (channel == 0) ? buffer + halfsample : buffer;
4599 
4600  for (uint sample = 0; sample < samples;
4601  (sample++), (from += samplesize), (to += samplesize))
4602  {
4603  memmove(to, from, halfsample);
4604  }
4605 }
4606 
4607 bool AvFormatDecoder::ProcessAudioPacket(AVStream *curstream, AVPacket *pkt,
4608  DecodeType decodetype)
4609 {
4610  AVCodecContext *ctx = m_codecMap.GetCodecContext(curstream);
4611  int ret = 0;
4612  int data_size = 0;
4613  bool firstloop = true;
4614  int decoded_size = -1;
4615 
4616  m_trackLock.lock();
4617  int audIdx = m_selectedTrack[kTrackTypeAudio].m_av_stream_index;
4618  int audSubIdx = m_selectedTrack[kTrackTypeAudio].m_av_substream_index;
4619  m_trackLock.unlock();
4620 
4621  AVPacket tmp_pkt;
4622  av_init_packet(&tmp_pkt);
4623  tmp_pkt.data = pkt->data;
4624  tmp_pkt.size = pkt->size;
4625 
4626  while (tmp_pkt.size > 0)
4627  {
4628  bool reselectAudioTrack = false;
4629 
4631  if (!m_audio->HasAudioIn())
4632  {
4633  LOG(VB_AUDIO, LOG_INFO, LOC +
4634  "Audio is disabled - trying to restart it");
4635  reselectAudioTrack = true;
4636  }
4638 
4639  // detect switches between stereo and dual languages
4640  bool wasDual = audSubIdx != -1;
4641  bool isDual = ctx->avcodec_dual_language != 0;
4642  if ((wasDual && !isDual) || (!wasDual && isDual))
4643  {
4645  reselectAudioTrack = true;
4646  }
4647 
4648  // detect channels on streams that need
4649  // to be decoded before we can know this
4650  bool already_decoded = false;
4651  if (!ctx->channels)
4652  {
4653  m_avCodecLock.lock();
4654  if (DoPassThrough(curstream->codecpar, false) || !DecoderWillDownmix(ctx))
4655  {
4656  // for passthru or codecs for which the decoder won't downmix
4657  // let the decoder set the number of channels. For other codecs
4658  // we downmix if necessary in audiooutputbase
4659  ctx->request_channel_layout = 0;
4660  }
4661  else // No passthru, the decoder will downmix
4662  {
4663  ctx->request_channel_layout =
4664  av_get_default_channel_layout(m_audio->GetMaxChannels());
4665  if (ctx->codec_id == AV_CODEC_ID_AC3)
4666  ctx->channels = m_audio->GetMaxChannels();
4667  }
4668 
4669  ret = m_audio->DecodeAudio(ctx, m_audioSamples, data_size, &tmp_pkt);
4670  decoded_size = data_size;
4671  already_decoded = true;
4672  reselectAudioTrack |= ctx->channels;
4673  m_avCodecLock.unlock();
4674  }
4675 
4676  if (reselectAudioTrack)
4677  {
4678  QMutexLocker locker(&m_trackLock);
4680  m_selectedTrack[kTrackTypeAudio].m_av_stream_index = -1;
4682  audIdx = m_selectedTrack[kTrackTypeAudio].m_av_stream_index;
4683  audSubIdx = m_selectedTrack[kTrackTypeAudio].m_av_substream_index;
4684  }
4685 
4686  if (!(decodetype & kDecodeAudio) || (pkt->stream_index != audIdx)
4687  || !m_audio->HasAudioOut())
4688  break;
4689 
4690  if (firstloop && pkt->pts != AV_NOPTS_VALUE)
4691  m_lastAPts = millisecondsFromFloat(av_q2d(curstream->time_base) * pkt->pts * 1000);
4692 
4693  if (!m_useFrameTiming)
4694  {
4695  // This code under certain conditions causes jump backwards to lose
4696  // audio.
4697  if (m_skipAudio && m_selectedTrack[kTrackTypeVideo].m_av_stream_index > -1)
4698  {
4699  if ((m_lastAPts < m_lastVPts - millisecondsFromFloat(10.0 / m_fps)) ||
4700  m_lastVPts == 0ms)
4701  break;
4702  m_skipAudio = false;
4703  }
4704 
4705  // skip any audio frames preceding first video frame
4706  if (m_firstVPtsInuse && (m_firstVPts != 0ms) && (m_lastAPts < m_firstVPts))
4707  {
4708  LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
4709  QString("discarding early audio timecode %1 %2 %3")
4710  .arg(pkt->pts).arg(pkt->dts).arg(m_lastAPts.count()));
4711  break;
4712  }
4713  }
4714  m_firstVPtsInuse = false;
4715  m_avCodecLock.lock();
4716  data_size = 0;
4717 
4718  // Check if the number of channels or sampling rate have changed
4719  if (ctx->sample_rate != m_audioOut.m_sampleRate ||
4720  ctx->channels != m_audioOut.m_channels ||
4722  ctx->bits_per_raw_sample) != m_audioOut.format)
4723  {
4724  LOG(VB_GENERAL, LOG_INFO, LOC + "Audio stream changed");
4725  if (ctx->channels != m_audioOut.m_channels)
4726  {
4727  LOG(VB_GENERAL, LOG_INFO, LOC + QString("Number of audio channels changed from %1 to %2")
4728  .arg(m_audioOut.m_channels).arg(ctx->channels));
4729  }
4730  QMutexLocker locker(&m_trackLock);
4732  m_selectedTrack[kTrackTypeAudio].m_av_stream_index = -1;
4733  audIdx = -1;
4735  }
4736 
4738  {
4739  if (!already_decoded)
4740  {
4742  {
4743  ret = m_audio->DecodeAudio(ctx, m_audioSamples, data_size, &tmp_pkt);
4744  decoded_size = data_size;
4745  }
4746  else
4747  {
4748  decoded_size = -1;
4749  }
4750  }
4751  memcpy(m_audioSamples, tmp_pkt.data, tmp_pkt.size);
4752  data_size = tmp_pkt.size;
4753  // We have processed all the data, there can't be any left
4754  tmp_pkt.size = 0;
4755  }
4756  else
4757  {
4758  if (!already_decoded)
4759  {
4760  if (DecoderWillDownmix(ctx))
4761  {
4762  ctx->request_channel_layout =
4763  av_get_default_channel_layout(m_audio->GetMaxChannels());
4764  }
4765  else
4766  {
4767  ctx->request_channel_layout = 0;
4768  }
4769 
4770  ret = m_audio->DecodeAudio(ctx, m_audioSamples, data_size, &tmp_pkt);
4771  decoded_size = data_size;
4772  }
4773  }
4774  m_avCodecLock.unlock();
4775 
4776  if (ret < 0)
4777  {
4778  LOG(VB_GENERAL, LOG_ERR, LOC + "Unknown audio decoding error");
4779  return false;
4780  }
4781 
4782  if (data_size <= 0)
4783  {
4784  tmp_pkt.data += ret;
4785  tmp_pkt.size -= ret;
4786  continue;
4787  }
4788 
4789  std::chrono::milliseconds temppts = m_lastAPts;
4790 
4791  if (audSubIdx != -1 && !m_audioOut.m_doPassthru)
4792  extract_mono_channel(audSubIdx, &m_audioOut,
4793  (char *)m_audioSamples, data_size);
4794 
4795  int samplesize = AudioOutputSettings::SampleSize(m_audio->GetFormat());
4796  int frames = (ctx->channels <= 0 || decoded_size < 0 || !samplesize) ? -1 :
4797  decoded_size / (ctx->channels * samplesize);
4798  m_audio->AddAudioData((char *)m_audioSamples, data_size, temppts, frames);
4800  {
4802  }
4803  else
4804  {
4806  ((double)(frames * 1000) / ctx->sample_rate);
4807  }
4808 
4809  LOG(VB_TIMESTAMP, LOG_INFO, LOC + QString("audio timecode %1 %2 %3 %4")
4810  .arg(pkt->pts).arg(pkt->dts).arg(temppts.count()).arg(m_lastAPts.count()));
4811 
4814 
4815  tmp_pkt.data += ret;
4816  tmp_pkt.size -= ret;
4817  firstloop = false;
4818  }
4819 
4820  return true;
4821 }
4822 
4823 // documented in decoderbase.h
4824 bool AvFormatDecoder::GetFrame(DecodeType decodetype, bool &Retry)
4825 {
4826  AVPacket *pkt = nullptr;
4827  bool have_err = false;
4828 
4829  const DecodeType origDecodetype = decodetype;
4830 
4831  m_gotVideoFrame = false;
4832 
4833  m_frameDecoded = 0;
4834  m_decodedVideoFrame = nullptr;
4835 
4836  m_allowedQuit = false;
4837  bool storevideoframes = false;
4838 
4839  AutoSelectTracks();
4840 
4841  m_skipAudio = (m_lastVPts == 0ms);
4842 
4843  if( !m_processFrames )
4844  {
4845  return false;
4846  }
4847 
4849  m_needDummyVideoFrames = false;
4850 
4851  if (!m_hasVideo && (decodetype & kDecodeVideo))
4852  {
4853  // NB This could be an issue if the video stream is not
4854  // detected initially as the video buffers will be filled.
4855  m_needDummyVideoFrames = true;
4856  decodetype = (DecodeType)((int)decodetype & ~kDecodeVideo);
4857  m_skipAudio = false;
4858  }
4859 
4861 
4862  while (!m_allowedQuit)
4863  {
4864  if (decodetype & kDecodeAudio)
4865  {
4866  if (((m_currentTrack[kTrackTypeAudio] < 0) ||
4867  (m_selectedTrack[kTrackTypeAudio].m_av_stream_index < 0)))
4868  {
4869  // disable audio request if there are no audio streams anymore
4870  // and we have video, otherwise allow decoding to stop
4871  if (m_hasVideo)
4872  decodetype = (DecodeType)((int)decodetype & ~kDecodeAudio);
4873  else
4874  m_allowedQuit = true;
4875  }
4876  }
4877  else if ((origDecodetype & kDecodeAudio) &&
4878  (m_currentTrack[kTrackTypeAudio] >= 0) &&
4879  (m_selectedTrack[kTrackTypeAudio].m_av_stream_index >= 0))
4880  {
4881  // Turn on audio decoding again if it was on originally
4882  // and an audio stream has now appeared. This can happen
4883  // in still DVD menus with audio
4884  decodetype = (DecodeType)((int)decodetype | kDecodeAudio);
4885  }
4886 
4888 
4889  if (m_gotVideoFrame)
4890  {
4891  if (decodetype == kDecodeNothing)
4892  {
4893  // no need to buffer audio or video if we
4894  // only care about building a keyframe map.
4895  // NB but allow for data only (MHEG) streams
4896  m_allowedQuit = true;
4897  }
4898  else if ((decodetype & kDecodeAV) == kDecodeAV &&
4899  (m_storedPackets.count() < max_video_queue_size) &&
4900  // buffer audio to prevent audio buffer
4901  // underruns in case you are setting negative values
4902  // in Adjust Audio Sync.
4905  {
4906  storevideoframes = true;
4907  }
4908  else if (decodetype & kDecodeVideo)
4909  {
4910  if (m_storedPackets.count() >= max_video_queue_size)
4911  {
4912  LOG(VB_GENERAL, LOG_WARNING, LOC +
4913  QString("Audio %1 ms behind video but already %2 "
4914  "video frames queued. AV-Sync might be broken.")
4915  .arg((m_lastVPts-m_lastAPts).count()).arg(m_storedPackets.count()));
4916  }
4917  m_allowedQuit = true;
4918  continue;
4919  }
4920  }
4921 
4922  if (!storevideoframes && m_storedPackets.count() > 0)
4923  {
4924  if (pkt)
4925  {
4926  av_packet_unref(pkt);
4927  delete pkt;
4928  }
4929  pkt = m_storedPackets.takeFirst();
4930  }
4931  else
4932  {
4933  if (!pkt)
4934  {
4935  pkt = new AVPacket;
4936  memset(pkt, 0, sizeof(AVPacket));
4937  av_init_packet(pkt);
4938  }
4939 
4940  int retval = 0;
4941  if (!m_ic || ((retval = ReadPacket(m_ic, pkt, storevideoframes)) < 0))
4942  {
4943  if (retval == -EAGAIN)
4944  continue;
4945 
4946  SetEof(true);
4947  delete pkt;
4948  std::string errbuf(256,'\0');
4949  QString errmsg;
4950  if (av_strerror_stdstring(retval, errbuf) == 0)
4951  errmsg = QString::fromStdString(errbuf);
4952  else
4953  errmsg = "UNKNOWN";
4954 
4955  LOG(VB_GENERAL, LOG_ERR, QString("decoding error %1 (%2)")
4956  .arg(errmsg).arg(retval));
4957  return false;
4958  }
4959 
4960  if (m_waitingForChange && pkt->pos >= m_readAdjust)
4961  FileChanged();
4962 
4963  if (pkt->pos > m_readAdjust)
4964  pkt->pos -= m_readAdjust;
4965  }
4966 
4967  if (!m_ic)
4968  {
4969  LOG(VB_GENERAL, LOG_ERR, LOC + "No context");
4970  av_packet_unref(pkt);
4971  continue;
4972  }
4973 
4974  if (pkt->stream_index >= (int)m_ic->nb_streams)
4975  {
4976  LOG(VB_GENERAL, LOG_ERR, LOC + "Bad stream");
4977  av_packet_unref(pkt);
4978  continue;
4979  }
4980 
4981  AVStream *curstream = m_ic->streams[pkt->stream_index];
4982 
4983  if (!curstream)
4984  {
4985  LOG(VB_GENERAL, LOG_ERR, LOC + "Bad stream (NULL)");
4986  av_packet_unref(pkt);
4987  continue;
4988  }
4989 
4990  enum AVMediaType codec_type = curstream->codecpar->codec_type;
4991 
4992  if (storevideoframes && codec_type == AVMEDIA_TYPE_VIDEO)
4993  {
4994  // av_dup_packet(pkt);
4995  m_storedPackets.append(pkt);
4996  pkt = nullptr;
4997  continue;
4998  }
4999 
5000  if (codec_type == AVMEDIA_TYPE_VIDEO &&
5001  pkt->stream_index == m_selectedTrack[kTrackTypeVideo].m_av_stream_index)
5002  {
5003  if (!PreProcessVideoPacket(curstream, pkt))
5004  continue;
5005 
5006  // If the resolution changed in XXXPreProcessPkt, we may
5007  // have a fatal error, so check for this before continuing.
5008  if (m_parent->IsErrored())
5009  {
5010  av_packet_unref(pkt);
5011  delete pkt;
5012  return false;
5013  }
5014  }
5015 
5016  if (codec_type == AVMEDIA_TYPE_SUBTITLE &&
5017  curstream->codecpar->codec_id == AV_CODEC_ID_TEXT)
5018  {
5019  ProcessRawTextPacket(pkt);
5020  av_packet_unref(pkt);
5021  continue;
5022  }
5023 
5024  if (codec_type == AVMEDIA_TYPE_SUBTITLE &&
5025  curstream->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT)
5026  {
5027  ProcessDVBDataPacket(curstream, pkt);
5028  av_packet_unref(pkt);
5029  continue;
5030  }
5031 
5032  if (codec_type == AVMEDIA_TYPE_DATA)
5033  {
5034  ProcessDataPacket(curstream, pkt, decodetype);
5035  av_packet_unref(pkt);
5036  continue;
5037  }
5038 
5039  AVCodecContext *ctx = m_codecMap.GetCodecContext(curstream);
5040  if (!ctx)
5041  {
5042  if (codec_type != AVMEDIA_TYPE_VIDEO)
5043  {
5044  LOG(VB_PLAYBACK, LOG_ERR, LOC +
5045  QString("No codec for stream index %1, type(%2) id(%3:%4)")
5046  .arg(pkt->stream_index)
5047  .arg(ff_codec_type_string(codec_type),
5048  ff_codec_id_string(curstream->codecpar->codec_id))
5049  .arg(curstream->codecpar->codec_id));
5050  // Process Stream Change in case we have no audio
5051  if (codec_type == AVMEDIA_TYPE_AUDIO && !m_audio->HasAudioIn())
5052  m_streamsChanged = true;
5053  }
5054  av_packet_unref(pkt);
5055  continue;
5056  }
5057 
5058  have_err = false;
5059 
5060  switch (codec_type)
5061  {
5062  case AVMEDIA_TYPE_AUDIO:
5063  {
5064  if (!ProcessAudioPacket(curstream, pkt, decodetype))
5065  have_err = true;
5066  else
5068  break;
5069  }
5070 
5071  case AVMEDIA_TYPE_VIDEO:
5072  {
5073  if (pkt->stream_index != m_selectedTrack[kTrackTypeVideo].m_av_stream_index)
5074  {
5075  break;
5076  }
5077 
5078  if (pkt->pts != AV_NOPTS_VALUE)
5079  {
5081  (av_q2d(curstream->time_base)*pkt->pts*1000000);
5082  }
5083 
5084  if (!(decodetype & kDecodeVideo))
5085  {
5086  m_framesPlayed++;
5087  m_gotVideoFrame = true;
5088  break;
5089  }
5090 
5091  if (!ProcessVideoPacket(curstream, pkt, Retry))
5092  have_err = true;
5093  break;
5094  }
5095 
5096  case AVMEDIA_TYPE_SUBTITLE:
5097  {
5098  if (!ProcessSubtitlePacket(curstream, pkt))
5099  have_err = true;
5100  break;
5101  }
5102 
5103  default:
5104  {
5105  LOG(VB_GENERAL, LOG_ERR, LOC +
5106  QString("Decoding - id(%1) type(%2)")
5107  .arg(ff_codec_id_string(ctx->codec_id),
5108  ff_codec_type_string(ctx->codec_type)));
5109  have_err = true;
5110  break;
5111  }
5112  }
5113 
5114  if (!have_err && !Retry)
5115  m_frameDecoded = 1;
5116  av_packet_unref(pkt);
5117  if (Retry)
5118  break;
5119  }
5120 
5121  delete pkt;
5122  return true;
5123 }
5124 
5126 {
5127  if (m_streamsChanged)
5128  {
5129  SeekReset(0, 0, true, true);
5130  ScanStreams(false);
5131  m_streamsChanged = false;
5132  }
5133 }
5134 
5135 int AvFormatDecoder::ReadPacket(AVFormatContext *ctx, AVPacket *pkt, bool &/*storePacket*/)
5136 {
5137  m_avCodecLock.lock();
5138  int result = av_read_frame(ctx, pkt);
5139  m_avCodecLock.unlock();
5140  return result;
5141 }
5142 
5143 bool AvFormatDecoder::HasVideo(const AVFormatContext *ic)
5144 {
5145  if (ic && ic->cur_pmt_sect)
5146  {
5147  const ProgramMapTable pmt(PSIPTable(ic->cur_pmt_sect));
5148 
5149  for (uint i = 0; i < pmt.StreamCount(); i++)
5150  {
5151  // MythTV remaps OpenCable Video to normal video during recording
5152  // so "dvb" is the safest choice for system info type, since this
5153  // will ignore other uses of the same stream id in DVB countries.
5154  if (pmt.IsVideo(i, "dvb"))
5155  return true;
5156 
5157  // MHEG may explicitly select a private stream as video
5158  if ((i == (uint)m_selectedTrack[kTrackTypeVideo].m_av_stream_index) &&
5159  (pmt.StreamType(i) == StreamID::PrivData))
5160  {
5161  return true;
5162  }
5163  }
5164  }
5165 
5166  return GetTrackCount(kTrackTypeVideo) != 0U;
5167 }
5168 
5170 {
5172  {
5174  if (!frame)
5175  return false;
5176 
5177  frame->ClearMetadata();
5178  frame->ClearBufferToBlank();
5179 
5180  frame->m_dummy = true;
5181  frame->m_frameNumber = m_framesPlayed;
5182  frame->m_frameCounter = m_frameCounter++;
5183 
5185  m_parent->DeLimboFrame(frame);
5186 
5187  m_decodedVideoFrame = frame;
5188  m_framesPlayed++;
5189  m_gotVideoFrame = true;
5190  }
5191  return true;
5192 }
5193 
5195 {
5197 }
5198 
5200 {
5201  int stream = m_selectedTrack[kTrackTypeVideo].m_av_stream_index;
5202  if (stream < 0 || !m_ic)
5203  return QString();
5204  return ff_codec_id_string(m_ic->streams[stream]->codecpar->codec_id);
5205 }
5206 
5208 {
5209  if (m_selectedTrack[kTrackTypeAudio].m_av_stream_index < 0)
5210  {
5211  m_disablePassthru = disable;
5212  return;
5213  }
5214 
5215  if (disable != m_disablePassthru)
5216  {
5217  m_disablePassthru = disable;
5218  QString msg = (disable) ? "Disabling" : "Allowing";
5219  LOG(VB_AUDIO, LOG_INFO, LOC + msg + " pass through");
5220 
5221  // Force pass through state to be reanalyzed
5223  }
5224 }
5225 
5227 {
5228  QMutexLocker locker(&m_trackLock);
5229  SetupAudioStream();
5230 }
5231 
5232 inline bool AvFormatDecoder::DecoderWillDownmix(const AVCodecContext *ctx)
5233 {
5234  // Until ffmpeg properly implements dialnorm
5235  // use Myth internal downmixer if machines has FPU/SSE
5237  return false;
5238  if (!m_audio->CanDownmix())
5239  return true;
5240  // use ffmpeg only for dolby codecs if we have to
5241  switch (ctx->codec_id)
5242  {
5243  case AV_CODEC_ID_AC3:
5244  case AV_CODEC_ID_TRUEHD:
5245  case AV_CODEC_ID_EAC3:
5246  return true;
5247  default:
5248  return false;
5249  }
5250 }
5251 
5252 bool AvFormatDecoder::DoPassThrough(const AVCodecParameters *par, bool withProfile)
5253 {
5254  bool passthru = false;
5255 
5256  // if withProfile == false, we will accept any DTS stream regardless
5257  // of its profile. We do so, so we can bitstream DTS-HD as DTS core
5258  if (!withProfile && par->codec_id == AV_CODEC_ID_DTS && !m_audio->CanDTSHD())
5259  {
5260  passthru = m_audio->CanPassthrough(par->sample_rate, par->channels,
5261  par->codec_id, FF_PROFILE_DTS);
5262  }
5263  else
5264  {
5265  passthru = m_audio->CanPassthrough(par->sample_rate, par->channels,
5266  par->codec_id, par->profile);
5267  }
5268 
5269  passthru &= !m_disablePassthru;
5270 
5271  return passthru;
5272 }
5273 
5280 {
5281  AudioInfo info; // no_audio
5282  AVStream *curstream = nullptr;
5283  AVCodecContext *ctx = nullptr;
5284  AudioInfo old_in = m_audioIn;
5285  int requested_channels = 0;
5286 
5287  if ((m_currentTrack[kTrackTypeAudio] >= 0) && m_ic &&
5288  (m_selectedTrack[kTrackTypeAudio].m_av_stream_index <=
5289  (int) m_ic->nb_streams) &&
5290  (curstream = m_ic->streams[m_selectedTrack[kTrackTypeAudio]
5291  .m_av_stream_index]) &&
5292  (ctx = m_codecMap.GetCodecContext(curstream)))
5293  {
5294  AudioFormat fmt =
5296  ctx->bits_per_raw_sample);
5297 
5298  if (av_sample_fmt_is_planar(ctx->sample_fmt))
5299  {
5300  LOG(VB_AUDIO, LOG_INFO, LOC + QString("Audio data is planar"));
5301  }
5302 
5303  if (fmt == FORMAT_NONE)
5304  {
5305  int bps = av_get_bytes_per_sample(ctx->sample_fmt) << 3;
5306  if (ctx->sample_fmt == AV_SAMPLE_FMT_S32 &&
5307  ctx->bits_per_raw_sample)
5308  bps = ctx->bits_per_raw_sample;
5309  LOG(VB_GENERAL, LOG_ERR, LOC +
5310  QString("Unsupported sample format with %1 bits").arg(bps));
5311  return false;
5312  }
5313 
5314  bool using_passthru = DoPassThrough(curstream->codecpar, false);
5315 
5316  requested_channels = ctx->channels;
5317  ctx->request_channel_layout =
5318  av_get_default_channel_layout(requested_channels);
5319 
5320  if (!using_passthru &&
5321  ctx->channels > (int)m_audio->GetMaxChannels() &&
5322  DecoderWillDownmix(ctx))
5323  {
5324  requested_channels = m_audio->GetMaxChannels();
5325  ctx->request_channel_layout =
5326  av_get_default_channel_layout(requested_channels);
5327  }
5328  else
5329  {
5330  ctx->request_channel_layout = 0;
5331  }
5332 
5333  info = AudioInfo(ctx->codec_id, fmt, ctx->sample_rate,
5334  requested_channels, using_passthru, ctx->channels,
5335  ctx->codec_id == AV_CODEC_ID_DTS ? ctx->profile : 0);
5336  }
5337 
5338  if (!ctx)
5339  {
5340  if (!m_tracks[kTrackTypeAudio].empty())
5341  LOG(VB_PLAYBACK, LOG_INFO, LOC + "No codec context. Returning false");
5342  return false;
5343  }
5344 
5345  if (info == m_audioIn)
5346  return false;
5347 
5348  LOG(VB_AUDIO, LOG_INFO, LOC + "Initializing audio parms from " +
5349  QString("audio track #%1").arg(m_currentTrack[kTrackTypeAudio]+1));
5350 
5351  m_audioOut = m_audioIn = info;
5352 
5353  LOG(VB_AUDIO, LOG_INFO, LOC + "Audio format changed " +
5354  QString("\n\t\t\tfrom %1 to %2")
5355  .arg(old_in.toString(), m_audioOut.toString()));
5356 
5357  m_audio->SetAudioParams(m_audioOut.format, ctx->channels,
5358  requested_channels,
5361  m_audio->ReinitAudio();
5362  AudioOutput *audioOutput = m_audio->GetAudioOutput();
5363  if (audioOutput)
5364  audioOutput->SetSourceBitrate(ctx->bit_rate);
5365 
5366  if (LCD *lcd = LCD::Get())
5367  {
5368  LCDAudioFormatSet audio_format = AUDIO_MP3;
5369 
5370  switch (ctx->codec_id)
5371  {
5372  case AV_CODEC_ID_MP2:
5373  audio_format = AUDIO_MPEG2;
5374  break;
5375  case AV_CODEC_ID_MP3:
5376  audio_format = AUDIO_MP3;
5377  break;
5378  case AV_CODEC_ID_AC3:
5379  audio_format = AUDIO_AC3;
5380  break;
5381  case AV_CODEC_ID_DTS:
5382  audio_format = AUDIO_DTS;
5383  break;
5384  case AV_CODEC_ID_VORBIS:
5385  audio_format = AUDIO_OGG;
5386  break;
5387  case AV_CODEC_ID_WMAV1:
5388  audio_format = AUDIO_WMA;
5389  break;
5390  case AV_CODEC_ID_WMAV2:
5391  audio_format = AUDIO_WMA2;
5392  break;
5393  default:
5394  audio_format = AUDIO_WAV;
5395  break;
5396  }
5397 
5398  lcd->setAudioFormatLEDs(audio_format, true);
5399 
5401  lcd->setVariousLEDs(VARIOUS_SPDIF, true);
5402  else
5403  lcd->setVariousLEDs(VARIOUS_SPDIF, false);
5404 
5405  switch (m_audioIn.m_channels)
5406  {
5407  case 0:
5408  /* nb: aac and mp3 seem to be coming up 0 here, may point to an
5409  * avformatdecoder audio channel handling bug, per janneg */
5410  case 1:
5411  case 2:
5412  /* all audio codecs have at *least* one channel, but
5413  * LR is the fewest LED we can light up */
5414  lcd->setSpeakerLEDs(SPEAKER_LR, true);
5415  break;
5416  case 3:
5417  case 4:
5418  case 5:
5419  case 6:
5420  lcd->setSpeakerLEDs(SPEAKER_51, true);
5421  break;
5422  default:
5423  lcd->setSpeakerLEDs(SPEAKER_71, true);
5424  break;
5425  }
5426 
5427  }
5428  return true;
5429 }
5430 
5432 {
5433  int64_t start_time = INT64_MAX;
5434  int64_t end_time = INT64_MIN;
5435  AVStream *st = nullptr;
5436 
5437  for (uint i = 0; i < ic->nb_streams; i++)
5438  {
5439  AVStream *st1 = ic->streams[i];
5440  if (st1 && st1->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
5441  {
5442  st = st1;
5443  break;
5444  }
5445  }
5446  if (!st)
5447  return;
5448 
5449  int64_t duration = INT64_MIN;
5450  if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
5451  int64_t start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
5452  if (start_time1 < start_time)
5453  start_time = start_time1;
5454  if (st->duration != AV_NOPTS_VALUE) {
5455  int64_t end_time1 = start_time1 +
5456  av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
5457  if (end_time1 > end_time)
5458  end_time = end_time1;
5459  }
5460  }
5461  if (st->duration != AV_NOPTS_VALUE) {
5462  int64_t duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
5463  if (duration1 > duration)
5464  duration = duration1;
5465  }
5466  if (start_time != INT64_MAX) {
5467  ic->start_time = start_time;
5468  if (end_time != INT64_MIN) {
5469  if (end_time - start_time > duration)
5470  duration = end_time - start_time;
5471  }
5472  }
5473  if (duration != INT64_MIN) {
5474  int64_t filesize = 0;
5475  ic->duration = duration;
5476  if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
5477  /* compute the bitrate */
5478  ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
5479  (double)ic->duration;
5480  }
5481  }
5482 }
5483 
5484 /* vim: set expandtab tabstop=4 shiftwidth=4: */
MythHDRVideoMetadata::Populate
static void Populate(class MythVideoFrame *Frame, struct AVFrame *AvFrame)
Create, update or destroy HDR metadata for the given MythVideoFrame.
Definition: mythhdrvideometadata.cpp:46
ProgramMapTable::ProgramInfo
const unsigned char * ProgramInfo(void) const
Definition: mpegtables.h:735
AvFormatDecoder::get_avf_buffer
friend int get_avf_buffer(struct AVCodecContext *c, AVFrame *pic, int flags)
Definition: avformatdecoder.cpp:2752
AvFormatDecoder::GetTrackDesc
QString GetTrackDesc(uint Type, uint TrackNo) override
Definition: avformatdecoder.cpp:4108
get_format_dxva2
static enum AVPixelFormat get_format_dxva2(struct AVCodecContext *, const enum AVPixelFormat *)
Definition: avformatdecoder.cpp:1405
TeletextDescriptor::TeletextMagazineNum
uint TeletextMagazineNum(uint i) const
Definition: dvbdescriptors.h:2363
AVRationalInit
AVRational AVRationalInit(int num, int den=1)
Definition: decoderbase.h:113
FORMAT_NONE
@ FORMAT_NONE
Definition: audiooutputsettings.h:26
AudioInfo::m_channels
int m_channels
Definition: avformatdecoder.h:62
VBI_IVTV
@ VBI_IVTV
Definition: vbilut.h:23
AVCParser
Definition: AVCParser.h:29
kDecodeAV
@ kDecodeAV
Definition: decoderbase.h:52
AudioOutput::kMaxSizeBuffer
static const int kMaxSizeBuffer
kMaxSizeBuffer is the maximum size of a buffer to be used with DecodeAudio
Definition: audiooutput.h:197
DecoderBase::DoFastForward
virtual bool DoFastForward(long long desiredFrame, bool discardFrames=true)
Skips ahead or rewinds to desiredFrame.
Definition: decoderbase.cpp:710
kAudioTypeHearingImpaired
@ kAudioTypeHearingImpaired
Definition: decoderbase.h:60
AvFormatDecoder::m_lastPtsForFaultDetection
int64_t m_lastPtsForFaultDetection
Definition: avformatdecoder.h:308
secondsFromFloat
std::enable_if_t< std::is_floating_point_v< T >, std::chrono::seconds > secondsFromFloat(T value)
Helper function for convert a floating point number to a duration.
Definition: mythchrono.h:80
MythTimer::elapsed
std::chrono::milliseconds elapsed(void)
Returns milliseconds elapsed since last start() or restart()
Definition: mythtimer.cpp:91
iso639_key_to_canonical_key
int iso639_key_to_canonical_key(int iso639_2)
Definition: iso639.cpp:118
CC608Decoder::SetIgnoreTimecode
void SetIgnoreTimecode(bool val)
Definition: cc608decoder.h:67
DecoderBase::SetTrack
virtual int SetTrack(uint Type, int TrackNo)
Definition: decoderbase.cpp:963
DecoderBase::m_readAdjust
long long m_readAdjust
Definition: decoderbase.h:348
AudioOutputSettings::AVSampleFormatToFormat
static AudioFormat AVSampleFormatToFormat(AVSampleFormat format, int bits=0)
Return AVSampleFormat closest equivalent to AudioFormat.
Definition: audiooutputsettings.cpp:197
AvFormatDecoder::GetRawEncodingType
QString GetRawEncodingType(void) override
Definition: avformatdecoder.cpp:5199
VIDEO_WMV
@ VIDEO_WMV
Definition: lcddevice.h:127
AvFormatDecoder::m_noDtsHack
bool m_noDtsHack
Definition: avformatdecoder.h:278
kDecoderProbeBufferSize
const int kDecoderProbeBufferSize
Definition: decoderbase.h:22
MythMediaBuffer::BestBufferSize
virtual int BestBufferSize(void)
Definition: mythmediabuffer.h:128
MythVideoFrame::m_colorspace
int m_colorspace
Definition: mythframe.h:148
AudioInfo::m_codecProfile
int m_codecProfile
Definition: avformatdecoder.h:63
MythPlayer::SetFileLength
void SetFileLength(std::chrono::seconds total, int frames)
Definition: mythplayer.cpp:387
MythMediaBuffer::SetBufferSizeFactors
void SetBufferSizeFactors(bool EstBitrate, bool Matroska)
Tells RingBuffer that the raw bitrate may be inaccurate and the underlying container is matroska,...
Definition: mythmediabuffer.cpp:328
AudioTrackType
AudioTrackType
Definition: decoderbase.h:55
InteractiveTV::ImageHasChanged
bool ImageHasChanged(void)
Definition: interactivetv.cpp:41
AudioInfo::m_codecId
AVCodecID m_codecId
Definition: avformatdecoder.h:58
MythVideoFrame::m_colortransfer
int m_colortransfer
Definition: mythframe.h:151
DecoderBase::m_selectedTrack
std::array< StreamInfo, kTrackTypeCount > m_selectedTrack
Definition: decoderbase.h:362
MythVideoFrame::m_interlaced
int m_interlaced
Definition: mythframe.h:134
AvFormatDecoder::av_update_stream_timings_video
static void av_update_stream_timings_video(AVFormatContext *ic)
Definition: avformatdecoder.cpp:5431
AvFormatDecoder::GetChapterTimes
void GetChapterTimes(QList< std::chrono::seconds > &times) override
Definition: avformatdecoder.cpp:486
error
static void error(const char *str,...)
Definition: vbi.cpp:42
DecoderBase::m_ringBuffer
MythMediaBuffer * m_ringBuffer
Definition: decoderbase.h:289
MythCodecContext::FindDecoder
static MythCodecID FindDecoder(const QString &Decoder, AVStream *Stream, AVCodecContext **Context, AVCodec **Codec)
Definition: mythcodeccontext.cpp:246
kScan_Detect
@ kScan_Detect
Definition: videoouttypes.h:97
MythDVDBuffer::GetAspectOverride
float GetAspectOverride(void) const
Definition: mythdvdbuffer.cpp:1146
StreamInfo::m_language_index
uint m_language_index
Definition: decoderbase.h:98
mpeg_version
uint mpeg_version(int codec_id)
Definition: mythcodecid.cpp:455
DecoderBase::PosMapEntry
Definition: decoderbase.h:278
AvFormatDecoder::SetTrack
int SetTrack(uint Type, int TrackNo) override
Definition: avformatdecoder.cpp:4096
AvFormatDecoder::m_doRewind
bool m_doRewind
Definition: avformatdecoder.h:279
MythVideoFrame::m_newGOP
bool m_newGOP
Definition: mythframe.h:137
ProgramMapTable::StreamCount
uint StreamCount(void) const
Definition: mpegtables.h:750
AvFormatDecoder::GetCurrentChapter
int GetCurrentChapter(long long framesPlayed) override
Definition: avformatdecoder.cpp:503
DecoderBase::m_currentWidth
int m_currentWidth
Definition: decoderbase.h:295
AudioInfo::m_sampleSize
int m_sampleSize
Definition: avformatdecoder.h:60
AvFormatDecoder::m_skipAudio
bool m_skipAudio
Definition: avformatdecoder.h:295
MythCodecMap::GetCodecContext
AVCodecContext * GetCodecContext(const AVStream *Stream, const AVCodec *Codec=nullptr, bool NullCodec=false)
Definition: mythavutil.cpp:250
AudioPlayer::ReinitAudio
QString ReinitAudio(void)
Definition: audioplayer.cpp:104
cc708_seen_flags
std::array< bool, 64 > cc708_seen_flags
Definition: cc708decoder.h:15
AvFormatDecoder::AutoSelectAudioTrack
int AutoSelectAudioTrack(void)
Selects the best audio track.
Definition: avformatdecoder.cpp:4368
DecoderBase::m_fps
double m_fps
Definition: decoderbase.h:291
MythTimer
A QElapsedTimer based timer to replace use of QTime as a timer.
Definition: mythtimer.h:13
audiooutpututil.h
AvFormatDecoder::m_gotVideoFrame
bool m_gotVideoFrame
Definition: avformatdecoder.h:292
CaptionServiceDescriptor::EasyReader
bool EasyReader(int i) const
Definition: atscdescriptors.h:113
AvFormatDecoder::UpdateFramesPlayed
void UpdateFramesPlayed(void) override
Definition: avformatdecoder.cpp:2558
AvFormatDecoder::m_lastScteField
uint m_lastScteField
Definition: avformatdecoder.h:328
AvFormatDecoder::m_storedPackets
QList< AVPacket * > m_storedPackets
Definition: avformatdecoder.h:287
AvFormatDecoder::SetEof
void SetEof(bool eof) override
Definition: avformatdecoder.cpp:820
kCodec_NONE
@ kCodec_NONE
Definition: mythcodecid.h:14
TeletextDecoder::Decode
void Decode(const unsigned char *buf, int vbimode)
Decodes teletext data.
Definition: teletextdecoder.cpp:40
MythVideoFrame::ClearBufferToBlank
void ClearBufferToBlank()
Definition: mythframe.cpp:205
MythVideoFrame::m_chromalocation
int m_chromalocation
Definition: mythframe.h:152
InteractiveTV::SetNetBootInfo
void SetNetBootInfo(const unsigned char *data, uint length)
Definition: interactivetv.cpp:77
DecoderBase::m_videoRotation
int m_videoRotation
Definition: decoderbase.h:349
AvFormatDecoder::GetAttachmentData
void GetAttachmentData(uint TrackNo, QByteArray &Filename, QByteArray &Data) override
Definition: avformatdecoder.cpp:4207
CC608Decoder::FormatCC
void FormatCC(std::chrono::milliseconds tc, int code1, int code2)
Definition: cc608decoder.cpp:49
DecoderBase::m_stereo3D
uint m_stereo3D
Definition: decoderbase.h:350
CaptionServiceDescriptor
Definition: atscdescriptors.h:74
AvFormatDecoder::m_itv
InteractiveTV * m_itv
MHEG/MHP decoder.
Definition: avformatdecoder.h:353
StreamInfo::m_av_stream_index
int m_av_stream_index
Definition: decoderbase.h:94
AudioInfo::toString
QString toString() const
Definition: avformatdecoder.h:75
AvFormatDecoder::m_maxKeyframeDist
int m_maxKeyframeDist
Definition: avformatdecoder.h:322
DecoderBase::AutoSelectTrack
virtual int AutoSelectTrack(uint Type)
Select best track.
Definition: decoderbase.cpp:1054
AvFormatDecoder::RemoveAudioStreams
void RemoveAudioStreams()
remove audio streams from the context used by dvd code during title transitions to remove stale audio...
Definition: avformatdecoder.cpp:2730
x2
static int x2
Definition: mythsocket.cpp:58
MythPlayer::GetInteractiveTV
virtual InteractiveTV * GetInteractiveTV()
Definition: mythplayer.h:167
DecoderBase::m_atEof
EofState m_atEof
Definition: decoderbase.h:309
ProgramMapTable::StreamInfo
const unsigned char * StreamInfo(uint i) const
Definition: mpegtables.h:747
DecoderBase::m_bitrate
uint m_bitrate
Definition: decoderbase.h:294
DecoderBase::m_parent
MythPlayer * m_parent
Definition: decoderbase.h:286
SLICE_MAX
#define SLICE_MAX
Definition: avformatdecoder.cpp:3121
AvFormatDecoder::NormalizeVideoTimecode
std::chrono::milliseconds NormalizeVideoTimecode(std::chrono::milliseconds timecode) override
Definition: avformatdecoder.cpp:423
MythVideoFrame::m_frameCounter
uint64_t m_frameCounter
Definition: mythframe.h:130
AvFormatDecoder::DecoderWillDownmix
bool DecoderWillDownmix(const AVCodecContext *ctx)
Definition: avformatdecoder.cpp:5232
mythtvexp.h
StreamInfo::m_stream_id
int m_stream_id
Definition: decoderbase.h:99
kTrackTypeTeletextMenu
@ kTrackTypeTeletextMenu
Definition: decoderbase.h:35
MythDVDBuffer::DecodeSubtitles
bool DecodeSubtitles(AVSubtitle *Subtitle, int *GotSubtitles, const uint8_t *SpuPkt, int BufSize, uint32_t StartTime)
generate dvd subtitle bitmap or dvd menu bitmap.
Definition: mythdvdbuffer.cpp:1452
kTrackTypeAttachment
@ kTrackTypeAttachment
Definition: decoderbase.h:37
cc708decoder.h
AvFormatDecoder::SetAudioByComponentTag
bool SetAudioByComponentTag(int Tag) override
Definition: avformatdecoder.cpp:4221
CC608Decoder
Definition: cc608decoder.h:53
ProgramMapTable
A PMT table maps a program described in the ProgramAssociationTable to various PID's which describe t...
Definition: mpegtables.h:692
MythAVFrame
MythAVFrame little utility class that act as a safe way to allocate an AVFrame which can then be allo...
Definition: mythaverror.h:52
TeletextDecoder
Definition: teletextdecoder.h:8
H2645Parser::FIELD_BOTTOM
@ FIELD_BOTTOM
Definition: H2645Parser.h:83
mythdvdbuffer.h
SPEAKER_71
@ SPEAKER_71
Definition: lcddevice.h:103
DecoderBase::m_livetv
bool m_livetv
Definition: decoderbase.h:336
codec_is_nvdec
#define codec_is_nvdec(id)
Definition: mythcodecid.h:328
AvFormatDecoder::SetIdrOnlyKeyframes
void SetIdrOnlyKeyframes(bool value) override
Definition: avformatdecoder.h:159
DEINT_NONE
@ DEINT_NONE
Definition: mythframe.h:69
MythCodecContext::CreateContext
static MythCodecContext * CreateContext(DecoderBase *Parent, MythCodecID Codec)
Definition: mythcodeccontext.cpp:73
AvFormatDecoder::m_faultyPts
int64_t m_faultyPts
Definition: avformatdecoder.h:306
microsecondsFromFloat
std::enable_if_t< std::is_floating_point_v< T >, std::chrono::microseconds > microsecondsFromFloat(T value)
Helper function for convert a floating point number to a duration.
Definition: mythchrono.h:102
DecoderBase::GetSeekSnap
uint64_t GetSeekSnap(void) const
Definition: decoderbase.h:138
mythdbcon.h
SPEAKER_LR
@ SPEAKER_LR
Definition: lcddevice.h:101
AvFormatDecoder::m_ccX08InTracks
std::array< bool, 68 > m_ccX08InTracks
Lookup table for whether a stream is represented in the UI entries 0-3 correspond to CEA-608 CC1 thro...
Definition: avformatdecoder.h:340
AudioOutputSettings::SampleSize
static int SampleSize(AudioFormat format)
Definition: audiooutputsettings.cpp:179
DecoderBase::ResetTracks
void ResetTracks(void)
Definition: decoderbase.cpp:1151
ProgramMapTable::IsVideo
bool IsVideo(uint i, const QString &sistandard) const
Returns true iff the stream at index i is a video stream.
Definition: mpegtables.cpp:513
AvFormatDecoder::m_audioSamples
uint8_t * m_audioSamples
Definition: avformatdecoder.h:356
DecoderBase::m_hasFullPositionMap
bool m_hasFullPositionMap
Definition: decoderbase.h:319
DescriptorID::caption_service
@ caption_service
Definition: mpegdescriptors.h:163
AudioPlayer::IsBufferAlmostFull
bool IsBufferAlmostFull(void)
Definition: audioplayer.cpp:493
mythhdrvideometadata.h
MythCodecContext::InitVideoCodec
virtual void InitVideoCodec(AVCodecContext *Context, bool SelectedStream, bool &DirectRendering)
Definition: mythcodeccontext.cpp:302
cc608_build_parity_table
static void cc608_build_parity_table(CC608Parity &parity_table)
Definition: avformatdecoder.cpp:1638
MythDate::Format
Format
Definition: mythdate.h:15
SubtitleReader::AddAVSubtitle
bool AddAVSubtitle(AVSubtitle &subtitle, bool fix_position, bool allow_forced)
Definition: subtitlereader.cpp:35
MythVideoFrame::m_width
int m_width
Definition: mythframe.h:121
CC708Decoder::decode_cc_data
void decode_cc_data(uint cc_type, uint data1, uint data2)
Definition: cc708decoder.cpp:40
AvFormatDecoder::GetTeletextDecoderType
int GetTeletextDecoderType(void) const override
Definition: avformatdecoder.cpp:4185
MythMediaBuffer
Definition: mythmediabuffer.h:50
MythMediaBuffer::IgnoreWaitStates
virtual void IgnoreWaitStates(bool)
Definition: mythmediabuffer.h:130
MythPlayer::IsErrored
bool IsErrored(void) const
Definition: mythplayer.cpp:1984
MythMediaBuffer::IsDVD
bool IsDVD(void) const
Definition: mythmediabuffer.cpp:1830
AvFormatDecoder::IsValidStream
virtual bool IsValidStream(int)
Definition: avformatdecoder.h:253
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:23
VIDEO_XVID
@ VIDEO_XVID
Definition: lcddevice.h:126
DecoderBase::m_videoDisplayProfile
MythVideoProfile m_videoDisplayProfile
Definition: decoderbase.h:367
myth_av_log
static void myth_av_log(void *ptr, int level, const char *fmt, va_list vl)
Definition: avformatdecoder.cpp:237
AudioPlayer::HasAudioOut
bool HasAudioOut(void) const
Definition: audioplayer.h:58
MythMediaBuffer::GetReadBufAvail
int GetReadBufAvail(void) const
Returns number of bytes available for reading from buffer.
Definition: mythmediabuffer.cpp:455
TrackType
TrackType
Track types.
Definition: decoderbase.h:26
AvFormatDecoder::m_seenGop
bool m_seenGop
A flag to indicate that we've seen a GOP frame. Used in junction with seq_count.
Definition: avformatdecoder.h:283
DecoderBase::m_trackLock
QRecursiveMutex m_trackLock
Definition: decoderbase.h:356
kAudioTypeCleanEffects
@ kAudioTypeCleanEffects
Definition: decoderbase.h:59
LOC
#define LOC
Definition: avformatdecoder.cpp:88
mythplayer.h
CC708Decoder
Definition: cc708decoder.h:29
DecoderBase::m_positionMapType
MarkTypes m_positionMapType
Definition: decoderbase.h:322
MythCodecContext::DecoderWillResetOnFlush
virtual bool DecoderWillResetOnFlush(void)
Definition: mythcodeccontext.h:159
AUDIO_WMA2
@ AUDIO_WMA2
Definition: lcddevice.h:112
build_compdb.parser
parser
Definition: build_compdb.py:7
PlayerFlags
PlayerFlags
Definition: mythplayer.h:65
cc608_good_parity
static int cc608_good_parity(const CC608Parity &parity_table, uint16_t data)
Definition: avformatdecoder.cpp:1652
subtitlereader.h
MythPlayer
Definition: mythplayer.h:86
AvFormatDecoder::SeekReset
void SeekReset(long long newkey, uint skipFrames, bool doFlush, bool discardFrames) override
Definition: avformatdecoder.cpp:676
kDecodeLowRes
@ kDecodeLowRes
Definition: mythplayer.h:68
MythVideoFrame::m_offsets
FrameOffsets m_offsets
Definition: mythframe.h:143
VBI_TYPE_CC
#define VBI_TYPE_CC
Definition: ivtv_myth.h:29
NULL
#define NULL
Definition: H2645Parser.h:67
DecoderBase::m_exitAfterDecoded
bool m_exitAfterDecoded
Definition: decoderbase.h:316
AvFormatDecoder::GetChapter
long long GetChapter(int chapter) override
Definition: avformatdecoder.cpp:527
DescriptorID::teletext
@ teletext
Definition: mpegdescriptors.h:95
MythMediaBuffer::UpdateRawBitrate
void UpdateRawBitrate(uint RawBitrate)
Set the raw bit rate, to allow RingBuffer adjust effective bitrate.
Definition: mythmediabuffer.cpp:277
AvFormatDecoder::m_readContext
URLContext m_readContext
Definition: avformatdecoder.h:269
AvFormatDecoder::FindStreamInfo
int FindStreamInfo(void)
Definition: avformatdecoder.cpp:913
AvFormatDecoder::ScanATSCCaptionStreams
void ScanATSCCaptionStreams(int av_index)
Definition: avformatdecoder.cpp:1664
iso639_key_toName
QString iso639_key_toName(int iso639_2)
Converts a canonical key to language name in English.
Definition: iso639.cpp:109
sinfo_vec_t
std::vector< StreamInfo > sinfo_vec_t
Definition: decoderbase.h:111
CC608Seen
std::array< bool, 4 > CC608Seen
Definition: cc608decoder.h:23
DecoderBase::m_frameToDurMap
frm_pos_map_t m_frameToDurMap
Definition: decoderbase.h:330
AvFormatDecoder::m_ignoreScte
uint m_ignoreScte
Definition: avformatdecoder.h:326
InteractiveTV::GetInitialStreams
void GetInitialStreams(int &audioTag, int &videoTag)
Definition: interactivetv.cpp:72
AvFormatDecoder::GetSubHeader
QByteArray GetSubHeader(uint TrackNo) override
Definition: avformatdecoder.cpp:4195