vdr  2.4.0
remux.c
Go to the documentation of this file.
1 /*
2  * remux.c: Tools for detecting frames and handling PAT/PMT
3  *
4  * See the main source file 'vdr.c' for copyright information and
5  * how to reach the author.
6  *
7  * $Id: remux.c 4.7 2017/04/29 12:25:09 kls Exp $
8  */
9 
10 #include "remux.h"
11 #include "device.h"
12 #include "libsi/si.h"
13 #include "libsi/section.h"
14 #include "libsi/descriptor.h"
15 #include "recording.h"
16 #include "shutdown.h"
17 #include "tools.h"
18 
19 // Set these to 'true' for debug output:
20 static bool DebugPatPmt = false;
21 static bool DebugFrames = false;
22 
23 #define dbgpatpmt(a...) if (DebugPatPmt) fprintf(stderr, a)
24 #define dbgframes(a...) if (DebugFrames) fprintf(stderr, a)
25 
26 #define MAX_TS_PACKETS_FOR_VIDEO_FRAME_DETECTION 6
27 #define WRN_TS_PACKETS_FOR_VIDEO_FRAME_DETECTION (MAX_TS_PACKETS_FOR_VIDEO_FRAME_DETECTION / 2)
28 #define WRN_TS_PACKETS_FOR_FRAME_DETECTOR (MIN_TS_PACKETS_FOR_FRAME_DETECTOR / 2)
29 
30 #define EMPTY_SCANNER (0xFFFFFFFF)
31 
32 ePesHeader AnalyzePesHeader(const uchar *Data, int Count, int &PesPayloadOffset, bool *ContinuationHeader)
33 {
34  if (Count < 7)
35  return phNeedMoreData; // too short
36 
37  if ((Data[6] & 0xC0) == 0x80) { // MPEG 2
38  if (Count < 9)
39  return phNeedMoreData; // too short
40 
41  PesPayloadOffset = 6 + 3 + Data[8];
42  if (Count < PesPayloadOffset)
43  return phNeedMoreData; // too short
44 
45  if (ContinuationHeader)
46  *ContinuationHeader = ((Data[6] == 0x80) && !Data[7] && !Data[8]);
47 
48  return phMPEG2; // MPEG 2
49  }
50 
51  // check for MPEG 1 ...
52  PesPayloadOffset = 6;
53 
54  // skip up to 16 stuffing bytes
55  for (int i = 0; i < 16; i++) {
56  if (Data[PesPayloadOffset] != 0xFF)
57  break;
58 
59  if (Count <= ++PesPayloadOffset)
60  return phNeedMoreData; // too short
61  }
62 
63  // skip STD_buffer_scale/size
64  if ((Data[PesPayloadOffset] & 0xC0) == 0x40) {
65  PesPayloadOffset += 2;
66 
67  if (Count <= PesPayloadOffset)
68  return phNeedMoreData; // too short
69  }
70 
71  if (ContinuationHeader)
72  *ContinuationHeader = false;
73 
74  if ((Data[PesPayloadOffset] & 0xF0) == 0x20) {
75  // skip PTS only
76  PesPayloadOffset += 5;
77  }
78  else if ((Data[PesPayloadOffset] & 0xF0) == 0x30) {
79  // skip PTS and DTS
80  PesPayloadOffset += 10;
81  }
82  else if (Data[PesPayloadOffset] == 0x0F) {
83  // continuation header
85 
86  if (ContinuationHeader)
87  *ContinuationHeader = true;
88  }
89  else
90  return phInvalid; // unknown
91 
92  if (Count < PesPayloadOffset)
93  return phNeedMoreData; // too short
94 
95  return phMPEG1; // MPEG 1
96 }
97 
98 #define VIDEO_STREAM_S 0xE0
99 
100 // --- cRemux ----------------------------------------------------------------
101 
102 void cRemux::SetBrokenLink(uchar *Data, int Length)
103 {
104  int PesPayloadOffset = 0;
105  if (AnalyzePesHeader(Data, Length, PesPayloadOffset) >= phMPEG1 && (Data[3] & 0xF0) == VIDEO_STREAM_S) {
106  for (int i = PesPayloadOffset; i < Length - 7; i++) {
107  if (Data[i] == 0 && Data[i + 1] == 0 && Data[i + 2] == 1 && Data[i + 3] == 0xB8) {
108  if (!(Data[i + 7] & 0x40)) // set flag only if GOP is not closed
109  Data[i + 7] |= 0x20;
110  return;
111  }
112  }
113  dsyslog("SetBrokenLink: no GOP header found in video packet");
114  }
115  else
116  dsyslog("SetBrokenLink: no video packet in frame");
117 }
118 
119 // --- Some TS handling tools ------------------------------------------------
120 
122 {
123  p[1] &= ~TS_PAYLOAD_START;
124  p[3] |= TS_ADAPT_FIELD_EXISTS;
125  p[3] &= ~TS_PAYLOAD_EXISTS;
126  p[4] = TS_SIZE - 5;
127  p[5] = 0x00;
128  memset(p + 6, 0xFF, TS_SIZE - 6);
129 }
130 
131 void TsSetPcr(uchar *p, int64_t Pcr)
132 {
133  if (TsHasAdaptationField(p)) {
134  if (p[4] >= 7 && (p[5] & TS_ADAPT_PCR)) {
135  int64_t b = Pcr / PCRFACTOR;
136  int e = Pcr % PCRFACTOR;
137  p[ 6] = b >> 25;
138  p[ 7] = b >> 17;
139  p[ 8] = b >> 9;
140  p[ 9] = b >> 1;
141  p[10] = (b << 7) | (p[10] & 0x7E) | ((e >> 8) & 0x01);
142  p[11] = e;
143  }
144  }
145 }
146 
147 int TsSync(const uchar *Data, int Length, const char *File, const char *Function, int Line)
148 {
149  int Skipped = 0;
150  while (Length > 0 && (*Data != TS_SYNC_BYTE || Length > TS_SIZE && Data[TS_SIZE] != TS_SYNC_BYTE)) {
151  Data++;
152  Length--;
153  Skipped++;
154  }
155  if (Skipped && File && Function && Line)
156  esyslog("ERROR: skipped %d bytes to sync on start of TS packet at %s/%s(%d)", Skipped, File, Function, Line);
157  return Skipped;
158 }
159 
160 int64_t TsGetPts(const uchar *p, int l)
161 {
162  // Find the first packet with a PTS and use it:
163  while (l > 0) {
164  const uchar *d = p;
165  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasPts(d))
166  return PesGetPts(d);
167  p += TS_SIZE;
168  l -= TS_SIZE;
169  }
170  return -1;
171 }
172 
173 int64_t TsGetDts(const uchar *p, int l)
174 {
175  // Find the first packet with a DTS and use it:
176  while (l > 0) {
177  const uchar *d = p;
178  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasDts(d))
179  return PesGetDts(d);
180  p += TS_SIZE;
181  l -= TS_SIZE;
182  }
183  return -1;
184 }
185 
186 void TsSetPts(uchar *p, int l, int64_t Pts)
187 {
188  // Find the first packet with a PTS and use it:
189  while (l > 0) {
190  const uchar *d = p;
191  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasPts(d)) {
192  PesSetPts(const_cast<uchar *>(d), Pts);
193  return;
194  }
195  p += TS_SIZE;
196  l -= TS_SIZE;
197  }
198 }
199 
200 void TsSetDts(uchar *p, int l, int64_t Dts)
201 {
202  // Find the first packet with a DTS and use it:
203  while (l > 0) {
204  const uchar *d = p;
205  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasDts(d)) {
206  PesSetDts(const_cast<uchar *>(d), Dts);
207  return;
208  }
209  p += TS_SIZE;
210  l -= TS_SIZE;
211  }
212 }
213 
214 // --- Some PES handling tools -----------------------------------------------
215 
216 void PesSetPts(uchar *p, int64_t Pts)
217 {
218  p[ 9] = ((Pts >> 29) & 0x0E) | (p[9] & 0xF1);
219  p[10] = Pts >> 22;
220  p[11] = ((Pts >> 14) & 0xFE) | 0x01;
221  p[12] = Pts >> 7;
222  p[13] = ((Pts << 1) & 0xFE) | 0x01;
223 }
224 
225 void PesSetDts(uchar *p, int64_t Dts)
226 {
227  p[14] = ((Dts >> 29) & 0x0E) | (p[14] & 0xF1);
228  p[15] = Dts >> 22;
229  p[16] = ((Dts >> 14) & 0xFE) | 0x01;
230  p[17] = Dts >> 7;
231  p[18] = ((Dts << 1) & 0xFE) | 0x01;
232 }
233 
234 int64_t PtsDiff(int64_t Pts1, int64_t Pts2)
235 {
236  int64_t d = Pts2 - Pts1;
237  if (d > MAX33BIT / 2)
238  return d - (MAX33BIT + 1);
239  if (d < -MAX33BIT / 2)
240  return d + (MAX33BIT + 1);
241  return d;
242 }
243 
244 // --- cTsPayload ------------------------------------------------------------
245 
247 {
248  data = NULL;
249  length = 0;
250  pid = -1;
251  Reset();
252 }
253 
254 cTsPayload::cTsPayload(uchar *Data, int Length, int Pid)
255 {
256  Setup(Data, Length, Pid);
257 }
258 
260 {
261  length = index; // triggers EOF
262  return 0x00;
263 }
264 
266 {
267  index = 0;
268  numPacketsPid = 0;
269  numPacketsOther = 0;
270 }
271 
272 void cTsPayload::Setup(uchar *Data, int Length, int Pid)
273 {
274  data = Data;
275  length = Length;
276  pid = Pid >= 0 ? Pid : TsPid(Data);
277  Reset();
278 }
279 
281 {
282  if (!Eof()) {
283  if (index % TS_SIZE == 0) { // encountered the next TS header
284  for (;; index += TS_SIZE) {
285  if (data[index] == TS_SYNC_BYTE && index + TS_SIZE <= length) { // to make sure we are at a TS header start and drop incomplete TS packets at the end
286  uchar *p = data + index;
287  if (TsPid(p) == pid) { // only handle TS packets for the initial PID
289  return SetEof();
290  if (TsHasPayload(p)) {
291  if (index > 0 && TsPayloadStart(p)) // checking index to not skip the very first TS packet
292  return SetEof();
293  index += TsPayloadOffset(p);
294  break;
295  }
296  }
297  else if (TsPid(p) == PATPID)
298  return SetEof(); // caller must see PAT packets in case of index regeneration
299  else
300  numPacketsOther++;
301  }
302  else
303  return SetEof();
304  }
305  }
306  return data[index++];
307  }
308  return 0x00;
309 }
310 
311 bool cTsPayload::SkipBytes(int Bytes)
312 {
313  while (Bytes-- > 0)
314  GetByte();
315  return !Eof();
316 }
317 
319 {
321 }
322 
324 {
325  return index - 1;
326 }
327 
328 void cTsPayload::SetByte(uchar Byte, int Index)
329 {
330  if (Index >= 0 && Index < length)
331  data[Index] = Byte;
332 }
333 
334 bool cTsPayload::Find(uint32_t Code)
335 {
336  int OldIndex = index;
337  int OldNumPacketsPid = numPacketsPid;
338  int OldNumPacketsOther = numPacketsOther;
339  uint32_t Scanner = EMPTY_SCANNER;
340  while (!Eof()) {
341  Scanner = (Scanner << 8) | GetByte();
342  if (Scanner == Code)
343  return true;
344  }
345  index = OldIndex;
346  numPacketsPid = OldNumPacketsPid;
347  numPacketsOther = OldNumPacketsOther;
348  return false;
349 }
350 
351 void cTsPayload::Statistics(void) const
352 {
354  dsyslog("WARNING: required (%d+%d) TS packets to determine frame type", numPacketsOther, numPacketsPid);
356  dsyslog("WARNING: required %d video TS packets to determine frame type", numPacketsPid);
357 }
358 
359 // --- cPatPmtGenerator ------------------------------------------------------
360 
362 {
363  numPmtPackets = 0;
364  patCounter = pmtCounter = 0;
365  patVersion = pmtVersion = 0;
366  pmtPid = 0;
367  esInfoLength = NULL;
368  SetChannel(Channel);
369 }
370 
371 void cPatPmtGenerator::IncCounter(int &Counter, uchar *TsPacket)
372 {
373  TsPacket[3] = (TsPacket[3] & 0xF0) | Counter;
374  if (++Counter > 0x0F)
375  Counter = 0x00;
376 }
377 
379 {
380  if (++Version > 0x1F)
381  Version = 0x00;
382 }
383 
385 {
386  if (esInfoLength) {
387  Length += ((*esInfoLength & 0x0F) << 8) | *(esInfoLength + 1);
388  *esInfoLength = 0xF0 | (Length >> 8);
389  *(esInfoLength + 1) = Length;
390  }
391 }
392 
393 int cPatPmtGenerator::MakeStream(uchar *Target, uchar Type, int Pid)
394 {
395  int i = 0;
396  Target[i++] = Type; // stream type
397  Target[i++] = 0xE0 | (Pid >> 8); // dummy (3), pid hi (5)
398  Target[i++] = Pid; // pid lo
399  esInfoLength = &Target[i];
400  Target[i++] = 0xF0; // dummy (4), ES info length hi
401  Target[i++] = 0x00; // ES info length lo
402  return i;
403 }
404 
406 {
407  int i = 0;
408  Target[i++] = Type;
409  Target[i++] = 0x01; // length
410  Target[i++] = 0x00;
411  IncEsInfoLength(i);
412  return i;
413 }
414 
415 int cPatPmtGenerator::MakeSubtitlingDescriptor(uchar *Target, const char *Language, uchar SubtitlingType, uint16_t CompositionPageId, uint16_t AncillaryPageId)
416 {
417  int i = 0;
418  Target[i++] = SI::SubtitlingDescriptorTag;
419  Target[i++] = 0x08; // length
420  Target[i++] = *Language++;
421  Target[i++] = *Language++;
422  Target[i++] = *Language++;
423  Target[i++] = SubtitlingType;
424  Target[i++] = CompositionPageId >> 8;
425  Target[i++] = CompositionPageId & 0xFF;
426  Target[i++] = AncillaryPageId >> 8;
427  Target[i++] = AncillaryPageId & 0xFF;
428  IncEsInfoLength(i);
429  return i;
430 }
431 
432 int cPatPmtGenerator::MakeLanguageDescriptor(uchar *Target, const char *Language)
433 {
434  int i = 0;
435  Target[i++] = SI::ISO639LanguageDescriptorTag;
436  int Length = i++;
437  Target[Length] = 0x00; // length
438  for (const char *End = Language + strlen(Language); Language < End; ) {
439  Target[i++] = *Language++;
440  Target[i++] = *Language++;
441  Target[i++] = *Language++;
442  Target[i++] = 0x00; // audio type
443  Target[Length] += 0x04; // length
444  if (*Language == '+')
445  Language++;
446  }
447  IncEsInfoLength(i);
448  return i;
449 }
450 
451 int cPatPmtGenerator::MakeCRC(uchar *Target, const uchar *Data, int Length)
452 {
453  int crc = SI::CRC32::crc32((const char *)Data, Length, 0xFFFFFFFF);
454  int i = 0;
455  Target[i++] = crc >> 24;
456  Target[i++] = crc >> 16;
457  Target[i++] = crc >> 8;
458  Target[i++] = crc;
459  return i;
460 }
461 
462 #define P_TSID 0x8008 // pseudo TS ID
463 #define P_PMT_PID 0x0084 // pseudo PMT pid
464 #define MAXPID 0x2000 // the maximum possible number of pids
465 
467 {
468  bool Used[MAXPID] = { false };
469 #define SETPID(p) { if ((p) >= 0 && (p) < MAXPID) Used[p] = true; }
470 #define SETPIDS(l) { const int *p = l; while (*p) { SETPID(*p); p++; } }
471  SETPID(Channel->Vpid());
472  SETPID(Channel->Ppid());
473  SETPID(Channel->Tpid());
474  SETPIDS(Channel->Apids());
475  SETPIDS(Channel->Dpids());
476  SETPIDS(Channel->Spids());
477  for (pmtPid = P_PMT_PID; Used[pmtPid]; pmtPid++)
478  ;
479 }
480 
482 {
483  memset(pat, 0xFF, sizeof(pat));
484  uchar *p = pat;
485  int i = 0;
486  p[i++] = TS_SYNC_BYTE; // TS indicator
487  p[i++] = TS_PAYLOAD_START | (PATPID >> 8); // flags (3), pid hi (5)
488  p[i++] = PATPID & 0xFF; // pid lo
489  p[i++] = 0x10; // flags (4), continuity counter (4)
490  p[i++] = 0x00; // pointer field (payload unit start indicator is set)
491  int PayloadStart = i;
492  p[i++] = 0x00; // table id
493  p[i++] = 0xB0; // section syntax indicator (1), dummy (3), section length hi (4)
494  int SectionLength = i;
495  p[i++] = 0x00; // section length lo (filled in later)
496  p[i++] = P_TSID >> 8; // TS id hi
497  p[i++] = P_TSID & 0xFF; // TS id lo
498  p[i++] = 0xC1 | (patVersion << 1); // dummy (2), version number (5), current/next indicator (1)
499  p[i++] = 0x00; // section number
500  p[i++] = 0x00; // last section number
501  p[i++] = pmtPid >> 8; // program number hi
502  p[i++] = pmtPid & 0xFF; // program number lo
503  p[i++] = 0xE0 | (pmtPid >> 8); // dummy (3), PMT pid hi (5)
504  p[i++] = pmtPid & 0xFF; // PMT pid lo
505  pat[SectionLength] = i - SectionLength - 1 + 4; // -1 = SectionLength storage, +4 = length of CRC
506  MakeCRC(pat + i, pat + PayloadStart, i - PayloadStart);
508 }
509 
511 {
512  // generate the complete PMT section:
513  uchar buf[MAX_SECTION_SIZE];
514  memset(buf, 0xFF, sizeof(buf));
515  numPmtPackets = 0;
516  if (Channel) {
517  int Vpid = Channel->Vpid();
518  int Ppid = Channel->Ppid();
519  uchar *p = buf;
520  int i = 0;
521  p[i++] = 0x02; // table id
522  int SectionLength = i;
523  p[i++] = 0xB0; // section syntax indicator (1), dummy (3), section length hi (4)
524  p[i++] = 0x00; // section length lo (filled in later)
525  p[i++] = pmtPid >> 8; // program number hi
526  p[i++] = pmtPid & 0xFF; // program number lo
527  p[i++] = 0xC1 | (pmtVersion << 1); // dummy (2), version number (5), current/next indicator (1)
528  p[i++] = 0x00; // section number
529  p[i++] = 0x00; // last section number
530  p[i++] = 0xE0 | (Ppid >> 8); // dummy (3), PCR pid hi (5)
531  p[i++] = Ppid; // PCR pid lo
532  p[i++] = 0xF0; // dummy (4), program info length hi (4)
533  p[i++] = 0x00; // program info length lo
534 
535  if (Vpid)
536  i += MakeStream(buf + i, Channel->Vtype(), Vpid);
537  for (int n = 0; Channel->Apid(n); n++) {
538  i += MakeStream(buf + i, Channel->Atype(n), Channel->Apid(n));
539  const char *Alang = Channel->Alang(n);
540  i += MakeLanguageDescriptor(buf + i, Alang);
541  }
542  for (int n = 0; Channel->Dpid(n); n++) {
543  i += MakeStream(buf + i, 0x06, Channel->Dpid(n));
544  i += MakeAC3Descriptor(buf + i, Channel->Dtype(n));
545  i += MakeLanguageDescriptor(buf + i, Channel->Dlang(n));
546  }
547  for (int n = 0; Channel->Spid(n); n++) {
548  i += MakeStream(buf + i, 0x06, Channel->Spid(n));
549  i += MakeSubtitlingDescriptor(buf + i, Channel->Slang(n), Channel->SubtitlingType(n), Channel->CompositionPageId(n), Channel->AncillaryPageId(n));
550  }
551 
552  int sl = i - SectionLength - 2 + 4; // -2 = SectionLength storage, +4 = length of CRC
553  buf[SectionLength] |= (sl >> 8) & 0x0F;
554  buf[SectionLength + 1] = sl;
555  MakeCRC(buf + i, buf, i);
556  // split the PMT section into several TS packets:
557  uchar *q = buf;
558  bool pusi = true;
559  while (i > 0) {
560  uchar *p = pmt[numPmtPackets++];
561  int j = 0;
562  p[j++] = TS_SYNC_BYTE; // TS indicator
563  p[j++] = (pusi ? TS_PAYLOAD_START : 0x00) | (pmtPid >> 8); // flags (3), pid hi (5)
564  p[j++] = pmtPid & 0xFF; // pid lo
565  p[j++] = 0x10; // flags (4), continuity counter (4)
566  if (pusi) {
567  p[j++] = 0x00; // pointer field (payload unit start indicator is set)
568  pusi = false;
569  }
570  int l = TS_SIZE - j;
571  memcpy(p + j, q, l);
572  q += l;
573  i -= l;
574  }
576  }
577 }
578 
579 void cPatPmtGenerator::SetVersions(int PatVersion, int PmtVersion)
580 {
581  patVersion = PatVersion & 0x1F;
582  pmtVersion = PmtVersion & 0x1F;
583 }
584 
586 {
587  if (Channel) {
588  GeneratePmtPid(Channel);
589  GeneratePat();
590  GeneratePmt(Channel);
591  }
592 }
593 
595 {
597  return pat;
598 }
599 
601 {
602  if (Index < numPmtPackets) {
603  IncCounter(pmtCounter, pmt[Index]);
604  return pmt[Index++];
605  }
606  return NULL;
607 }
608 
609 // --- cPatPmtParser ---------------------------------------------------------
610 
611 cPatPmtParser::cPatPmtParser(bool UpdatePrimaryDevice)
612 {
613  updatePrimaryDevice = UpdatePrimaryDevice;
614  Reset();
615 }
616 
618 {
619  completed = false;
620  pmtSize = 0;
621  patVersion = pmtVersion = -1;
622  pmtPids[0] = 0;
623  vpid = vtype = 0;
624  ppid = 0;
625 }
626 
627 void cPatPmtParser::ParsePat(const uchar *Data, int Length)
628 {
629  // Unpack the TS packet:
630  int PayloadOffset = TsPayloadOffset(Data);
631  Data += PayloadOffset;
632  Length -= PayloadOffset;
633  // The PAT is always assumed to fit into a single TS packet
634  if ((Length -= Data[0] + 1) <= 0)
635  return;
636  Data += Data[0] + 1; // process pointer_field
637  SI::PAT Pat(Data, false);
638  if (Pat.CheckCRCAndParse()) {
639  dbgpatpmt("PAT: TSid = %d, c/n = %d, v = %d, s = %d, ls = %d\n", Pat.getTransportStreamId(), Pat.getCurrentNextIndicator(), Pat.getVersionNumber(), Pat.getSectionNumber(), Pat.getLastSectionNumber());
640  if (patVersion == Pat.getVersionNumber())
641  return;
642  int NumPmtPids = 0;
643  SI::PAT::Association assoc;
644  for (SI::Loop::Iterator it; Pat.associationLoop.getNext(assoc, it); ) {
645  dbgpatpmt(" isNITPid = %d\n", assoc.isNITPid());
646  if (!assoc.isNITPid()) {
647  if (NumPmtPids <= MAX_PMT_PIDS)
648  pmtPids[NumPmtPids++] = assoc.getPid();
649  dbgpatpmt(" service id = %d, pid = %d\n", assoc.getServiceId(), assoc.getPid());
650  }
651  }
652  pmtPids[NumPmtPids] = 0;
654  }
655  else
656  esyslog("ERROR: can't parse PAT");
657 }
658 
659 void cPatPmtParser::ParsePmt(const uchar *Data, int Length)
660 {
661  // Unpack the TS packet:
662  bool PayloadStart = TsPayloadStart(Data);
663  int PayloadOffset = TsPayloadOffset(Data);
664  Data += PayloadOffset;
665  Length -= PayloadOffset;
666  // The PMT may extend over several TS packets, so we need to assemble them
667  if (PayloadStart) {
668  pmtSize = 0;
669  if ((Length -= Data[0] + 1) <= 0)
670  return;
671  Data += Data[0] + 1; // this is the first packet
672  if (SectionLength(Data, Length) > Length) {
673  if (Length <= int(sizeof(pmt))) {
674  memcpy(pmt, Data, Length);
675  pmtSize = Length;
676  }
677  else
678  esyslog("ERROR: PMT packet length too big (%d byte)!", Length);
679  return;
680  }
681  // the packet contains the entire PMT section, so we run into the actual parsing
682  }
683  else if (pmtSize > 0) {
684  // this is a following packet, so we add it to the pmt storage
685  if (Length <= int(sizeof(pmt)) - pmtSize) {
686  memcpy(pmt + pmtSize, Data, Length);
687  pmtSize += Length;
688  }
689  else {
690  esyslog("ERROR: PMT section length too big (%d byte)!", pmtSize + Length);
691  pmtSize = 0;
692  }
694  return; // more packets to come
695  // the PMT section is now complete, so we run into the actual parsing
696  Data = pmt;
697  }
698  else
699  return; // fragment of broken packet - ignore
700  SI::PMT Pmt(Data, false);
701  if (Pmt.CheckCRCAndParse()) {
702  dbgpatpmt("PMT: sid = %d, c/n = %d, v = %d, s = %d, ls = %d\n", Pmt.getServiceId(), Pmt.getCurrentNextIndicator(), Pmt.getVersionNumber(), Pmt.getSectionNumber(), Pmt.getLastSectionNumber());
703  dbgpatpmt(" pcr = %d\n", Pmt.getPCRPid());
704  if (pmtVersion == Pmt.getVersionNumber())
705  return;
708  int NumApids = 0;
709  int NumDpids = 0;
710  int NumSpids = 0;
711  vpid = vtype = 0;
712  ppid = 0;
713  apids[0] = 0;
714  dpids[0] = 0;
715  spids[0] = 0;
716  atypes[0] = 0;
717  dtypes[0] = 0;
718  SI::PMT::Stream stream;
719  for (SI::Loop::Iterator it; Pmt.streamLoop.getNext(stream, it); ) {
720  dbgpatpmt(" stream type = %02X, pid = %d", stream.getStreamType(), stream.getPid());
721  switch (stream.getStreamType()) {
722  case 0x01: // STREAMTYPE_11172_VIDEO
723  case 0x02: // STREAMTYPE_13818_VIDEO
724  case 0x1B: // H.264
725  case 0x24: // H.265
726  vpid = stream.getPid();
727  vtype = stream.getStreamType();
728  ppid = Pmt.getPCRPid();
729  break;
730  case 0x03: // STREAMTYPE_11172_AUDIO
731  case 0x04: // STREAMTYPE_13818_AUDIO
732  case 0x0F: // ISO/IEC 13818-7 Audio with ADTS transport syntax
733  case 0x11: // ISO/IEC 14496-3 Audio with LATM transport syntax
734  {
735  if (NumApids < MAXAPIDS) {
736  apids[NumApids] = stream.getPid();
737  atypes[NumApids] = stream.getStreamType();
738  *alangs[NumApids] = 0;
739  SI::Descriptor *d;
740  for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) {
741  switch (d->getDescriptorTag()) {
745  char *s = alangs[NumApids];
746  int n = 0;
747  for (SI::Loop::Iterator it; ld->languageLoop.getNext(l, it); ) {
748  if (*ld->languageCode != '-') { // some use "---" to indicate "none"
749  dbgpatpmt(" '%s'", l.languageCode);
750  if (n > 0)
751  *s++ = '+';
753  s += strlen(s);
754  if (n++ > 1)
755  break;
756  }
757  }
758  }
759  break;
760  default: ;
761  }
762  delete d;
763  }
765  cDevice::PrimaryDevice()->SetAvailableTrack(ttAudio, NumApids, apids[NumApids], alangs[NumApids]);
766  NumApids++;
767  apids[NumApids] = 0;
768  }
769  }
770  break;
771  case 0x06: // STREAMTYPE_13818_PES_PRIVATE
772  {
773  int dpid = 0;
774  int dtype = 0;
775  char lang[MAXLANGCODE1] = "";
776  SI::Descriptor *d;
777  for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) {
778  switch (d->getDescriptorTag()) {
781  dbgpatpmt(" AC3");
782  dpid = stream.getPid();
783  dtype = d->getDescriptorTag();
784  break;
786  dbgpatpmt(" subtitling");
787  if (NumSpids < MAXSPIDS) {
788  spids[NumSpids] = stream.getPid();
789  *slangs[NumSpids] = 0;
790  subtitlingTypes[NumSpids] = 0;
791  compositionPageIds[NumSpids] = 0;
792  ancillaryPageIds[NumSpids] = 0;
795  char *s = slangs[NumSpids];
796  int n = 0;
797  for (SI::Loop::Iterator it; sd->subtitlingLoop.getNext(sub, it); ) {
798  if (sub.languageCode[0]) {
799  dbgpatpmt(" '%s'", sub.languageCode);
800  subtitlingTypes[NumSpids] = sub.getSubtitlingType();
801  compositionPageIds[NumSpids] = sub.getCompositionPageId();
802  ancillaryPageIds[NumSpids] = sub.getAncillaryPageId();
803  if (n > 0)
804  *s++ = '+';
806  s += strlen(s);
807  if (n++ > 1)
808  break;
809  }
810  }
812  cDevice::PrimaryDevice()->SetAvailableTrack(ttSubtitle, NumSpids, spids[NumSpids], slangs[NumSpids]);
813  NumSpids++;
814  spids[NumSpids] = 0;
815  }
816  break;
819  dbgpatpmt(" '%s'", ld->languageCode);
821  }
822  break;
823  default: ;
824  }
825  delete d;
826  }
827  if (dpid) {
828  if (NumDpids < MAXDPIDS) {
829  dpids[NumDpids] = dpid;
830  dtypes[NumDpids] = dtype;
831  strn0cpy(dlangs[NumDpids], lang, sizeof(dlangs[NumDpids]));
833  cDevice::PrimaryDevice()->SetAvailableTrack(ttDolby, NumDpids, dpid, lang);
834  NumDpids++;
835  dpids[NumDpids] = 0;
836  }
837  }
838  }
839  break;
840  case 0x81: // STREAMTYPE_USER_PRIVATE - AC3 audio for ATSC and BD
841  case 0x82: // STREAMTYPE_USER_PRIVATE - DTS audio for BD
842  {
843  dbgpatpmt(" %s",
844  stream.getStreamType() == 0x81 ? "AC3" :
845  stream.getStreamType() == 0x82 ? "DTS" : "");
846  char lang[MAXLANGCODE1] = { 0 };
847  SI::Descriptor *d;
848  for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) {
849  switch (d->getDescriptorTag()) {
852  dbgpatpmt(" '%s'", ld->languageCode);
854  }
855  break;
856  default: ;
857  }
858  delete d;
859  }
860  if (NumDpids < MAXDPIDS) {
861  dpids[NumDpids] = stream.getPid();
862  dtypes[NumDpids] = SI::AC3DescriptorTag;
863  strn0cpy(dlangs[NumDpids], lang, sizeof(dlangs[NumDpids]));
865  cDevice::PrimaryDevice()->SetAvailableTrack(ttDolby, NumDpids, stream.getPid(), lang);
866  NumDpids++;
867  dpids[NumDpids] = 0;
868  }
869  }
870  break;
871  case 0x90: // PGS subtitles for BD
872  {
873  dbgpatpmt(" subtitling");
874  char lang[MAXLANGCODE1] = { 0 };
875  SI::Descriptor *d;
876  for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) {
877  switch (d->getDescriptorTag()) {
880  dbgpatpmt(" '%s'", ld->languageCode);
882  if (NumSpids < MAXSPIDS) {
883  spids[NumSpids] = stream.getPid();
884  *slangs[NumSpids] = 0;
885  subtitlingTypes[NumSpids] = 0;
886  compositionPageIds[NumSpids] = 0;
887  ancillaryPageIds[NumSpids] = 0;
889  cDevice::PrimaryDevice()->SetAvailableTrack(ttSubtitle, NumSpids, stream.getPid(), lang);
890  NumSpids++;
891  spids[NumSpids] = 0;
892  }
893  }
894  break;
895  default: ;
896  }
897  delete d;
898  }
899  }
900  break;
901  default: ;
902  }
903  dbgpatpmt("\n");
904  if (updatePrimaryDevice) {
907  }
908  }
910  completed = true;
911  }
912  else
913  esyslog("ERROR: can't parse PMT");
914  pmtSize = 0;
915 }
916 
917 bool cPatPmtParser::ParsePatPmt(const uchar *Data, int Length)
918 {
919  while (Length >= TS_SIZE) {
920  if (*Data != TS_SYNC_BYTE)
921  break; // just for safety
922  int Pid = TsPid(Data);
923  if (Pid == PATPID)
924  ParsePat(Data, TS_SIZE);
925  else if (IsPmtPid(Pid)) {
926  ParsePmt(Data, TS_SIZE);
927  if (patVersion >= 0 && pmtVersion >= 0)
928  return true;
929  }
930  Data += TS_SIZE;
931  Length -= TS_SIZE;
932  }
933  return false;
934 }
935 
936 bool cPatPmtParser::GetVersions(int &PatVersion, int &PmtVersion) const
937 {
938  PatVersion = patVersion;
939  PmtVersion = pmtVersion;
940  return patVersion >= 0 && pmtVersion >= 0;
941 }
942 
943 // --- cEitGenerator ---------------------------------------------------------
944 
946 {
947  counter = 0;
948  version = 0;
949  if (Sid)
950  Generate(Sid);
951 }
952 
953 uint16_t cEitGenerator::YMDtoMJD(int Y, int M, int D)
954 {
955  int L = (M < 3) ? 1 : 0;
956  return 14956 + D + int((Y - L) * 365.25) + int((M + 1 + L * 12) * 30.6001);
957 }
958 
960 {
962  *p++ = 0x04; // descriptor length
963  *p++ = 'D'; // country code
964  *p++ = 'E';
965  *p++ = 'U';
966  *p++ = ParentalRating;
967  return p;
968 }
969 
971 {
972  uchar *PayloadStart;
973  uchar *SectionStart;
974  uchar *DescriptorsStart;
975  memset(eit, 0xFF, sizeof(eit));
976  struct tm tm_r;
977  time_t t = time(NULL) - 3600; // let's have the event start one hour in the past
978  tm *tm = localtime_r(&t, &tm_r);
979  uint16_t MJD = YMDtoMJD(tm->tm_year, tm->tm_mon + 1, tm->tm_mday);
980  uchar *p = eit;
981  // TS header:
982  *p++ = TS_SYNC_BYTE;
983  *p++ = TS_PAYLOAD_START;
984  *p++ = EITPID;
985  *p++ = 0x10 | (counter++ & 0x0F); // continuity counter
986  *p++ = 0x00; // pointer field (payload unit start indicator is set)
987  // payload:
988  PayloadStart = p;
989  *p++ = 0x4E; // TID present/following event on this transponder
990  *p++ = 0xF0;
991  *p++ = 0x00; // section length
992  SectionStart = p;
993  *p++ = Sid >> 8;
994  *p++ = Sid & 0xFF;
995  *p++ = 0xC1 | (version << 1);
996  *p++ = 0x00; // section number
997  *p++ = 0x00; // last section number
998  *p++ = 0x00; // transport stream id
999  *p++ = 0x00; // ...
1000  *p++ = 0x00; // original network id
1001  *p++ = 0x00; // ...
1002  *p++ = 0x00; // segment last section number
1003  *p++ = 0x4E; // last table id
1004  *p++ = 0x00; // event id
1005  *p++ = 0x01; // ...
1006  *p++ = MJD >> 8; // start time
1007  *p++ = MJD & 0xFF; // ...
1008  *p++ = tm->tm_hour; // ...
1009  *p++ = tm->tm_min; // ...
1010  *p++ = tm->tm_sec; // ...
1011  *p++ = 0x24; // duration (one day, should cover everything)
1012  *p++ = 0x00; // ...
1013  *p++ = 0x00; // ...
1014  *p++ = 0x90; // running status, free/CA mode
1015  *p++ = 0x00; // descriptors loop length
1016  DescriptorsStart = p;
1018  // fill in lengths:
1019  *(SectionStart - 1) = p - SectionStart + 4; // +4 = length of CRC
1020  *(DescriptorsStart - 1) = p - DescriptorsStart;
1021  // checksum
1022  int crc = SI::CRC32::crc32((char *)PayloadStart, p - PayloadStart, 0xFFFFFFFF);
1023  *p++ = crc >> 24;
1024  *p++ = crc >> 16;
1025  *p++ = crc >> 8;
1026  *p++ = crc;
1027  return eit;
1028 }
1029 
1030 // --- cTsToPes --------------------------------------------------------------
1031 
1033 {
1034  data = NULL;
1035  size = 0;
1036  Reset();
1037 }
1038 
1040 {
1041  free(data);
1042 }
1043 
1044 void cTsToPes::PutTs(const uchar *Data, int Length)
1045 {
1046  if (TsError(Data)) {
1047  Reset();
1048  return; // ignore packets with TEI set, and drop any PES data collected so far
1049  }
1050  if (TsPayloadStart(Data))
1051  Reset();
1052  else if (!size)
1053  return; // skip everything before the first payload start
1054  Length = TsGetPayload(&Data);
1055  if (length + Length > size) {
1056  int NewSize = max(KILOBYTE(2), length + Length);
1057  if (uchar *NewData = (uchar *)realloc(data, NewSize)) {
1058  data = NewData;
1059  size = NewSize;
1060  }
1061  else {
1062  esyslog("ERROR: out of memory");
1063  Reset();
1064  return;
1065  }
1066  }
1067  memcpy(data + length, Data, Length);
1068  length += Length;
1069 }
1070 
1071 #define MAXPESLENGTH 0xFFF0
1072 
1073 const uchar *cTsToPes::GetPes(int &Length)
1074 {
1075  if (repeatLast) {
1076  repeatLast = false;
1077  Length = lastLength;
1078  return lastData;
1079  }
1080  if (offset < length && PesLongEnough(length)) {
1081  if (!PesHasLength(data)) // this is a video PES packet with undefined length
1082  offset = 6; // trigger setting PES length for initial slice
1083  if (offset) {
1084  uchar *p = data + offset - 6;
1085  if (p != data) {
1086  p -= 3;
1087  if (p < data) {
1088  Reset();
1089  return NULL;
1090  }
1091  memmove(p, data, 4);
1092  }
1093  int l = min(length - offset, MAXPESLENGTH);
1094  offset += l;
1095  if (p != data) {
1096  l += 3;
1097  p[6] = 0x80;
1098  p[7] = 0x00;
1099  p[8] = 0x00;
1100  }
1101  p[4] = l / 256;
1102  p[5] = l & 0xFF;
1103  Length = l + 6;
1104  lastLength = Length;
1105  lastData = p;
1106  return p;
1107  }
1108  else {
1109  Length = PesLength(data);
1110  if (Length <= length) {
1111  offset = Length; // to make sure we break out in case of garbage data
1112  lastLength = Length;
1113  lastData = data;
1114  return data;
1115  }
1116  }
1117  }
1118  return NULL;
1119 }
1120 
1122 {
1123  repeatLast = true;
1124 }
1125 
1127 {
1128  length = offset = 0;
1129  lastData = NULL;
1130  lastLength = 0;
1131  repeatLast = false;
1132 }
1133 
1134 // --- Some helper functions for debugging -----------------------------------
1135 
1136 void BlockDump(const char *Name, const u_char *Data, int Length)
1137 {
1138  printf("--- %s\n", Name);
1139  for (int i = 0; i < Length; i++) {
1140  if (i && (i % 16) == 0)
1141  printf("\n");
1142  printf(" %02X", Data[i]);
1143  }
1144  printf("\n");
1145 }
1146 
1147 void TsDump(const char *Name, const u_char *Data, int Length)
1148 {
1149  printf("%s: %04X", Name, Length);
1150  int n = min(Length, 20);
1151  for (int i = 0; i < n; i++)
1152  printf(" %02X", Data[i]);
1153  if (n < Length) {
1154  printf(" ...");
1155  n = max(n, Length - 10);
1156  for (n = max(n, Length - 10); n < Length; n++)
1157  printf(" %02X", Data[n]);
1158  }
1159  printf("\n");
1160 }
1161 
1162 void PesDump(const char *Name, const u_char *Data, int Length)
1163 {
1164  TsDump(Name, Data, Length);
1165 }
1166 
1167 // --- cFrameParser ----------------------------------------------------------
1168 
1170 protected:
1171  bool debug;
1172  bool newFrame;
1175 public:
1176  cFrameParser(void);
1177  virtual ~cFrameParser() {};
1178  virtual int Parse(const uchar *Data, int Length, int Pid) = 0;
1185  void SetDebug(bool Debug) { debug = Debug; }
1186  bool NewFrame(void) { return newFrame; }
1187  bool IndependentFrame(void) { return independentFrame; }
1189  };
1190 
1192 {
1193  debug = true;
1194  newFrame = false;
1195  independentFrame = false;
1197 }
1198 
1199 // --- cAudioParser ----------------------------------------------------------
1200 
1201 class cAudioParser : public cFrameParser {
1202 public:
1203  cAudioParser(void);
1204  virtual int Parse(const uchar *Data, int Length, int Pid);
1205  };
1206 
1208 {
1209 }
1210 
1211 int cAudioParser::Parse(const uchar *Data, int Length, int Pid)
1212 {
1213  if (TsPayloadStart(Data)) {
1214  newFrame = independentFrame = true;
1215  if (debug)
1216  dbgframes("/");
1217  }
1218  else
1219  newFrame = independentFrame = false;
1220  return TS_SIZE;
1221 }
1222 
1223 // --- cMpeg2Parser ----------------------------------------------------------
1224 
1225 class cMpeg2Parser : public cFrameParser {
1226 private:
1227  uint32_t scanner;
1230 public:
1231  cMpeg2Parser(void);
1232  virtual int Parse(const uchar *Data, int Length, int Pid);
1233  };
1234 
1236 {
1238  seenIndependentFrame = false;
1239  lastIFrameTemporalReference = -1; // invalid
1240 }
1241 
1242 int cMpeg2Parser::Parse(const uchar *Data, int Length, int Pid)
1243 {
1244  newFrame = independentFrame = false;
1245  bool SeenPayloadStart = false;
1246  cTsPayload tsPayload(const_cast<uchar *>(Data), Length, Pid);
1247  if (TsPayloadStart(Data)) {
1248  SeenPayloadStart = true;
1249  tsPayload.SkipPesHeader();
1251  if (debug && seenIndependentFrame)
1252  dbgframes("/");
1253  }
1254  uint32_t OldScanner = scanner; // need to remember it in case of multiple frames per payload
1255  for (;;) {
1256  if (!SeenPayloadStart && tsPayload.AtTsStart())
1257  OldScanner = scanner;
1258  scanner = (scanner << 8) | tsPayload.GetByte();
1259  if (scanner == 0x00000100) { // Picture Start Code
1260  if (!SeenPayloadStart && tsPayload.GetLastIndex() > TS_SIZE) {
1261  scanner = OldScanner;
1262  return tsPayload.Used() - TS_SIZE;
1263  }
1264  uchar b1 = tsPayload.GetByte();
1265  uchar b2 = tsPayload.GetByte();
1266  int TemporalReference = (b1 << 2 ) + ((b2 & 0xC0) >> 6);
1267  uchar FrameType = (b2 >> 3) & 0x07;
1268  if (tsPayload.Find(0x000001B5)) { // Extension start code
1269  if (((tsPayload.GetByte() & 0xF0) >> 4) == 0x08) { // Picture coding extension
1270  tsPayload.GetByte();
1271  uchar PictureStructure = tsPayload.GetByte() & 0x03;
1272  if (PictureStructure == 0x02) // bottom field
1273  break;
1274  }
1275  }
1276  newFrame = true;
1277  independentFrame = FrameType == 1; // I-Frame
1278  if (independentFrame) {
1279  if (lastIFrameTemporalReference >= 0)
1281  lastIFrameTemporalReference = TemporalReference;
1282  }
1283  if (debug) {
1285  if (seenIndependentFrame) {
1286  static const char FrameTypes[] = "?IPBD???";
1287  dbgframes("%c", FrameTypes[FrameType]);
1288  }
1289  }
1290  tsPayload.Statistics();
1291  break;
1292  }
1293  if (tsPayload.AtPayloadStart() // stop at any new payload start to have the buffer refilled if necessary
1294  || tsPayload.Eof()) // or if we're out of data
1295  break;
1296  }
1297  return tsPayload.Used();
1298 }
1299 
1300 // --- cH264Parser -----------------------------------------------------------
1301 
1302 class cH264Parser : public cFrameParser {
1303 private:
1309  };
1310  uchar byte; // holds the current byte value in case of bitwise access
1311  int bit; // the bit index into the current byte (-1 if we're not in bit reading mode)
1312  int zeroBytes; // the number of consecutive zero bytes (to detect 0x000003)
1313  // Identifiers written in '_' notation as in "ITU-T H.264":
1317 protected:
1319  uint32_t scanner;
1322  uchar GetByte(bool Raw = false);
1326  uchar GetBit(void);
1327  uint32_t GetBits(int Bits);
1328  uint32_t GetGolombUe(void);
1329  int32_t GetGolombSe(void);
1330  void ParseAccessUnitDelimiter(void);
1331  void ParseSequenceParameterSet(void);
1332  void ParseSliceHeader(void);
1333 public:
1334  cH264Parser(void);
1338  virtual int Parse(const uchar *Data, int Length, int Pid);
1339  };
1340 
1342 {
1343  byte = 0;
1344  bit = -1;
1345  zeroBytes = 0;
1348  log2_max_frame_num = 0;
1349  frame_mbs_only_flag = false;
1350  gotAccessUnitDelimiter = false;
1351  gotSequenceParameterSet = false;
1352 }
1353 
1355 {
1356  uchar b = tsPayload.GetByte();
1357  if (!Raw) {
1358  // If we encounter the byte sequence 0x000003, we need to skip the 0x03:
1359  if (b == 0x00)
1360  zeroBytes++;
1361  else {
1362  if (b == 0x03 && zeroBytes >= 2)
1363  b = tsPayload.GetByte();
1364  zeroBytes = 0;
1365  }
1366  }
1367  else
1368  zeroBytes = 0;
1369  bit = -1;
1370  return b;
1371 }
1372 
1374 {
1375  if (bit < 0) {
1376  byte = GetByte();
1377  bit = 7;
1378  }
1379  return (byte & (1 << bit--)) ? 1 : 0;
1380 }
1381 
1382 uint32_t cH264Parser::GetBits(int Bits)
1383 {
1384  uint32_t b = 0;
1385  while (Bits--)
1386  b |= GetBit() << Bits;
1387  return b;
1388 }
1389 
1391 {
1392  int z = -1;
1393  for (int b = 0; !b && z < 32; z++) // limiting z to no get stuck if GetBit() always returns 0
1394  b = GetBit();
1395  return (1 << z) - 1 + GetBits(z);
1396 }
1397 
1399 {
1400  uint32_t v = GetGolombUe();
1401  if (v) {
1402  if ((v & 0x01) != 0)
1403  return (v + 1) / 2; // fails for v == 0xFFFFFFFF, but that will probably never happen
1404  else
1405  return -int32_t(v / 2);
1406  }
1407  return v;
1408 }
1409 
1410 int cH264Parser::Parse(const uchar *Data, int Length, int Pid)
1411 {
1412  newFrame = independentFrame = false;
1413  tsPayload.Setup(const_cast<uchar *>(Data), Length, Pid);
1414  if (TsPayloadStart(Data)) {
1417  if (debug && gotSequenceParameterSet) {
1418  dbgframes("/");
1419  }
1420  }
1421  for (;;) {
1422  scanner = (scanner << 8) | GetByte(true);
1423  if ((scanner & 0xFFFFFF00) == 0x00000100) { // NAL unit start
1424  uchar NalUnitType = scanner & 0x1F;
1425  switch (NalUnitType) {
1427  gotAccessUnitDelimiter = true;
1428  break;
1431  gotSequenceParameterSet = true;
1432  }
1433  break;
1434  case nutCodedSliceNonIdr:
1436  ParseSliceHeader();
1437  gotAccessUnitDelimiter = false;
1438  if (newFrame)
1440  return tsPayload.Used();
1441  }
1442  break;
1443  default: ;
1444  }
1445  }
1446  if (tsPayload.AtPayloadStart() // stop at any new payload start to have the buffer refilled if necessary
1447  || tsPayload.Eof()) // or if we're out of data
1448  break;
1449  }
1450  return tsPayload.Used();
1451 }
1452 
1454 {
1456  dbgframes("A");
1457  GetByte(); // primary_pic_type
1458 }
1459 
1461 {
1462  uchar profile_idc = GetByte(); // profile_idc
1463  GetByte(); // constraint_set[0-5]_flags, reserved_zero_2bits
1464  GetByte(); // level_idc
1465  GetGolombUe(); // seq_parameter_set_id
1466  if (profile_idc == 100 || profile_idc == 110 || profile_idc == 122 || profile_idc == 244 || profile_idc == 44 || profile_idc == 83 || profile_idc == 86 || profile_idc ==118 || profile_idc == 128) {
1467  int chroma_format_idc = GetGolombUe(); // chroma_format_idc
1468  if (chroma_format_idc == 3)
1470  GetGolombUe(); // bit_depth_luma_minus8
1471  GetGolombUe(); // bit_depth_chroma_minus8
1472  GetBit(); // qpprime_y_zero_transform_bypass_flag
1473  if (GetBit()) { // seq_scaling_matrix_present_flag
1474  for (int i = 0; i < ((chroma_format_idc != 3) ? 8 : 12); i++) {
1475  if (GetBit()) { // seq_scaling_list_present_flag
1476  int SizeOfScalingList = (i < 6) ? 16 : 64;
1477  int LastScale = 8;
1478  int NextScale = 8;
1479  for (int j = 0; j < SizeOfScalingList; j++) {
1480  if (NextScale)
1481  NextScale = (LastScale + GetGolombSe() + 256) % 256; // delta_scale
1482  if (NextScale)
1483  LastScale = NextScale;
1484  }
1485  }
1486  }
1487  }
1488  }
1489  log2_max_frame_num = GetGolombUe() + 4; // log2_max_frame_num_minus4
1490  int pic_order_cnt_type = GetGolombUe(); // pic_order_cnt_type
1491  if (pic_order_cnt_type == 0)
1492  GetGolombUe(); // log2_max_pic_order_cnt_lsb_minus4
1493  else if (pic_order_cnt_type == 1) {
1494  GetBit(); // delta_pic_order_always_zero_flag
1495  GetGolombSe(); // offset_for_non_ref_pic
1496  GetGolombSe(); // offset_for_top_to_bottom_field
1497  for (int i = GetGolombUe(); i--; ) // num_ref_frames_in_pic_order_cnt_cycle
1498  GetGolombSe(); // offset_for_ref_frame
1499  }
1500  GetGolombUe(); // max_num_ref_frames
1501  GetBit(); // gaps_in_frame_num_value_allowed_flag
1502  GetGolombUe(); // pic_width_in_mbs_minus1
1503  GetGolombUe(); // pic_height_in_map_units_minus1
1504  frame_mbs_only_flag = GetBit(); // frame_mbs_only_flag
1505  if (debug) {
1507  dbgframes("A"); // just for completeness
1508  dbgframes(frame_mbs_only_flag ? "S" : "s");
1509  }
1510 }
1511 
1513 {
1514  newFrame = true;
1515  GetGolombUe(); // first_mb_in_slice
1516  int slice_type = GetGolombUe(); // slice_type, 0 = P, 1 = B, 2 = I, 3 = SP, 4 = SI
1517  independentFrame = (slice_type % 5) == 2;
1518  if (debug) {
1519  static const char SliceTypes[] = "PBIpi";
1520  dbgframes("%c", SliceTypes[slice_type % 5]);
1521  }
1522  if (frame_mbs_only_flag)
1523  return; // don't need the rest - a frame is complete
1524  GetGolombUe(); // pic_parameter_set_id
1526  GetBits(2); // colour_plane_id
1527  GetBits(log2_max_frame_num); // frame_num
1528  if (!frame_mbs_only_flag) {
1529  if (GetBit()) // field_pic_flag
1530  newFrame = !GetBit(); // bottom_field_flag
1531  if (debug)
1532  dbgframes(newFrame ? "t" : "b");
1533  }
1534 }
1535 
1536 // --- cH265Parser -----------------------------------------------------------
1537 
1538 class cH265Parser : public cH264Parser {
1539 private:
1570  };
1571 public:
1572  cH265Parser(void);
1573  virtual int Parse(const uchar *Data, int Length, int Pid);
1574  };
1575 
1577 :cH264Parser()
1578 {
1579 }
1580 
1581 int cH265Parser::Parse(const uchar *Data, int Length, int Pid)
1582 {
1583  newFrame = independentFrame = false;
1584  tsPayload.Setup(const_cast<uchar *>(Data), Length, Pid);
1585  if (TsPayloadStart(Data)) {
1588  }
1589  for (;;) {
1590  scanner = (scanner << 8) | GetByte(true);
1591  if ((scanner & 0xFFFFFF00) == 0x00000100) { // NAL unit start
1592  uchar NalUnitType = (scanner >> 1) & 0x3F;
1593  GetByte(); // nuh_layer_id + nuh_temporal_id_plus1
1594  if (NalUnitType <= nutSliceSegmentRASLR || (NalUnitType >= nutSliceSegmentBLAWLP && NalUnitType <= nutSliceSegmentCRANUT)) {
1595  if (NalUnitType == nutSliceSegmentIDRWRADL || NalUnitType == nutSliceSegmentIDRNLP || NalUnitType == nutSliceSegmentCRANUT)
1596  independentFrame = true;
1597  if (GetBit()) { // first_slice_segment_in_pic_flag
1598  newFrame = true;
1600  }
1601  break;
1602  }
1603  }
1604  if (tsPayload.AtPayloadStart() // stop at any new payload start to have the buffer refilled if necessary
1605  || tsPayload.Eof()) // or if we're out of data
1606  break;
1607  }
1608  return tsPayload.Used();
1609 }
1610 
1611 // --- cFrameDetector --------------------------------------------------------
1612 
1614 {
1615  parser = NULL;
1616  SetPid(Pid, Type);
1617  synced = false;
1618  newFrame = independentFrame = false;
1619  numPtsValues = 0;
1620  numIFrames = 0;
1621  framesPerSecond = 0;
1623  scanning = false;
1624 }
1625 
1626 static int CmpUint32(const void *p1, const void *p2)
1627 {
1628  if (*(uint32_t *)p1 < *(uint32_t *)p2) return -1;
1629  if (*(uint32_t *)p1 > *(uint32_t *)p2) return 1;
1630  return 0;
1631 }
1632 
1633 void cFrameDetector::SetPid(int Pid, int Type)
1634 {
1635  pid = Pid;
1636  type = Type;
1637  isVideo = type == 0x01 || type == 0x02 || type == 0x1B || type == 0x24; // MPEG 1, 2, H.264 or H.265
1638  delete parser;
1639  parser = NULL;
1640  if (type == 0x01 || type == 0x02)
1641  parser = new cMpeg2Parser;
1642  else if (type == 0x1B)
1643  parser = new cH264Parser;
1644  else if (type == 0x24)
1645  parser = new cH265Parser;
1646  else if (type == 0x03 || type == 0x04 || type == 0x06) // MPEG audio or AC3 audio
1647  parser = new cAudioParser;
1648  else if (type != 0)
1649  esyslog("ERROR: unknown stream type %d (PID %d) in frame detector", type, pid);
1650 }
1651 
1652 int cFrameDetector::Analyze(const uchar *Data, int Length)
1653 {
1654  if (!parser)
1655  return 0;
1656  int Processed = 0;
1657  newFrame = independentFrame = false;
1658  while (Length >= MIN_TS_PACKETS_FOR_FRAME_DETECTOR * TS_SIZE) { // makes sure we are looking at enough data, in case the frame type is not stored in the first TS packet
1659  // Sync on TS packet borders:
1660  if (int Skipped = TS_SYNC(Data, Length))
1661  return Processed + Skipped;
1662  // Handle one TS packet:
1663  int Handled = TS_SIZE;
1664  if (TsHasPayload(Data) && !TsIsScrambled(Data)) {
1665  int Pid = TsPid(Data);
1666  if (Pid == pid) {
1667  if (Processed)
1668  return Processed;
1669  if (TsPayloadStart(Data))
1670  scanning = true;
1671  if (scanning) {
1672  // Detect the beginning of a new frame:
1673  if (TsPayloadStart(Data)) {
1674  if (!framesPerPayloadUnit)
1676  }
1677  int n = parser->Parse(Data, Length, pid);
1678  if (n > 0) {
1679  if (parser->NewFrame()) {
1680  newFrame = true;
1682  if (synced) {
1683  if (framesPerPayloadUnit <= 1)
1684  scanning = false;
1685  }
1686  else {
1688  if (independentFrame)
1689  numIFrames++;
1690  }
1691  }
1692  Handled = n;
1693  }
1694  }
1695  if (TsPayloadStart(Data)) {
1696  // Determine the frame rate from the PTS values in the PES headers:
1697  if (framesPerSecond <= 0.0) {
1698  // frame rate unknown, so collect a sequence of PTS values:
1699  if (numPtsValues < 2 || numPtsValues < MaxPtsValues && numIFrames < 2) { // collect a sequence containing at least two I-frames
1700  if (newFrame) { // only take PTS values at the beginning of a frame (in case if fields!)
1701  const uchar *Pes = Data + TsPayloadOffset(Data);
1702  if (numIFrames && PesHasPts(Pes)) {
1704  // check for rollover:
1705  if (numPtsValues && ptsValues[numPtsValues - 1] > 0xF0000000 && ptsValues[numPtsValues] < 0x10000000) {
1706  dbgframes("#");
1707  numPtsValues = 0;
1708  numIFrames = 0;
1709  }
1710  else
1711  numPtsValues++;
1712  }
1713  }
1714  }
1715  if (numPtsValues >= 2 && numIFrames >= 2) {
1716  // find the smallest PTS delta:
1717  qsort(ptsValues, numPtsValues, sizeof(uint32_t), CmpUint32);
1718  numPtsValues--;
1719  for (int i = 0; i < numPtsValues; i++)
1720  ptsValues[i] = ptsValues[i + 1] - ptsValues[i];
1721  qsort(ptsValues, numPtsValues, sizeof(uint32_t), CmpUint32);
1722  int Div = framesPerPayloadUnit;
1723  if (framesPerPayloadUnit > 1)
1725  if (Div <= 0)
1726  Div = 1;
1727  int Delta = ptsValues[0] / Div;
1728  // determine frame info:
1729  if (isVideo) {
1730  if (Delta == 3753)
1731  framesPerSecond = 24.0 / 1.001;
1732  else if (abs((int32_t)Delta - 3600) <= 1)
1733  framesPerSecond = 25.0;
1734  else if (Delta % 3003 == 0)
1735  framesPerSecond = 30.0 / 1.001;
1736  else if (abs((int32_t)Delta - 1800) <= 1)
1737  framesPerSecond = 50.0;
1738  else if (Delta == 1501)
1739  framesPerSecond = 60.0 / 1.001;
1740  else {
1742  dsyslog("unknown frame delta (%d), assuming %5.2f fps", Delta, DEFAULTFRAMESPERSECOND);
1743  }
1744  }
1745  else // audio
1746  framesPerSecond = double(PTSTICKS) / Delta; // PTS of audio frames is always increasing
1747  dbgframes("\nDelta = %d FPS = %5.2f FPPU = %d NF = %d TRO = %d\n", Delta, framesPerSecond, framesPerPayloadUnit, numPtsValues + 1, parser->IFrameTemporalReferenceOffset());
1748  synced = true;
1749  parser->SetDebug(false);
1750  }
1751  }
1752  }
1753  }
1754  else if (Pid == PATPID && synced && Processed)
1755  return Processed; // allow the caller to see any PAT packets
1756  }
1757  Data += Handled;
1758  Length -= Handled;
1759  Processed += Handled;
1760  if (newFrame)
1761  break;
1762  }
1763  return Processed;
1764 }
int framesInPayloadUnit
Definition: remux.h:520
#define VIDEO_STREAM_S
Definition: remux.c:98
bool ParsePatPmt(const uchar *Data, int Length)
Parses the given Data (which may consist of several TS packets, typically an entire frame) and extrac...
Definition: remux.c:917
unsigned char uchar
Definition: tools.h:31
void ParsePat(const uchar *Data, int Length)
Parses the PAT data from the single TS packet in Data.
Definition: remux.c:627
uchar * data
Definition: remux.h:228
int Used(void)
Returns the number of raw bytes that have already been used (e.g.
Definition: remux.h:258
uchar GetBit(void)
Definition: remux.c:1373
bool separate_colour_plane_flag
Definition: remux.c:1314
uchar GetByte(void)
Gets the next byte of the TS payload, skipping any intermediate TS header data.
Definition: remux.c:280
bool repeatLast
Definition: remux.h:458
int vpid
Definition: remux.h:360
int index
Definition: remux.h:231
int pid
Definition: remux.h:230
uchar subtitlingTypes[MAXSPIDS]
Definition: remux.h:371
Definition: device.h:64
void SetVersions(int PatVersion, int PmtVersion)
Sets the version numbers for the generated PAT and PMT, in case this generator is used to,...
Definition: remux.c:579
#define dsyslog(a...)
Definition: tools.h:37
int getVersionNumber() const
Definition: si.c:84
bool TsError(const uchar *p)
Definition: remux.h:77
void SetPid(int Pid, int Type)
Sets the Pid and stream Type to detect frames for.
Definition: remux.c:1633
#define MAX_TS_PACKETS_FOR_VIDEO_FRAME_DETECTION
Definition: remux.c:26
#define DEFAULTFRAMESPERSECOND
Definition: recording.h:351
bool newFrame
Definition: remux.c:1172
int PesPayloadOffset(const uchar *p)
Definition: remux.h:178
int Dpid(int i) const
Definition: channels.h:159
void IncCounter(int &Counter, uchar *TsPacket)
Definition: remux.c:371
bool SkipBytes(int Bytes)
Skips the given number of bytes in the payload and returns true if there is still data left to read.
Definition: remux.c:311
bool TsHasAdaptationField(const uchar *p)
Definition: remux.h:67
int Ppid(void) const
Definition: channels.h:153
void ParsePmt(const uchar *Data, int Length)
Parses the PMT data from the single TS packet in Data.
Definition: remux.c:659
uchar eit[TS_SIZE]
Definition: remux.h:434
uint16_t ancillaryPageIds[MAXSPIDS]
Definition: remux.h:373
int framesPerPayloadUnit
Definition: remux.h:521
virtual int Parse(const uchar *Data, int Length, int Pid)
Parses the given Data, which is a sequence of Length bytes of TS packets.
Definition: remux.c:1242
int pmtSize
Definition: remux.h:356
cH265Parser(void)
Definition: remux.c:1576
char alangs[MAXAPIDS][MAXLANGCODE2]
Definition: remux.h:365
bool IndependentFrame(void)
Definition: remux.c:1187
bool isNITPid() const
Definition: section.h:31
#define SETPID(p)
#define MAX33BIT
Definition: remux.h:59
bool getCurrentNextIndicator() const
Definition: si.c:80
bool TsPayloadStart(const uchar *p)
Definition: remux.h:72
uint32_t scanner
Definition: remux.c:1319
bool gotAccessUnitDelimiter
Definition: remux.c:1320
int MakeLanguageDescriptor(uchar *Target, const char *Language)
Definition: remux.c:432
bool IsPmtPid(int Pid) const
Returns true if Pid the one of the PMT pids as defined by the current PAT.
Definition: remux.h:400
void GeneratePmtPid(const cChannel *Channel)
Generates a PMT pid that doesn't collide with any of the actual pids of the Channel.
Definition: remux.c:466
int64_t PesGetPts(const uchar *p)
Definition: remux.h:193
int Analyze(const uchar *Data, int Length)
Analyzes the TS packets pointed to by Data.
Definition: remux.c:1652
uchar pat[TS_SIZE]
Definition: remux.h:300
uint16_t YMDtoMJD(int Y, int M, int D)
Definition: remux.c:953
int numPacketsPid
Definition: remux.h:232
bool debug
Definition: remux.c:1171
bool TsHasPayload(const uchar *p)
Definition: remux.h:62
StructureLoop< Association > associationLoop
Definition: section.h:39
const char * Alang(int i) const
Definition: channels.h:161
uint32_t ptsValues[MaxPtsValues]
Definition: remux.h:515
#define esyslog(a...)
Definition: tools.h:35
StructureLoop< Stream > streamLoop
Definition: section.h:71
int Atype(int i) const
Definition: channels.h:164
char slangs[MAXSPIDS][MAXLANGCODE2]
Definition: remux.h:370
#define TS_ADAPT_FIELD_EXISTS
Definition: remux.h:40
char * strn0cpy(char *dest, const char *src, size_t n)
Definition: tools.c:131
static u_int32_t crc32(const char *d, int len, u_int32_t CRCvalue)
Definition: util.c:267
void IncEsInfoLength(int Length)
Definition: remux.c:384
int MakeCRC(uchar *Target, const uchar *Data, int Length)
Definition: remux.c:451
bool SetAvailableTrack(eTrackType Type, int Index, uint16_t Id, const char *Language=NULL, const char *Description=NULL)
Sets the track of the given Type and Index to the given values.
Definition: device.c:1050
int getStreamType() const
Definition: section.c:69
T max(T a, T b)
Definition: tools.h:60
#define WRN_TS_PACKETS_FOR_FRAME_DETECTOR
Definition: remux.c:28
const char * Slang(int i) const
Definition: channels.h:163
void SetChannel(const cChannel *Channel)
Sets the Channel for which the PAT/PMT shall be generated.
Definition: remux.c:585
bool AtPayloadStart(void)
Returns true if this payload handler is currently pointing to the first byte of a TS packet that star...
Definition: remux.h:252
bool PesHasPts(const uchar *p)
Definition: remux.h:183
#define PTSTICKS
Definition: remux.h:57
cPatPmtGenerator(const cChannel *Channel=NULL)
Definition: remux.c:361
uchar SetEof(void)
Definition: remux.c:259
int MakeSubtitlingDescriptor(uchar *Target, const char *Language, uchar SubtitlingType, uint16_t CompositionPageId, uint16_t AncillaryPageId)
Definition: remux.c:415
const int * Spids(void) const
Definition: channels.h:157
int length
Definition: remux.h:454
void Setup(uchar *Data, int Length, int Pid=-1)
Sets up this TS payload handler with the given Data, which points to a sequence of Length bytes of co...
Definition: remux.c:272
StructureLoop< Subtitling > subtitlingLoop
Definition: descriptor.h:331
bool isVideo
Definition: remux.h:518
void ParseSequenceParameterSet(void)
Definition: remux.c:1460
int pmtVersion
Definition: remux.h:358
const char * Dlang(int i) const
Definition: channels.h:162
int64_t TsGetDts(const uchar *p, int l)
Definition: remux.c:173
int numPtsValues
Definition: remux.h:516
bool independentFrame
Definition: remux.c:1173
T min(T a, T b)
Definition: tools.h:59
bool independentFrame
Definition: remux.h:514
#define TS_SYNC_BYTE
Definition: remux.h:33
int lastLength
Definition: remux.h:457
int MakeAC3Descriptor(uchar *Target, uchar Type)
Definition: remux.c:405
int Vtype(void) const
Definition: channels.h:154
static bool DebugPatPmt
Definition: remux.c:20
void GeneratePat(void)
Generates a PAT section for later use with GetPat().
Definition: remux.c:481
bool Find(uint32_t Code)
Searches for the four byte sequence given in Code and returns true if it was found within the payload...
Definition: remux.c:334
#define dbgpatpmt(a...)
Definition: remux.c:23
cFrameParser(void)
Definition: remux.c:1191
int SectionLength(const uchar *Data, int Length)
Definition: remux.h:377
int MakeStream(uchar *Target, uchar Type, int Pid)
Definition: remux.c:393
uchar GetByte(bool Raw=false)
Gets the next data byte.
Definition: remux.c:1354
int iFrameTemporalReferenceOffset
Definition: remux.c:1174
int Spid(int i) const
Definition: channels.h:160
int patCounter
Definition: remux.h:303
uchar pmt[MAX_PMT_TS][TS_SIZE]
Definition: remux.h:301
uchar * lastData
Definition: remux.h:456
bool PesLongEnough(int Length)
Definition: remux.h:163
const int * Apids(void) const
Definition: channels.h:155
int Dtype(int i) const
Definition: channels.h:165
void TsSetPcr(uchar *p, int64_t Pcr)
Definition: remux.c:131
#define MAX_SECTION_SIZE
Definition: remux.h:295
#define EMPTY_SCANNER
Definition: remux.c:30
int TsPid(const uchar *p)
Definition: remux.h:82
virtual int Parse(const uchar *Data, int Length, int Pid)
Parses the given Data, which is a sequence of Length bytes of TS packets.
Definition: remux.c:1410
cFrameDetector(int Pid=0, int Type=0)
Sets up a frame detector for the given Pid and stream Type.
Definition: remux.c:1613
#define SETPIDS(l)
void ParseSliceHeader(void)
Definition: remux.c:1512
double framesPerSecond
Definition: remux.h:519
void EnsureSubtitleTrack(void)
Makes sure one of the preferred language subtitle tracks is selected.
Definition: device.c:1183
#define TS_PAYLOAD_EXISTS
Definition: remux.h:41
int PesLength(const uchar *p)
Definition: remux.h:173
void PesSetPts(uchar *p, int64_t Pts)
Definition: remux.c:216
void ParseAccessUnitDelimiter(void)
Definition: remux.c:1453
Definition: remux.h:20
int lastIFrameTemporalReference
Definition: remux.c:1229
int zeroBytes
Definition: remux.c:1312
int ppid
Definition: remux.h:361
bool GetVersions(int &PatVersion, int &PmtVersion) const
Returns true if a valid PAT/PMT has been parsed and stores the current version numbers in the given v...
Definition: remux.c:936
int getPid() const
Definition: section.c:65
cH264Parser(void)
Sets up a new H.264 parser.
Definition: remux.c:1341
char dlangs[MAXDPIDS][MAXLANGCODE2]
Definition: remux.h:368
const int * Dpids(void) const
Definition: channels.h:156
void Reset(void)
Resets the converter.
Definition: remux.c:1126
#define MAXPID
Definition: remux.c:464
bool synced
Definition: remux.h:512
bool PesHasDts(const uchar *p)
Definition: remux.h:188
int Tpid(void) const
Definition: channels.h:169
void PesSetDts(uchar *p, int64_t Dts)
Definition: remux.c:225
void BlockDump(const char *Name, const u_char *Data, int Length)
Definition: remux.c:1136
void TsSetDts(uchar *p, int l, int64_t Dts)
Definition: remux.c:200
cPatPmtParser(bool UpdatePrimaryDevice=false)
Definition: remux.c:611
int TsSync(const uchar *Data, int Length, const char *File, const char *Function, int Line)
Definition: remux.c:147
int GetLastIndex(void)
Returns the index into the TS data of the payload byte that has most recently been read.
Definition: remux.c:323
virtual int Parse(const uchar *Data, int Length, int Pid)=0
Parses the given Data, which is a sequence of Length bytes of TS packets.
cTsPayload(void)
Definition: remux.c:246
int dtypes[MAXDPIDS+1]
Definition: remux.h:367
int dpids[MAXDPIDS+1]
Definition: remux.h:366
void TsDump(const char *Name, const u_char *Data, int Length)
Definition: remux.c:1147
virtual int Parse(const uchar *Data, int Length, int Pid)
Parses the given Data, which is a sequence of Length bytes of TS packets.
Definition: remux.c:1211
int64_t PtsDiff(int64_t Pts1, int64_t Pts2)
Returns the difference between two PTS values.
Definition: remux.c:234
void PutTs(const uchar *Data, int Length)
Puts the payload data of the single TS packet at Data into the converter.
Definition: remux.c:1044
int getServiceId() const
Definition: section.c:30
void ClrAvailableTracks(bool DescriptionsOnly=false, bool IdsOnly=false)
Clears the list of currently available tracks.
Definition: device.c:1027
ePesHeader AnalyzePesHeader(const uchar *Data, int Count, int &PesPayloadOffset, bool *ContinuationHeader)
Definition: remux.c:32
int IFrameTemporalReferenceOffset(void)
Definition: remux.c:1188
int atypes[MAXAPIDS+1]
Definition: remux.h:364
uchar byte
Definition: remux.c:1310
uchar * GetPmt(int &Index)
Returns a pointer to the Index'th TS packet of the PMT section.
Definition: remux.c:600
int numPmtPackets
Definition: remux.h:302
cSetup Setup
Definition: config.c:372
uchar * Generate(int Sid)
Definition: remux.c:970
StructureLoop< Language > languageLoop
Definition: descriptor.h:489
int getServiceId() const
Definition: section.c:57
bool Eof(void) const
Returns true if all available bytes of the TS payload have been processed.
Definition: remux.h:262
int Apid(int i) const
Definition: channels.h:158
#define WRN_TS_PACKETS_FOR_VIDEO_FRAME_DETECTION
Definition: remux.c:27
~cTsToPes()
Definition: remux.c:1039
#define MAXLANGCODE1
Definition: channels.h:36
int TsGetPayload(const uchar **p)
Definition: remux.h:114
#define MAXPESLENGTH
Definition: remux.c:1071
int pmtCounter
Definition: remux.h:304
void GeneratePmt(const cChannel *Channel)
Generates a PMT section for the given Channel, for later use with GetPmt().
Definition: remux.c:510
uchar pmt[MAX_SECTION_SIZE]
Definition: remux.h:355
int32_t GetGolombSe(void)
Definition: remux.c:1398
void TsHidePayload(uchar *p)
Definition: remux.c:121
#define P_TSID
Definition: remux.c:462
int length
Definition: remux.h:229
uint16_t compositionPageIds[MAXSPIDS]
Definition: remux.h:372
void PesDump(const char *Name, const u_char *Data, int Length)
Definition: remux.c:1162
int counter
Definition: remux.h:435
int pmtPids[MAX_PMT_PIDS+1]
Definition: remux.h:359
virtual int Parse(const uchar *Data, int Length, int Pid)
Parses the given Data, which is a sequence of Length bytes of TS packets.
Definition: remux.c:1581
uint16_t CompositionPageId(int i) const
Definition: channels.h:167
int getSectionNumber() const
Definition: si.c:88
bool CheckCRCAndParse()
Definition: si.c:65
uint32_t GetBits(int Bits)
Definition: remux.c:1382
bool frame_mbs_only_flag
Definition: remux.c:1316
static void SetBrokenLink(uchar *Data, int Length)
Definition: remux.c:102
bool completed
Definition: remux.h:375
virtual ~cFrameParser()
Definition: remux.c:1177
static bool DebugFrames
Definition: remux.c:21
Definition: device.h:67
uchar SubtitlingType(int i) const
Definition: channels.h:166
bool seenIndependentFrame
Definition: remux.c:1228
int Vpid(void) const
Definition: channels.h:152
int patVersion
Definition: remux.h:305
int UseDolbyDigital
Definition: config.h:320
cFrameParser * parser
Definition: remux.h:524
int numPacketsOther
Definition: remux.h:233
#define MAXDPIDS
Definition: channels.h:32
int spids[MAXSPIDS+1]
Definition: remux.h:369
#define MIN_TS_PACKETS_FOR_FRAME_DETECTOR
Definition: remux.h:503
int version
Definition: remux.h:436
int size
Definition: remux.h:453
#define PCRFACTOR
Definition: remux.h:58
void EnsureAudioTrack(bool Force=false)
Makes sure an audio track is selected that is actually available.
Definition: device.c:1150
#define PATPID
Definition: remux.h:52
int getTransportStreamId() const
Definition: section.c:26
#define MAX_PMT_PIDS
Definition: remux.h:351
static cDevice * PrimaryDevice(void)
Returns the primary device.
Definition: device.h:146
bool PesHasLength(const uchar *p)
Definition: remux.h:168
#define P_PMT_PID
Definition: remux.c:463
#define TS_SYNC(Data, Length)
Definition: remux.h:149
int64_t TsGetPts(const uchar *p, int l)
Definition: remux.c:160
#define KILOBYTE(n)
Definition: tools.h:44
uchar * AddParentalRatingDescriptor(uchar *p, uchar ParentalRating=0)
Definition: remux.c:959
unsigned char u_char
Definition: headers.h:24
bool TsIsScrambled(const uchar *p)
Definition: remux.h:93
int64_t PesGetDts(const uchar *p)
Definition: remux.h:202
cTsPayload tsPayload
Definition: remux.c:1318
ePesHeader
Definition: remux.h:16
void SetByte(uchar Byte, int Index)
Sets the TS data byte at the given Index to the value Byte.
Definition: remux.c:328
uchar * esInfoLength
Definition: remux.h:308
#define TS_PAYLOAD_START
Definition: remux.h:36
bool updatePrimaryDevice
Definition: remux.h:374
DescriptorLoop streamDescriptors
Definition: section.h:63
void Reset(void)
Definition: remux.c:265
#define MAXSPIDS
Definition: channels.h:33
bool newFrame
Definition: remux.h:513
bool gotSequenceParameterSet
Definition: remux.c:1321
void Statistics(void) const
May be called after a new frame has been detected, and will log a warning if the number of TS packets...
Definition: remux.c:351
uint16_t AncillaryPageId(int i) const
Definition: channels.h:168
DescriptorTag getDescriptorTag() const
Definition: si.c:100
#define TS_SIZE
Definition: remux.h:34
cMpeg2Parser(void)
Definition: remux.c:1235
Definition: remux.h:19
void IncVersion(int &Version)
Definition: remux.c:378
const uchar * GetPes(int &Length)
Gets a pointer to the complete PES packet, or NULL if the packet is not complete yet.
Definition: remux.c:1073
int getPCRPid() const
Definition: section.c:61
uint32_t GetGolombUe(void)
Definition: remux.c:1390
int bit
Definition: remux.c:1311
int getPid() const
Definition: section.c:34
int log2_max_frame_num
Definition: remux.c:1315
#define EITPID
Definition: remux.h:54
void SetDebug(bool Debug)
Definition: remux.c:1185
int TsPayloadOffset(const uchar *p)
Definition: remux.h:108
bool scanning
Definition: remux.h:523
int offset
Definition: remux.h:455
#define TS_ADAPT_PCR
Definition: remux.h:46
int numIFrames
Definition: remux.h:517
bool NewFrame(void)
Definition: remux.c:1186
void SetRepeatLast(void)
Makes the next call to GetPes() return exactly the same data as the last one (provided there was no c...
Definition: remux.c:1121
bool AtTsStart(void)
Returns true if this payload handler is currently pointing to first byte of a TS packet.
Definition: remux.h:249
cEitGenerator(int Sid=0)
Definition: remux.c:945
void TsSetPts(uchar *p, int l, int64_t Pts)
Definition: remux.c:186
const char * I18nNormalizeLanguageCode(const char *Code)
Returns a 3 letter language code that may not be zero terminated.
Definition: i18n.c:238
static int CmpUint32(const void *p1, const void *p2)
Definition: remux.c:1626
void Reset(void)
Resets the parser.
Definition: remux.c:617
Descriptor * getNext(Iterator &it)
Definition: si.c:112
uchar * data
Definition: remux.h:452
uchar * GetPat(void)
Returns a pointer to the PAT section, which consists of exactly one TS packet.
Definition: remux.c:594
int getLastSectionNumber() const
Definition: si.c:92
int patVersion
Definition: remux.h:357
int vtype
Definition: remux.h:362
#define dbgframes(a...)
Definition: remux.c:24
int pmtVersion
Definition: remux.h:306
bool SkipPesHeader(void)
Skips all bytes belonging to the PES header of the payload.
Definition: remux.c:318
uint32_t scanner
Definition: remux.c:1227
cTsToPes(void)
Definition: remux.c:1032
int apids[MAXAPIDS+1]
Definition: remux.h:363
#define MAXAPIDS
Definition: channels.h:31
cAudioParser(void)
Definition: remux.c:1207