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