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