vdr  2.0.6
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 2.75.1.5 2014/03/08 15:10:24 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
84  PesPayloadOffset++;
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 int64_t TsGetPts(const uchar *p, int l)
148 {
149  // Find the first packet with a PTS and use it:
150  while (l > 0) {
151  const uchar *d = p;
152  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasPts(d))
153  return PesGetPts(d);
154  p += TS_SIZE;
155  l -= TS_SIZE;
156  }
157  return -1;
158 }
159 
160 int64_t TsGetDts(const uchar *p, int l)
161 {
162  // Find the first packet with a DTS and use it:
163  while (l > 0) {
164  const uchar *d = p;
165  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasDts(d))
166  return PesGetDts(d);
167  p += TS_SIZE;
168  l -= TS_SIZE;
169  }
170  return -1;
171 }
172 
173 void TsSetPts(uchar *p, int l, int64_t Pts)
174 {
175  // Find the first packet with a PTS and use it:
176  while (l > 0) {
177  const uchar *d = p;
178  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasPts(d)) {
179  PesSetPts(const_cast<uchar *>(d), Pts);
180  return;
181  }
182  p += TS_SIZE;
183  l -= TS_SIZE;
184  }
185 }
186 
187 void TsSetDts(uchar *p, int l, int64_t Dts)
188 {
189  // Find the first packet with a DTS and use it:
190  while (l > 0) {
191  const uchar *d = p;
192  if (TsPayloadStart(d) && TsGetPayload(&d) && PesHasDts(d)) {
193  PesSetDts(const_cast<uchar *>(d), Dts);
194  return;
195  }
196  p += TS_SIZE;
197  l -= TS_SIZE;
198  }
199 }
200 
201 // --- Some PES handling tools -----------------------------------------------
202 
203 void PesSetPts(uchar *p, int64_t Pts)
204 {
205  p[ 9] = ((Pts >> 29) & 0x0E) | (p[9] & 0xF1);
206  p[10] = Pts >> 22;
207  p[11] = ((Pts >> 14) & 0xFE) | 0x01;
208  p[12] = Pts >> 7;
209  p[13] = ((Pts << 1) & 0xFE) | 0x01;
210 }
211 
212 void PesSetDts(uchar *p, int64_t Dts)
213 {
214  p[14] = ((Dts >> 29) & 0x0E) | (p[14] & 0xF1);
215  p[15] = Dts >> 22;
216  p[16] = ((Dts >> 14) & 0xFE) | 0x01;
217  p[17] = Dts >> 7;
218  p[18] = ((Dts << 1) & 0xFE) | 0x01;
219 }
220 
221 int64_t PtsDiff(int64_t Pts1, int64_t Pts2)
222 {
223  int64_t d = Pts2 - Pts1;
224  if (d > MAX33BIT / 2)
225  return d - (MAX33BIT + 1);
226  if (d < -MAX33BIT / 2)
227  return d + (MAX33BIT + 1);
228  return d;
229 }
230 
231 // --- cTsPayload ------------------------------------------------------------
232 
234 {
235  data = NULL;
236  length = 0;
237  pid = -1;
238  Reset();
239 }
240 
241 cTsPayload::cTsPayload(uchar *Data, int Length, int Pid)
242 {
243  Setup(Data, Length, Pid);
244 }
245 
247 {
248  length = index; // triggers EOF
249  return 0x00;
250 }
251 
253 {
254  index = 0;
255  numPacketsPid = 0;
256  numPacketsOther = 0;
257 }
258 
259 void cTsPayload::Setup(uchar *Data, int Length, int Pid)
260 {
261  data = Data;
262  length = Length;
263  pid = Pid >= 0 ? Pid : TsPid(Data);
264  Reset();
265 }
266 
268 {
269  if (!Eof()) {
270  if (index % TS_SIZE == 0) { // encountered the next TS header
271  for (;; index += TS_SIZE) {
272  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
273  uchar *p = data + index;
274  if (TsPid(p) == pid) { // only handle TS packets for the initial PID
276  return SetEof();
277  if (TsHasPayload(p)) {
278  if (index > 0 && TsPayloadStart(p)) // checking index to not skip the very first TS packet
279  return SetEof();
280  index += TsPayloadOffset(p);
281  break;
282  }
283  }
284  else if (TsPid(p) == PATPID)
285  return SetEof(); // caller must see PAT packets in case of index regeneration
286  else
287  numPacketsOther++;
288  }
289  else
290  return SetEof();
291  }
292  }
293  return data[index++];
294  }
295  return 0x00;
296 }
297 
298 bool cTsPayload::SkipBytes(int Bytes)
299 {
300  while (Bytes-- > 0)
301  GetByte();
302  return !Eof();
303 }
304 
306 {
308 }
309 
311 {
312  return index - 1;
313 }
314 
315 void cTsPayload::SetByte(uchar Byte, int Index)
316 {
317  if (Index >= 0 && Index < length)
318  data[Index] = Byte;
319 }
320 
321 bool cTsPayload::Find(uint32_t Code)
322 {
323  int OldIndex = index;
324  int OldNumPacketsPid = numPacketsPid;
325  int OldNumPacketsOther = numPacketsOther;
326  uint32_t Scanner = EMPTY_SCANNER;
327  while (!Eof()) {
328  Scanner = (Scanner << 8) | GetByte();
329  if (Scanner == Code)
330  return true;
331  }
332  index = OldIndex;
333  numPacketsPid = OldNumPacketsPid;
334  numPacketsOther = OldNumPacketsOther;
335  return false;
336 }
337 
338 void cTsPayload::Statistics(void) const
339 {
341  dsyslog("WARNING: required (%d+%d) TS packets to determine frame type", numPacketsOther, numPacketsPid);
343  dsyslog("WARNING: required %d video TS packets to determine frame type", numPacketsPid);
344 }
345 
346 void TsExtendAdaptionField(unsigned char *Packet, int ToLength)
347 {
348  // Hint: ExtenAdaptionField(p, TsPayloadOffset(p) - 4) is a null operation
349 
350  int Offset = TsPayloadOffset(Packet); // First byte after existing adaption field
351 
352  if (ToLength <= 0)
353  {
354  // Remove adaption field
355  Packet[3] = Packet[3] & ~TS_ADAPT_FIELD_EXISTS;
356  return;
357  }
358 
359  // Set adaption field present
360  Packet[3] = Packet[3] | TS_ADAPT_FIELD_EXISTS;
361 
362  // Set new length of adaption field:
363  Packet[4] = ToLength <= TS_SIZE-4 ? ToLength-1 : TS_SIZE-4-1;
364 
365  if (Packet[4] == TS_SIZE-4-1)
366  {
367  // No more payload, remove payload flag
368  Packet[3] = Packet[3] & ~TS_PAYLOAD_EXISTS;
369  }
370 
371  int NewPayload = TsPayloadOffset(Packet); // First byte after new adaption field
372 
373  // Fill new adaption field
374  if (Offset == 4 && Offset < NewPayload)
375  Offset++; // skip adaptation_field_length
376  if (Offset == 5 && Offset < NewPayload)
377  Packet[Offset++] = 0; // various flags set to 0
378  while (Offset < NewPayload)
379  Packet[Offset++] = 0xff; // stuffing byte
380 }
381 
382 // --- cPatPmtGenerator ------------------------------------------------------
383 
385 {
386  numPmtPackets = 0;
387  patCounter = pmtCounter = 0;
388  patVersion = pmtVersion = 0;
389  pmtPid = 0;
390  esInfoLength = NULL;
391  SetChannel(Channel);
392 }
393 
394 void cPatPmtGenerator::IncCounter(int &Counter, uchar *TsPacket)
395 {
396  TsPacket[3] = (TsPacket[3] & 0xF0) | Counter;
397  if (++Counter > 0x0F)
398  Counter = 0x00;
399 }
400 
402 {
403  if (++Version > 0x1F)
404  Version = 0x00;
405 }
406 
408 {
409  if (esInfoLength) {
410  Length += ((*esInfoLength & 0x0F) << 8) | *(esInfoLength + 1);
411  *esInfoLength = 0xF0 | (Length >> 8);
412  *(esInfoLength + 1) = Length;
413  }
414 }
415 
416 int cPatPmtGenerator::MakeStream(uchar *Target, uchar Type, int Pid)
417 {
418  int i = 0;
419  Target[i++] = Type; // stream type
420  Target[i++] = 0xE0 | (Pid >> 8); // dummy (3), pid hi (5)
421  Target[i++] = Pid; // pid lo
422  esInfoLength = &Target[i];
423  Target[i++] = 0xF0; // dummy (4), ES info length hi
424  Target[i++] = 0x00; // ES info length lo
425  return i;
426 }
427 
429 {
430  int i = 0;
431  Target[i++] = Type;
432  Target[i++] = 0x01; // length
433  Target[i++] = 0x00;
434  IncEsInfoLength(i);
435  return i;
436 }
437 
438 int cPatPmtGenerator::MakeSubtitlingDescriptor(uchar *Target, const char *Language, uchar SubtitlingType, uint16_t CompositionPageId, uint16_t AncillaryPageId)
439 {
440  int i = 0;
441  Target[i++] = SI::SubtitlingDescriptorTag;
442  Target[i++] = 0x08; // length
443  Target[i++] = *Language++;
444  Target[i++] = *Language++;
445  Target[i++] = *Language++;
446  Target[i++] = SubtitlingType;
447  Target[i++] = CompositionPageId >> 8;
448  Target[i++] = CompositionPageId & 0xFF;
449  Target[i++] = AncillaryPageId >> 8;
450  Target[i++] = AncillaryPageId & 0xFF;
451  IncEsInfoLength(i);
452  return i;
453 }
454 
456 {
457  int i = 0, j = 0;
458  Target[i++] = SI::TeletextDescriptorTag;
459  int l = i;
460  Target[i++] = 0x00; // length
461  for (int n = 0; n < pageCount; n++) {
462  const char* Language = pages[n].ttxtLanguage;
463  Target[i++] = *Language++;
464  Target[i++] = *Language++;
465  Target[i++] = *Language++;
466  Target[i++] = (pages[n].ttxtType << 3) + pages[n].ttxtMagazine;
467  Target[i++] = pages[n].ttxtPage;
468  j++;
469  }
470  if (j > 0) {
471  Target[l] = j * 5; // update length
472  IncEsInfoLength(i);
473  return i;
474  }
475  return 0;
476 }
477 
478 int cPatPmtGenerator::MakeLanguageDescriptor(uchar *Target, const char *Language)
479 {
480  int i = 0;
481  Target[i++] = SI::ISO639LanguageDescriptorTag;
482  int Length = i++;
483  Target[Length] = 0x00; // length
484  for (const char *End = Language + strlen(Language); Language < End; ) {
485  Target[i++] = *Language++;
486  Target[i++] = *Language++;
487  Target[i++] = *Language++;
488  Target[i++] = 0x00; // audio type
489  Target[Length] += 0x04; // length
490  if (*Language == '+')
491  Language++;
492  }
493  IncEsInfoLength(i);
494  return i;
495 }
496 
497 int cPatPmtGenerator::MakeCRC(uchar *Target, const uchar *Data, int Length)
498 {
499  int crc = SI::CRC32::crc32((const char *)Data, Length, 0xFFFFFFFF);
500  int i = 0;
501  Target[i++] = crc >> 24;
502  Target[i++] = crc >> 16;
503  Target[i++] = crc >> 8;
504  Target[i++] = crc;
505  return i;
506 }
507 
508 #define P_TSID 0x8008 // pseudo TS ID
509 #define P_PMT_PID 0x0084 // pseudo PMT pid
510 #define MAXPID 0x2000 // the maximum possible number of pids
511 
513 {
514  bool Used[MAXPID] = { false };
515 #define SETPID(p) { if ((p) >= 0 && (p) < MAXPID) Used[p] = true; }
516 #define SETPIDS(l) { const int *p = l; while (*p) { SETPID(*p); p++; } }
517  SETPID(Channel->Vpid());
518  SETPID(Channel->Ppid());
519  SETPID(Channel->Tpid());
520  SETPIDS(Channel->Apids());
521  SETPIDS(Channel->Dpids());
522  SETPIDS(Channel->Spids());
523  for (pmtPid = P_PMT_PID; Used[pmtPid]; pmtPid++)
524  ;
525 }
526 
528 {
529  memset(pat, 0xFF, sizeof(pat));
530  uchar *p = pat;
531  int i = 0;
532  p[i++] = TS_SYNC_BYTE; // TS indicator
533  p[i++] = TS_PAYLOAD_START | (PATPID >> 8); // flags (3), pid hi (5)
534  p[i++] = PATPID & 0xFF; // pid lo
535  p[i++] = 0x10; // flags (4), continuity counter (4)
536  p[i++] = 0x00; // pointer field (payload unit start indicator is set)
537  int PayloadStart = i;
538  p[i++] = 0x00; // table id
539  p[i++] = 0xB0; // section syntax indicator (1), dummy (3), section length hi (4)
540  int SectionLength = i;
541  p[i++] = 0x00; // section length lo (filled in later)
542  p[i++] = P_TSID >> 8; // TS id hi
543  p[i++] = P_TSID & 0xFF; // TS id lo
544  p[i++] = 0xC1 | (patVersion << 1); // dummy (2), version number (5), current/next indicator (1)
545  p[i++] = 0x00; // section number
546  p[i++] = 0x00; // last section number
547  p[i++] = pmtPid >> 8; // program number hi
548  p[i++] = pmtPid & 0xFF; // program number lo
549  p[i++] = 0xE0 | (pmtPid >> 8); // dummy (3), PMT pid hi (5)
550  p[i++] = pmtPid & 0xFF; // PMT pid lo
551  pat[SectionLength] = i - SectionLength - 1 + 4; // -2 = SectionLength storage, +4 = length of CRC
552  MakeCRC(pat + i, pat + PayloadStart, i - PayloadStart);
554 }
555 
557 {
558  // generate the complete PMT section:
559  uchar buf[MAX_SECTION_SIZE];
560  memset(buf, 0xFF, sizeof(buf));
561  numPmtPackets = 0;
562  if (Channel) {
563  int Vpid = Channel->Vpid();
564  int Ppid = Channel->Ppid();
565  int Tpid = Channel->Tpid();
566  uchar *p = buf;
567  int i = 0;
568  p[i++] = 0x02; // table id
569  int SectionLength = i;
570  p[i++] = 0xB0; // section syntax indicator (1), dummy (3), section length hi (4)
571  p[i++] = 0x00; // section length lo (filled in later)
572  p[i++] = pmtPid >> 8; // program number hi
573  p[i++] = pmtPid & 0xFF; // program number lo
574  p[i++] = 0xC1 | (pmtVersion << 1); // dummy (2), version number (5), current/next indicator (1)
575  p[i++] = 0x00; // section number
576  p[i++] = 0x00; // last section number
577  p[i++] = 0xE0 | (Ppid >> 8); // dummy (3), PCR pid hi (5)
578  p[i++] = Ppid; // PCR pid lo
579  p[i++] = 0xF0; // dummy (4), program info length hi (4)
580  p[i++] = 0x00; // program info length lo
581 
582  if (Vpid)
583  i += MakeStream(buf + i, Channel->Vtype(), Vpid);
584  for (int n = 0; Channel->Apid(n); n++) {
585  i += MakeStream(buf + i, Channel->Atype(n), Channel->Apid(n));
586  const char *Alang = Channel->Alang(n);
587  i += MakeLanguageDescriptor(buf + i, Alang);
588  }
589  for (int n = 0; Channel->Dpid(n); n++) {
590  i += MakeStream(buf + i, 0x06, Channel->Dpid(n));
591  i += MakeAC3Descriptor(buf + i, Channel->Dtype(n));
592  i += MakeLanguageDescriptor(buf + i, Channel->Dlang(n));
593  }
594  for (int n = 0; Channel->Spid(n); n++) {
595  i += MakeStream(buf + i, 0x06, Channel->Spid(n));
596  i += MakeSubtitlingDescriptor(buf + i, Channel->Slang(n), Channel->SubtitlingType(n), Channel->CompositionPageId(n), Channel->AncillaryPageId(n));
597  }
598  if (Tpid) {
599  i += MakeStream(buf + i, 0x06, Tpid);
600  i += MakeTeletextDescriptor(buf + i, Channel->TeletextSubtitlePages(), Channel->TotalTeletextSubtitlePages());
601  }
602 
603  int sl = i - SectionLength - 2 + 4; // -2 = SectionLength storage, +4 = length of CRC
604  buf[SectionLength] |= (sl >> 8) & 0x0F;
605  buf[SectionLength + 1] = sl;
606  MakeCRC(buf + i, buf, i);
607  // split the PMT section into several TS packets:
608  uchar *q = buf;
609  bool pusi = true;
610  while (i > 0) {
611  uchar *p = pmt[numPmtPackets++];
612  int j = 0;
613  p[j++] = TS_SYNC_BYTE; // TS indicator
614  p[j++] = (pusi ? TS_PAYLOAD_START : 0x00) | (pmtPid >> 8); // flags (3), pid hi (5)
615  p[j++] = pmtPid & 0xFF; // pid lo
616  p[j++] = 0x10; // flags (4), continuity counter (4)
617  if (pusi) {
618  p[j++] = 0x00; // pointer field (payload unit start indicator is set)
619  pusi = false;
620  }
621  int l = TS_SIZE - j;
622  memcpy(p + j, q, l);
623  q += l;
624  i -= l;
625  }
627  }
628 }
629 
630 void cPatPmtGenerator::SetVersions(int PatVersion, int PmtVersion)
631 {
632  patVersion = PatVersion & 0x1F;
633  pmtVersion = PmtVersion & 0x1F;
634 }
635 
637 {
638  if (Channel) {
639  GeneratePmtPid(Channel);
640  GeneratePat();
641  GeneratePmt(Channel);
642  }
643 }
644 
646 {
648  return pat;
649 }
650 
652 {
653  if (Index < numPmtPackets) {
654  IncCounter(pmtCounter, pmt[Index]);
655  return pmt[Index++];
656  }
657  return NULL;
658 }
659 
660 // --- cPatPmtParser ---------------------------------------------------------
661 
662 cPatPmtParser::cPatPmtParser(bool UpdatePrimaryDevice)
663 {
664  updatePrimaryDevice = UpdatePrimaryDevice;
665  Reset();
666 }
667 
669 {
670  pmtSize = 0;
671  patVersion = pmtVersion = -1;
672  pmtPids[0] = 0;
673  vpid = vtype = 0;
674  ppid = 0;
675  tpid = 0;
676 }
677 
678 void cPatPmtParser::ParsePat(const uchar *Data, int Length)
679 {
680  // Unpack the TS packet:
681  int PayloadOffset = TsPayloadOffset(Data);
682  Data += PayloadOffset;
683  Length -= PayloadOffset;
684  // The PAT is always assumed to fit into a single TS packet
685  if ((Length -= Data[0] + 1) <= 0)
686  return;
687  Data += Data[0] + 1; // process pointer_field
688  SI::PAT Pat(Data, false);
689  if (Pat.CheckCRCAndParse()) {
690  dbgpatpmt("PAT: TSid = %d, c/n = %d, v = %d, s = %d, ls = %d\n", Pat.getTransportStreamId(), Pat.getCurrentNextIndicator(), Pat.getVersionNumber(), Pat.getSectionNumber(), Pat.getLastSectionNumber());
691  if (patVersion == Pat.getVersionNumber())
692  return;
693  int NumPmtPids = 0;
694  SI::PAT::Association assoc;
695  for (SI::Loop::Iterator it; Pat.associationLoop.getNext(assoc, it); ) {
696  dbgpatpmt(" isNITPid = %d\n", assoc.isNITPid());
697  if (!assoc.isNITPid()) {
698  if (NumPmtPids <= MAX_PMT_PIDS)
699  pmtPids[NumPmtPids++] = assoc.getPid();
700  dbgpatpmt(" service id = %d, pid = %d\n", assoc.getServiceId(), assoc.getPid());
701  }
702  }
703  pmtPids[NumPmtPids] = 0;
705  }
706  else
707  esyslog("ERROR: can't parse PAT");
708 }
709 
710 void cPatPmtParser::ParsePmt(const uchar *Data, int Length)
711 {
712  // Unpack the TS packet:
713  bool PayloadStart = TsPayloadStart(Data);
714  int PayloadOffset = TsPayloadOffset(Data);
715  Data += PayloadOffset;
716  Length -= PayloadOffset;
717  // The PMT may extend over several TS packets, so we need to assemble them
718  if (PayloadStart) {
719  pmtSize = 0;
720  if ((Length -= Data[0] + 1) <= 0)
721  return;
722  Data += Data[0] + 1; // this is the first packet
723  if (SectionLength(Data, Length) > Length) {
724  if (Length <= int(sizeof(pmt))) {
725  memcpy(pmt, Data, Length);
726  pmtSize = Length;
727  }
728  else
729  esyslog("ERROR: PMT packet length too big (%d byte)!", Length);
730  return;
731  }
732  // the packet contains the entire PMT section, so we run into the actual parsing
733  }
734  else if (pmtSize > 0) {
735  // this is a following packet, so we add it to the pmt storage
736  if (Length <= int(sizeof(pmt)) - pmtSize) {
737  memcpy(pmt + pmtSize, Data, Length);
738  pmtSize += Length;
739  }
740  else {
741  esyslog("ERROR: PMT section length too big (%d byte)!", pmtSize + Length);
742  pmtSize = 0;
743  }
745  return; // more packets to come
746  // the PMT section is now complete, so we run into the actual parsing
747  Data = pmt;
748  }
749  else
750  return; // fragment of broken packet - ignore
751  SI::PMT Pmt(Data, false);
752  if (Pmt.CheckCRCAndParse()) {
753  dbgpatpmt("PMT: sid = %d, c/n = %d, v = %d, s = %d, ls = %d\n", Pmt.getServiceId(), Pmt.getCurrentNextIndicator(), Pmt.getVersionNumber(), Pmt.getSectionNumber(), Pmt.getLastSectionNumber());
754  dbgpatpmt(" pcr = %d\n", Pmt.getPCRPid());
755  if (pmtVersion == Pmt.getVersionNumber())
756  return;
759  int NumApids = 0;
760  int NumDpids = 0;
761  int NumSpids = 0;
762  vpid = vtype = 0;
763  ppid = 0;
764  tpid = 0;
765  apids[0] = 0;
766  dpids[0] = 0;
767  spids[0] = 0;
768  atypes[0] = 0;
769  dtypes[0] = 0;
771  SI::PMT::Stream stream;
772  for (SI::Loop::Iterator it; Pmt.streamLoop.getNext(stream, it); ) {
773  dbgpatpmt(" stream type = %02X, pid = %d", stream.getStreamType(), stream.getPid());
774  switch (stream.getStreamType()) {
775  case 0x01: // STREAMTYPE_11172_VIDEO
776  case 0x02: // STREAMTYPE_13818_VIDEO
777  case 0x1B: // H.264
778  vpid = stream.getPid();
779  vtype = stream.getStreamType();
780  ppid = Pmt.getPCRPid();
781  break;
782  case 0x03: // STREAMTYPE_11172_AUDIO
783  case 0x04: // STREAMTYPE_13818_AUDIO
784  case 0x0F: // ISO/IEC 13818-7 Audio with ADTS transport syntax
785  case 0x11: // ISO/IEC 14496-3 Audio with LATM transport syntax
786  {
787  if (NumApids < MAXAPIDS) {
788  apids[NumApids] = stream.getPid();
789  atypes[NumApids] = stream.getStreamType();
790  *alangs[NumApids] = 0;
791  SI::Descriptor *d;
792  for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) {
793  switch (d->getDescriptorTag()) {
797  char *s = alangs[NumApids];
798  int n = 0;
799  for (SI::Loop::Iterator it; ld->languageLoop.getNext(l, it); ) {
800  if (*ld->languageCode != '-') { // some use "---" to indicate "none"
801  dbgpatpmt(" '%s'", l.languageCode);
802  if (n > 0)
803  *s++ = '+';
805  s += strlen(s);
806  if (n++ > 1)
807  break;
808  }
809  }
810  }
811  break;
812  default: ;
813  }
814  delete d;
815  }
817  cDevice::PrimaryDevice()->SetAvailableTrack(ttAudio, NumApids, apids[NumApids], alangs[NumApids]);
818  NumApids++;
819  apids[NumApids] = 0;
820  }
821  }
822  break;
823  case 0x06: // STREAMTYPE_13818_PES_PRIVATE
824  {
825  int dpid = 0;
826  int dtype = 0;
827  char lang[MAXLANGCODE1] = "";
828  SI::Descriptor *d;
829  for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) {
830  switch (d->getDescriptorTag()) {
833  dbgpatpmt(" AC3");
834  dpid = stream.getPid();
835  dtype = d->getDescriptorTag();
836  break;
838  dbgpatpmt(" subtitling");
839  if (NumSpids < MAXSPIDS) {
840  spids[NumSpids] = stream.getPid();
841  *slangs[NumSpids] = 0;
842  subtitlingTypes[NumSpids] = 0;
843  compositionPageIds[NumSpids] = 0;
844  ancillaryPageIds[NumSpids] = 0;
847  char *s = slangs[NumSpids];
848  int n = 0;
849  for (SI::Loop::Iterator it; sd->subtitlingLoop.getNext(sub, it); ) {
850  if (sub.languageCode[0]) {
851  dbgpatpmt(" '%s'", sub.languageCode);
852  subtitlingTypes[NumSpids] = sub.getSubtitlingType();
853  compositionPageIds[NumSpids] = sub.getCompositionPageId();
854  ancillaryPageIds[NumSpids] = sub.getAncillaryPageId();
855  if (n > 0)
856  *s++ = '+';
858  s += strlen(s);
859  if (n++ > 1)
860  break;
861  }
862  }
864  cDevice::PrimaryDevice()->SetAvailableTrack(ttSubtitle, NumSpids, spids[NumSpids], slangs[NumSpids]);
865  NumSpids++;
866  spids[NumSpids] = 0;
867  }
868  break;
870  dbgpatpmt(" teletext");
871  tpid = stream.getPid();
875  for (SI::Loop::Iterator it; sd->teletextLoop.getNext(ttxt, it); ) {
876  bool isSubtitlePage = (ttxt.getTeletextType() == 0x02) || (ttxt.getTeletextType() == 0x05);
877  if (isSubtitlePage && ttxt.languageCode[0]) {
878  dbgpatpmt(" '%s:%x.%x'", ttxt.languageCode, ttxt.getTeletextMagazineNumber(), ttxt.getTeletextPageNumber());
885  break;
886  }
887  }
888  }
889  }
890  break;
893  dbgpatpmt(" '%s'", ld->languageCode);
895  }
896  break;
897  default: ;
898  }
899  delete d;
900  }
901  if (dpid) {
902  if (NumDpids < MAXDPIDS) {
903  dpids[NumDpids] = dpid;
904  dtypes[NumDpids] = dtype;
905  strn0cpy(dlangs[NumDpids], lang, sizeof(dlangs[NumDpids]));
907  cDevice::PrimaryDevice()->SetAvailableTrack(ttDolby, NumDpids, dpid, lang);
908  NumDpids++;
909  dpids[NumDpids] = 0;
910  }
911  }
912  }
913  break;
914  case 0x81: // STREAMTYPE_USER_PRIVATE
915  {
916  dbgpatpmt(" AC3");
917  char lang[MAXLANGCODE1] = { 0 };
918  SI::Descriptor *d;
919  for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) {
920  switch (d->getDescriptorTag()) {
923  dbgpatpmt(" '%s'", ld->languageCode);
925  }
926  break;
927  default: ;
928  }
929  delete d;
930  }
931  if (NumDpids < MAXDPIDS) {
932  dpids[NumDpids] = stream.getPid();
933  dtypes[NumDpids] = SI::AC3DescriptorTag;
934  strn0cpy(dlangs[NumDpids], lang, sizeof(dlangs[NumDpids]));
936  cDevice::PrimaryDevice()->SetAvailableTrack(ttDolby, NumDpids, stream.getPid(), lang);
937  NumDpids++;
938  dpids[NumDpids] = 0;
939  }
940  }
941  break;
942  default: ;
943  }
944  dbgpatpmt("\n");
945  if (updatePrimaryDevice) {
948  }
949  }
951  }
952  else
953  esyslog("ERROR: can't parse PMT");
954  pmtSize = 0;
955 }
956 
957 bool cPatPmtParser::ParsePatPmt(const uchar *Data, int Length)
958 {
959  while (Length >= TS_SIZE) {
960  if (*Data != TS_SYNC_BYTE)
961  break; // just for safety
962  int Pid = TsPid(Data);
963  if (Pid == PATPID)
964  ParsePat(Data, TS_SIZE);
965  else if (IsPmtPid(Pid)) {
966  ParsePmt(Data, TS_SIZE);
967  if (patVersion >= 0 && pmtVersion >= 0)
968  return true;
969  }
970  Data += TS_SIZE;
971  Length -= TS_SIZE;
972  }
973  return false;
974 }
975 
976 bool cPatPmtParser::GetVersions(int &PatVersion, int &PmtVersion) const
977 {
978  PatVersion = patVersion;
979  PmtVersion = pmtVersion;
980  return patVersion >= 0 && pmtVersion >= 0;
981 }
982 
983 // --- cTsToPes --------------------------------------------------------------
984 
986 {
987  data = NULL;
988  size = 0;
989  Reset();
990 }
991 
993 {
994  free(data);
995 }
996 
997 void cTsToPes::PutTs(const uchar *Data, int Length)
998 {
999  if (TsError(Data)) {
1000  Reset();
1001  return; // ignore packets with TEI set, and drop any PES data collected so far
1002  }
1003  if (TsPayloadStart(Data))
1004  Reset();
1005  else if (!size)
1006  return; // skip everything before the first payload start
1007  Length = TsGetPayload(&Data);
1008  if (length + Length > size) {
1009  int NewSize = max(KILOBYTE(2), length + Length);
1010  if (uchar *NewData = (uchar *)realloc(data, NewSize)) {
1011  data = NewData;
1012  size = NewSize;
1013  }
1014  else {
1015  esyslog("ERROR: out of memory");
1016  Reset();
1017  return;
1018  }
1019  }
1020  memcpy(data + length, Data, Length);
1021  length += Length;
1022 }
1023 
1024 #define MAXPESLENGTH 0xFFF0
1025 
1026 const uchar *cTsToPes::GetPes(int &Length)
1027 {
1028  if (repeatLast) {
1029  repeatLast = false;
1030  Length = lastLength;
1031  return lastData;
1032  }
1033  if (offset < length && PesLongEnough(length)) {
1034  if (!PesHasLength(data)) // this is a video PES packet with undefined length
1035  offset = 6; // trigger setting PES length for initial slice
1036  if (offset) {
1037  uchar *p = data + offset - 6;
1038  if (p != data) {
1039  p -= 3;
1040  if (p < data) {
1041  Reset();
1042  return NULL;
1043  }
1044  memmove(p, data, 4);
1045  }
1046  int l = min(length - offset, MAXPESLENGTH);
1047  offset += l;
1048  if (p != data) {
1049  l += 3;
1050  p[6] = 0x80;
1051  p[7] = 0x00;
1052  p[8] = 0x00;
1053  }
1054  p[4] = l / 256;
1055  p[5] = l & 0xFF;
1056  Length = l + 6;
1057  lastLength = Length;
1058  lastData = p;
1059  return p;
1060  }
1061  else {
1062  Length = PesLength(data);
1063  if (Length <= length) {
1064  offset = Length; // to make sure we break out in case of garbage data
1065  lastLength = Length;
1066  lastData = data;
1067  return data;
1068  }
1069  }
1070  }
1071  return NULL;
1072 }
1073 
1075 {
1076  repeatLast = true;
1077 }
1078 
1080 {
1081  length = offset = 0;
1082  lastData = NULL;
1083  lastLength = 0;
1084  repeatLast = false;
1085 }
1086 
1087 // --- Some helper functions for debugging -----------------------------------
1088 
1089 void BlockDump(const char *Name, const u_char *Data, int Length)
1090 {
1091  printf("--- %s\n", Name);
1092  for (int i = 0; i < Length; i++) {
1093  if (i && (i % 16) == 0)
1094  printf("\n");
1095  printf(" %02X", Data[i]);
1096  }
1097  printf("\n");
1098 }
1099 
1100 void TsDump(const char *Name, const u_char *Data, int Length)
1101 {
1102  printf("%s: %04X", Name, Length);
1103  int n = min(Length, 20);
1104  for (int i = 0; i < n; i++)
1105  printf(" %02X", Data[i]);
1106  if (n < Length) {
1107  printf(" ...");
1108  n = max(n, Length - 10);
1109  for (n = max(n, Length - 10); n < Length; n++)
1110  printf(" %02X", Data[n]);
1111  }
1112  printf("\n");
1113 }
1114 
1115 void PesDump(const char *Name, const u_char *Data, int Length)
1116 {
1117  TsDump(Name, Data, Length);
1118 }
1119 
1120 // --- cFrameParser ----------------------------------------------------------
1121 
1123 protected:
1124  bool debug;
1125  bool newFrame;
1128 public:
1129  cFrameParser(void);
1130  virtual ~cFrameParser() {};
1131  virtual int Parse(const uchar *Data, int Length, int Pid) = 0;
1138  void SetDebug(bool Debug) { debug = Debug; }
1139  bool NewFrame(void) { return newFrame; }
1140  bool IndependentFrame(void) { return independentFrame; }
1142  };
1143 
1145 {
1146  debug = true;
1147  newFrame = false;
1148  independentFrame = false;
1150 }
1151 
1152 // --- cAudioParser ----------------------------------------------------------
1153 
1154 class cAudioParser : public cFrameParser {
1155 public:
1156  cAudioParser(void);
1157  virtual int Parse(const uchar *Data, int Length, int Pid);
1158  };
1159 
1161 {
1162 }
1163 
1164 int cAudioParser::Parse(const uchar *Data, int Length, int Pid)
1165 {
1166  if (TsPayloadStart(Data)) {
1167  newFrame = independentFrame = true;
1168  if (debug)
1169  dbgframes("/");
1170  }
1171  else
1172  newFrame = independentFrame = false;
1173  return TS_SIZE;
1174 }
1175 
1176 // --- cMpeg2Parser ----------------------------------------------------------
1177 
1178 class cMpeg2Parser : public cFrameParser {
1179 private:
1180  uint32_t scanner;
1183 public:
1184  cMpeg2Parser(void);
1185  virtual int Parse(const uchar *Data, int Length, int Pid);
1186  };
1187 
1189 {
1191  seenIndependentFrame = false;
1192  lastIFrameTemporalReference = -1; // invalid
1193 }
1194 
1195 int cMpeg2Parser::Parse(const uchar *Data, int Length, int Pid)
1196 {
1197  newFrame = independentFrame = false;
1198  bool SeenPayloadStart = false;
1199  cTsPayload tsPayload(const_cast<uchar *>(Data), Length, Pid);
1200  if (TsPayloadStart(Data)) {
1201  SeenPayloadStart = true;
1202  tsPayload.SkipPesHeader();
1204  if (debug && seenIndependentFrame)
1205  dbgframes("/");
1206  }
1207  uint32_t OldScanner = scanner; // need to remember it in case of multiple frames per payload
1208  for (;;) {
1209  if (!SeenPayloadStart && tsPayload.AtTsStart())
1210  OldScanner = scanner;
1211  scanner = (scanner << 8) | tsPayload.GetByte();
1212  if (scanner == 0x00000100) { // Picture Start Code
1213  if (!SeenPayloadStart && tsPayload.GetLastIndex() > TS_SIZE) {
1214  scanner = OldScanner;
1215  return tsPayload.Used() - TS_SIZE;
1216  }
1217  uchar b1 = tsPayload.GetByte();
1218  uchar b2 = tsPayload.GetByte();
1219  int TemporalReference = (b1 << 2 ) + ((b2 & 0xC0) >> 6);
1220  uchar FrameType = (b2 >> 3) & 0x07;
1221  if (tsPayload.Find(0x000001B5)) { // Extension start code
1222  if (((tsPayload.GetByte() & 0xF0) >> 4) == 0x08) { // Picture coding extension
1223  tsPayload.GetByte();
1224  uchar PictureStructure = tsPayload.GetByte() & 0x03;
1225  if (PictureStructure == 0x02) // bottom field
1226  break;
1227  }
1228  }
1229  newFrame = true;
1230  independentFrame = FrameType == 1; // I-Frame
1231  if (independentFrame) {
1232  if (lastIFrameTemporalReference >= 0)
1234  lastIFrameTemporalReference = TemporalReference;
1235  }
1236  if (debug) {
1238  if (seenIndependentFrame) {
1239  static const char FrameTypes[] = "?IPBD???";
1240  dbgframes("%c", FrameTypes[FrameType]);
1241  }
1242  }
1243  tsPayload.Statistics();
1244  break;
1245  }
1246  if (tsPayload.AtPayloadStart() // stop at any new payload start to have the buffer refilled if necessary
1247  || tsPayload.Eof()) // or if we're out of data
1248  break;
1249  }
1250  return tsPayload.Used();
1251 }
1252 
1253 // --- cH264Parser -----------------------------------------------------------
1254 
1255 class cH264Parser : public cFrameParser {
1256 private:
1262  };
1264  uchar byte; // holds the current byte value in case of bitwise access
1265  int bit; // the bit index into the current byte (-1 if we're not in bit reading mode)
1266  int zeroBytes; // the number of consecutive zero bytes (to detect 0x000003)
1267  uint32_t scanner;
1268  // Identifiers written in '_' notation as in "ITU-T H.264":
1272  //
1275  uchar GetByte(bool Raw = false);
1279  uchar GetBit(void);
1280  uint32_t GetBits(int Bits);
1281  uint32_t GetGolombUe(void);
1282  int32_t GetGolombSe(void);
1283  void ParseAccessUnitDelimiter(void);
1284  void ParseSequenceParameterSet(void);
1285  void ParseSliceHeader(void);
1286 public:
1287  cH264Parser(void);
1291  virtual int Parse(const uchar *Data, int Length, int Pid);
1292  };
1293 
1295 {
1296  byte = 0;
1297  bit = -1;
1298  zeroBytes = 0;
1301  log2_max_frame_num = 0;
1302  frame_mbs_only_flag = false;
1303  gotAccessUnitDelimiter = false;
1304  gotSequenceParameterSet = false;
1305 }
1306 
1308 {
1309  uchar b = tsPayload.GetByte();
1310  if (!Raw) {
1311  // If we encounter the byte sequence 0x000003, we need to skip the 0x03:
1312  if (b == 0x00)
1313  zeroBytes++;
1314  else {
1315  if (b == 0x03 && zeroBytes >= 2)
1316  b = tsPayload.GetByte();
1317  zeroBytes = 0;
1318  }
1319  }
1320  else
1321  zeroBytes = 0;
1322  bit = -1;
1323  return b;
1324 }
1325 
1327 {
1328  if (bit < 0) {
1329  byte = GetByte();
1330  bit = 7;
1331  }
1332  return (byte & (1 << bit--)) ? 1 : 0;
1333 }
1334 
1335 uint32_t cH264Parser::GetBits(int Bits)
1336 {
1337  uint32_t b = 0;
1338  while (Bits--)
1339  b |= GetBit() << Bits;
1340  return b;
1341 }
1342 
1344 {
1345  int z = -1;
1346  for (int b = 0; !b && z < 32; z++) // limiting z to no get stuck if GetBit() always returns 0
1347  b = GetBit();
1348  return (1 << z) - 1 + GetBits(z);
1349 }
1350 
1352 {
1353  uint32_t v = GetGolombUe();
1354  if (v) {
1355  if ((v & 0x01) != 0)
1356  return (v + 1) / 2; // fails for v == 0xFFFFFFFF, but that will probably never happen
1357  else
1358  return -int32_t(v / 2);
1359  }
1360  return v;
1361 }
1362 
1363 int cH264Parser::Parse(const uchar *Data, int Length, int Pid)
1364 {
1365  newFrame = independentFrame = false;
1366  tsPayload.Setup(const_cast<uchar *>(Data), Length, Pid);
1367  if (TsPayloadStart(Data)) {
1370  if (debug && gotSequenceParameterSet) {
1371  dbgframes("/");
1372  }
1373  }
1374  for (;;) {
1375  scanner = (scanner << 8) | GetByte(true);
1376  if ((scanner & 0xFFFFFF00) == 0x00000100) { // NAL unit start
1377  uchar NalUnitType = scanner & 0x1F;
1378  switch (NalUnitType) {
1380  gotAccessUnitDelimiter = true;
1381  break;
1384  gotSequenceParameterSet = true;
1385  }
1386  break;
1387  case nutCodedSliceNonIdr:
1389  ParseSliceHeader();
1390  gotAccessUnitDelimiter = false;
1391  if (newFrame)
1393  return tsPayload.Used();
1394  }
1395  break;
1396  default: ;
1397  }
1398  }
1399  if (tsPayload.AtPayloadStart() // stop at any new payload start to have the buffer refilled if necessary
1400  || tsPayload.Eof()) // or if we're out of data
1401  break;
1402  }
1403  return tsPayload.Used();
1404 }
1405 
1407 {
1409  dbgframes("A");
1410  GetByte(); // primary_pic_type
1411 }
1412 
1414 {
1415  uchar profile_idc = GetByte(); // profile_idc
1416  GetByte(); // constraint_set[0-5]_flags, reserved_zero_2bits
1417  GetByte(); // level_idc
1418  GetGolombUe(); // seq_parameter_set_id
1419  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) {
1420  int chroma_format_idc = GetGolombUe(); // chroma_format_idc
1421  if (chroma_format_idc == 3)
1423  GetGolombUe(); // bit_depth_luma_minus8
1424  GetGolombUe(); // bit_depth_chroma_minus8
1425  GetBit(); // qpprime_y_zero_transform_bypass_flag
1426  if (GetBit()) { // seq_scaling_matrix_present_flag
1427  for (int i = 0; i < ((chroma_format_idc != 3) ? 8 : 12); i++) {
1428  if (GetBit()) { // seq_scaling_list_present_flag
1429  int SizeOfScalingList = (i < 6) ? 16 : 64;
1430  int LastScale = 8;
1431  int NextScale = 8;
1432  for (int j = 0; j < SizeOfScalingList; j++) {
1433  if (NextScale)
1434  NextScale = (LastScale + GetGolombSe() + 256) % 256; // delta_scale
1435  if (NextScale)
1436  LastScale = NextScale;
1437  }
1438  }
1439  }
1440  }
1441  }
1442  log2_max_frame_num = GetGolombUe() + 4; // log2_max_frame_num_minus4
1443  int pic_order_cnt_type = GetGolombUe(); // pic_order_cnt_type
1444  if (pic_order_cnt_type == 0)
1445  GetGolombUe(); // log2_max_pic_order_cnt_lsb_minus4
1446  else if (pic_order_cnt_type == 1) {
1447  GetBit(); // delta_pic_order_always_zero_flag
1448  GetGolombSe(); // offset_for_non_ref_pic
1449  GetGolombSe(); // offset_for_top_to_bottom_field
1450  for (int i = GetGolombUe(); i--; ) // num_ref_frames_in_pic_order_cnt_cycle
1451  GetGolombSe(); // offset_for_ref_frame
1452  }
1453  GetGolombUe(); // max_num_ref_frames
1454  GetBit(); // gaps_in_frame_num_value_allowed_flag
1455  GetGolombUe(); // pic_width_in_mbs_minus1
1456  GetGolombUe(); // pic_height_in_map_units_minus1
1457  frame_mbs_only_flag = GetBit(); // frame_mbs_only_flag
1458  if (debug) {
1460  dbgframes("A"); // just for completeness
1461  dbgframes(frame_mbs_only_flag ? "S" : "s");
1462  }
1463 }
1464 
1466 {
1467  newFrame = true;
1468  GetGolombUe(); // first_mb_in_slice
1469  int slice_type = GetGolombUe(); // slice_type, 0 = P, 1 = B, 2 = I, 3 = SP, 4 = SI
1470  independentFrame = (slice_type % 5) == 2;
1471  if (debug) {
1472  static const char SliceTypes[] = "PBIpi";
1473  dbgframes("%c", SliceTypes[slice_type % 5]);
1474  }
1475  if (frame_mbs_only_flag)
1476  return; // don't need the rest - a frame is complete
1477  GetGolombUe(); // pic_parameter_set_id
1479  GetBits(2); // colour_plane_id
1480  GetBits(log2_max_frame_num); // frame_num
1481  if (!frame_mbs_only_flag) {
1482  if (GetBit()) // field_pic_flag
1483  newFrame = !GetBit(); // bottom_field_flag
1484  if (debug)
1485  dbgframes(newFrame ? "t" : "b");
1486  }
1487 }
1488 
1489 // --- cFrameDetector --------------------------------------------------------
1490 
1492 {
1493  parser = NULL;
1494  SetPid(Pid, Type);
1495  synced = false;
1496  newFrame = independentFrame = false;
1497  numPtsValues = 0;
1498  numIFrames = 0;
1499  framesPerSecond = 0;
1501  scanning = false;
1502 }
1503 
1504 static int CmpUint32(const void *p1, const void *p2)
1505 {
1506  if (*(uint32_t *)p1 < *(uint32_t *)p2) return -1;
1507  if (*(uint32_t *)p1 > *(uint32_t *)p2) return 1;
1508  return 0;
1509 }
1510 
1511 void cFrameDetector::SetPid(int Pid, int Type)
1512 {
1513  pid = Pid;
1514  type = Type;
1515  isVideo = type == 0x01 || type == 0x02 || type == 0x1B; // MPEG 1, 2 or H.264
1516  delete parser;
1517  parser = NULL;
1518  if (type == 0x01 || type == 0x02)
1519  parser = new cMpeg2Parser;
1520  else if (type == 0x1B)
1521  parser = new cH264Parser;
1522  else if (type == 0x04 || type == 0x06) // MPEG audio or AC3 audio
1523  parser = new cAudioParser;
1524  else if (type != 0)
1525  esyslog("ERROR: unknown stream type %d (PID %d) in frame detector", type, pid);
1526 }
1527 
1528 int cFrameDetector::Analyze(const uchar *Data, int Length)
1529 {
1530  if (!parser)
1531  return 0;
1532  int Processed = 0;
1533  newFrame = independentFrame = false;
1534  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
1535  // Sync on TS packet borders:
1536  if (Data[0] != TS_SYNC_BYTE) {
1537  int Skipped = 1;
1538  while (Skipped < Length && (Data[Skipped] != TS_SYNC_BYTE || Length - Skipped > TS_SIZE && Data[Skipped + TS_SIZE] != TS_SYNC_BYTE))
1539  Skipped++;
1540  esyslog("ERROR: skipped %d bytes to sync on start of TS packet", Skipped);
1541  return Processed + Skipped;
1542  }
1543  // Handle one TS packet:
1544  int Handled = TS_SIZE;
1545  if (TsHasPayload(Data) && !TsIsScrambled(Data)) {
1546  int Pid = TsPid(Data);
1547  if (Pid == pid) {
1548  if (Processed)
1549  return Processed;
1550  if (TsPayloadStart(Data))
1551  scanning = true;
1552  if (scanning) {
1553  // Detect the beginning of a new frame:
1554  if (TsPayloadStart(Data)) {
1555  if (!framesPerPayloadUnit)
1557  }
1558  int n = parser->Parse(Data, Length, pid);
1559  if (n > 0) {
1560  if (parser->NewFrame()) {
1561  newFrame = true;
1563  if (synced) {
1564  if (framesPerPayloadUnit <= 1)
1565  scanning = false;
1566  }
1567  else {
1569  if (independentFrame)
1570  numIFrames++;
1571  }
1572  }
1573  Handled = n;
1574  }
1575  }
1576  if (TsPayloadStart(Data)) {
1577  // Determine the frame rate from the PTS values in the PES headers:
1578  if (framesPerSecond <= 0.0) {
1579  // frame rate unknown, so collect a sequence of PTS values:
1580  if (numPtsValues < 2 || numPtsValues < MaxPtsValues && numIFrames < 2) { // collect a sequence containing at least two I-frames
1581  if (newFrame) { // only take PTS values at the beginning of a frame (in case if fields!)
1582  const uchar *Pes = Data + TsPayloadOffset(Data);
1583  if (numIFrames && PesHasPts(Pes)) {
1585  // check for rollover:
1586  if (numPtsValues && ptsValues[numPtsValues - 1] > 0xF0000000 && ptsValues[numPtsValues] < 0x10000000) {
1587  dbgframes("#");
1588  numPtsValues = 0;
1589  numIFrames = 0;
1590  }
1591  else
1592  numPtsValues++;
1593  }
1594  }
1595  }
1596  if (numPtsValues >= 2 && numIFrames >= 2) {
1597  // find the smallest PTS delta:
1598  qsort(ptsValues, numPtsValues, sizeof(uint32_t), CmpUint32);
1599  numPtsValues--;
1600  for (int i = 0; i < numPtsValues; i++)
1601  ptsValues[i] = ptsValues[i + 1] - ptsValues[i];
1602  qsort(ptsValues, numPtsValues, sizeof(uint32_t), CmpUint32);
1604  // determine frame info:
1605  if (isVideo) {
1606  if (abs(Delta - 3600) <= 1)
1607  framesPerSecond = 25.0;
1608  else if (Delta % 3003 == 0)
1609  framesPerSecond = 30.0 / 1.001;
1610  else if (abs(Delta - 1800) <= 1)
1611  framesPerSecond = 50.0;
1612  else if (Delta == 1501)
1613  framesPerSecond = 60.0 / 1.001;
1614  else {
1616  dsyslog("unknown frame delta (%d), assuming %5.2f fps", Delta, DEFAULTFRAMESPERSECOND);
1617  }
1618  }
1619  else // audio
1620  framesPerSecond = double(PTSTICKS) / Delta; // PTS of audio frames is always increasing
1621  dbgframes("\nDelta = %d FPS = %5.2f FPPU = %d NF = %d TRO = %d\n", Delta, framesPerSecond, framesPerPayloadUnit, numPtsValues + 1, parser->IFrameTemporalReferenceOffset());
1622  synced = true;
1623  parser->SetDebug(false);
1624  }
1625  }
1626  }
1627  }
1628  else if (Pid == PATPID && synced && Processed)
1629  return Processed; // allow the caller to see any PAT packets
1630  }
1631  Data += Handled;
1632  Length -= Handled;
1633  Processed += Handled;
1634  if (newFrame)
1635  break;
1636  }
1637  return Processed;
1638 }
1639 
1640 // --- cNaluDumper ---------------------------------------------------------
1641 
1643 {
1644  LastContinuityOutput = -1;
1645  reset();
1646 }
1647 
1649 {
1650  LastContinuityInput = -1;
1651  ContinuityOffset = 0;
1652  PesId = -1;
1653  PesOffset = 0;
1655  NaluOffset = 0;
1656  History = 0xffffffff;
1657  DropAllPayload = false;
1658 }
1659 
1660 void cNaluDumper::ProcessPayload(unsigned char *Payload, int size, bool PayloadStart, sPayloadInfo &Info)
1661 {
1662  Info.DropPayloadStartBytes = 0;
1663  Info.DropPayloadEndBytes = 0;
1664  int LastKeepByte = -1;
1665 
1666  if (PayloadStart)
1667  {
1668  History = 0xffffffff;
1669  PesId = -1;
1671  }
1672 
1673  for (int i=0; i<size; i++) {
1674  History = (History << 8) | Payload[i];
1675 
1676  PesOffset++;
1677  NaluOffset++;
1678 
1679  bool DropByte = false;
1680 
1681  if (History >= 0x00000180 && History <= 0x000001FF)
1682  {
1683  // Start of PES packet
1684  PesId = History & 0xff;
1685  PesOffset = 0;
1687  }
1688  else if (PesId >= 0xe0 && PesId <= 0xef // video stream
1689  && History >= 0x00000100 && History <= 0x0000017F) // NALU start code
1690  {
1691  int NaluId = History & 0xff;
1692  NaluOffset = 0;
1693  NaluFillState = ((NaluId & 0x1f) == 0x0c) ? NALU_FILL : NALU_NONE;
1694  }
1695 
1696  if (PesId >= 0xe0 && PesId <= 0xef // video stream
1697  && PesOffset >= 1 && PesOffset <= 2)
1698  {
1699  Payload[i] = 0; // Zero out PES length field
1700  }
1701 
1702  if (NaluFillState == NALU_FILL && NaluOffset > 0) // Within NALU fill data
1703  {
1704  // We expect a series of 0xff bytes terminated by a single 0x80 byte.
1705 
1706  if (Payload[i] == 0xFF)
1707  {
1708  DropByte = true;
1709  }
1710  else if (Payload[i] == 0x80)
1711  {
1712  NaluFillState = NALU_TERM; // Last byte of NALU fill, next byte sets NaluFillEnd=true
1713  DropByte = true;
1714  }
1715  else // Invalid NALU fill
1716  {
1717  dsyslog("cNaluDumper: Unexpected NALU fill data: %02x", Payload[i]);
1719  if (LastKeepByte == -1)
1720  {
1721  // Nalu fill from beginning of packet until last byte
1722  // packet start needs to be dropped
1723  Info.DropPayloadStartBytes = i;
1724  }
1725  }
1726  }
1727  else if (NaluFillState == NALU_TERM) // Within NALU fill data
1728  {
1729  // We are after the terminating 0x80 byte
1731  if (LastKeepByte == -1)
1732  {
1733  // Nalu fill from beginning of packet until last byte
1734  // packet start needs to be dropped
1735  Info.DropPayloadStartBytes = i;
1736  }
1737  }
1738 
1739  if (!DropByte)
1740  LastKeepByte = i; // Last useful byte
1741  }
1742 
1743  Info.DropAllPayloadBytes = (LastKeepByte == -1);
1744  Info.DropPayloadEndBytes = size-1-LastKeepByte;
1745 }
1746 
1747 bool cNaluDumper::ProcessTSPacket(unsigned char *Packet)
1748 {
1749  bool HasAdaption = TsHasAdaptationField(Packet);
1750  bool HasPayload = TsHasPayload(Packet);
1751 
1752  // Check continuity:
1753  int ContinuityInput = TsContinuityCounter(Packet);
1754  if (LastContinuityInput >= 0)
1755  {
1756  int NewContinuityInput = HasPayload ? (LastContinuityInput + 1) & TS_CONT_CNT_MASK : LastContinuityInput;
1757  int Offset = (NewContinuityInput - ContinuityInput) & TS_CONT_CNT_MASK;
1758  if (Offset > 0)
1759  dsyslog("cNaluDumper: TS continuity offset %i", Offset);
1760  if (Offset > ContinuityOffset)
1761  ContinuityOffset = Offset; // max if packets get dropped, otherwise always the current one.
1762  }
1763  LastContinuityInput = ContinuityInput;
1764 
1765  if (HasPayload) {
1766  sPayloadInfo Info;
1767  int Offset = TsPayloadOffset(Packet);
1768  ProcessPayload(Packet + Offset, TS_SIZE - Offset, TsPayloadStart(Packet), Info);
1769 
1770  if (DropAllPayload && !Info.DropAllPayloadBytes)
1771  {
1772  // Return from drop packet mode to normal mode
1773  DropAllPayload = false;
1774 
1775  // Does the packet start with some remaining NALU fill data?
1776  if (Info.DropPayloadStartBytes > 0)
1777  {
1778  // Add these bytes as stuffing to the adaption field.
1779 
1780  // Sample payload layout:
1781  // FF FF FF FF FF 80 00 00 01 xx xx xx xx
1782  // ^DropPayloadStartBytes
1783 
1784  TsExtendAdaptionField(Packet, Offset - 4 + Info.DropPayloadStartBytes);
1785  }
1786  }
1787 
1788  bool DropThisPayload = DropAllPayload;
1789 
1790  if (!DropAllPayload && Info.DropPayloadEndBytes > 0) // Payload ends with 0xff NALU Fill
1791  {
1792  // Last packet of useful data
1793  // Do early termination of NALU fill data
1794  Packet[TS_SIZE-1] = 0x80;
1795  DropAllPayload = true;
1796  // Drop all packets AFTER this one
1797 
1798  // Since we already wrote the 0x80, we have to make sure that
1799  // as soon as we stop dropping packets, any beginning NALU fill of next
1800  // packet gets dumped. (see DropPayloadStartBytes above)
1801  }
1802 
1803  if (DropThisPayload && HasAdaption)
1804  {
1805  // Drop payload data, but keep adaption field data
1806  TsExtendAdaptionField(Packet, TS_SIZE-4);
1807  DropThisPayload = false;
1808  }
1809 
1810  if (DropThisPayload)
1811  {
1812  return true; // Drop packet
1813  }
1814  }
1815 
1816  // Fix Continuity Counter and reproduce incoming offsets:
1817  int NewContinuityOutput = TsHasPayload(Packet) ? (LastContinuityOutput + 1) & TS_CONT_CNT_MASK : LastContinuityOutput;
1818  NewContinuityOutput = (NewContinuityOutput + ContinuityOffset) & TS_CONT_CNT_MASK;
1819  TsSetContinuityCounter(Packet, NewContinuityOutput);
1820  LastContinuityOutput = NewContinuityOutput;
1821  ContinuityOffset = 0;
1822 
1823  return false; // Keep packet
1824 }
1825 
1826 // --- cNaluStreamProcessor ---------------------------------------------------------
1827 
1829 {
1830  pPatPmtParser = NULL;
1831  vpid = -1;
1832  data = NULL;
1833  length = 0;
1834  tempLength = 0;
1835  tempLengthAtEnd = false;
1836  TotalPackets = 0;
1837  DroppedPackets = 0;
1838 }
1839 
1841 {
1842  if (length > 0)
1843  esyslog("cNaluStreamProcessor::PutBuffer: New data before old data was processed!");
1844 
1845  data = Data;
1846  length = Length;
1847 }
1848 
1850 {
1851  if (length <= 0)
1852  {
1853  // Need more data - quick exit
1854  OutLength = 0;
1855  return NULL;
1856  }
1857  if (tempLength > 0) // Data in temp buffer?
1858  {
1859  if (tempLengthAtEnd) // Data is at end, copy to beginning
1860  {
1861  // Overlapping src and dst!
1862  for (int i=0; i<tempLength; i++)
1863  tempBuffer[i] = tempBuffer[TS_SIZE-tempLength+i];
1864  }
1865  // Normalize TempBuffer fill
1866  if (tempLength < TS_SIZE && length > 0)
1867  {
1868  int Size = min(TS_SIZE-tempLength, length);
1869  memcpy(tempBuffer+tempLength, data, Size);
1870  data += Size;
1871  length -= Size;
1872  tempLength += Size;
1873  }
1874  if (tempLength < TS_SIZE)
1875  {
1876  // All incoming data buffered, but need more data
1877  tempLengthAtEnd = false;
1878  OutLength = 0;
1879  return NULL;
1880  }
1881  // Now: TempLength==TS_SIZE
1882  if (tempBuffer[0] != TS_SYNC_BYTE)
1883  {
1884  // Need to sync on TS within temp buffer
1885  int Skipped = 1;
1886  while (Skipped < TS_SIZE && (tempBuffer[Skipped] != TS_SYNC_BYTE || (Skipped < length && data[Skipped] != TS_SYNC_BYTE)))
1887  Skipped++;
1888  esyslog("ERROR: skipped %d bytes to sync on start of TS packet", Skipped);
1889  // Pass through skipped bytes
1890  tempLengthAtEnd = true;
1891  tempLength = TS_SIZE - Skipped; // may be 0, thats ok
1892  OutLength = Skipped;
1893  return tempBuffer;
1894  }
1895  // Now: TempBuffer is a TS packet
1896  int Pid = TsPid(tempBuffer);
1897  if (pPatPmtParser)
1898  {
1899  if (Pid == 0)
1901  else if (pPatPmtParser->IsPmtPid(Pid))
1903  }
1904 
1905  TotalPackets++;
1906  bool Drop = false;
1907  if (Pid == vpid || (pPatPmtParser && Pid == pPatPmtParser->Vpid() && pPatPmtParser->Vtype() == 0x1B))
1909  if (!Drop)
1910  {
1911  // Keep this packet, then continue with new data
1912  tempLength = 0;
1913  OutLength = TS_SIZE;
1914  return tempBuffer;
1915  }
1916  // Drop TempBuffer
1917  DroppedPackets++;
1918  tempLength = 0;
1919  }
1920  // Now: TempLength==0, just process data/length
1921 
1922  // Pointer to processed data / length:
1923  uchar *Out = data;
1924  uchar *OutEnd = Out;
1925 
1926  while (length >= TS_SIZE)
1927  {
1928  if (data[0] != TS_SYNC_BYTE) {
1929  int Skipped = 1;
1930  while (Skipped < length && (data[Skipped] != TS_SYNC_BYTE || (length - Skipped > TS_SIZE && data[Skipped + TS_SIZE] != TS_SYNC_BYTE)))
1931  Skipped++;
1932  esyslog("ERROR: skipped %d bytes to sync on start of TS packet", Skipped);
1933 
1934  // Pass through skipped bytes
1935  if (OutEnd != data)
1936  memcpy(OutEnd, data, Skipped);
1937  OutEnd += Skipped;
1938  continue;
1939  }
1940  // Now: Data starts with complete TS packet
1941 
1942  int Pid = TsPid(data);
1943  if (pPatPmtParser)
1944  {
1945  if (Pid == 0)
1947  else if (pPatPmtParser->IsPmtPid(Pid))
1949  }
1950 
1951  TotalPackets++;
1952  bool Drop = false;
1953  if (Pid == vpid || (pPatPmtParser && Pid == pPatPmtParser->Vpid() && pPatPmtParser->Vtype() == 0x1B))
1955  if (!Drop)
1956  {
1957  if (OutEnd != data)
1958  memcpy(OutEnd, data, TS_SIZE);
1959  OutEnd += TS_SIZE;
1960  }
1961  else
1962  {
1963  DroppedPackets++;
1964  }
1965  data += TS_SIZE;
1966  length -= TS_SIZE;
1967  }
1968  // Now: Less than a packet remains.
1969  if (length > 0)
1970  {
1971  // copy remains into temp buffer
1972  memcpy(tempBuffer, data, length);
1973  tempLength = length;
1974  tempLengthAtEnd = false;
1975  length = 0;
1976  }
1977  OutLength = (OutEnd - Out);
1978  return OutLength > 0 ? Out : NULL;
1979 }
int framesInPayloadUnit
Definition: remux.h:505
#define VIDEO_STREAM_S
Definition: remux.c:98
uint16_t AncillaryPageId(int i) const
Definition: channels.h:181
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:957
unsigned char uchar
Definition: tools.h:30
void ParsePat(const uchar *Data, int Length)
Parses the PAT data from the single TS packet in Data.
Definition: remux.c:678
uchar * data
Definition: remux.h:222
int Used(void)
Returns the number of raw bytes that have already been used (e.g.
Definition: remux.h:252
uchar GetBit(void)
Definition: remux.c:1326
int Vpid(void) const
Definition: channels.h:165
bool separate_colour_plane_flag
Definition: remux.c:1269
uchar GetByte(void)
Gets the next byte of the TS payload, skipping any intermediate TS header data.
Definition: remux.c:267
const int * Dpids(void) const
Definition: channels.h:169
bool repeatLast
Definition: remux.h:442
int vpid
Definition: remux.h:355
int index
Definition: remux.h:225
int pid
Definition: remux.h:224
uchar subtitlingTypes[MAXSPIDS]
Definition: remux.h:367
Definition: device.h:66
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:630
#define dsyslog(a...)
Definition: tools.h:36
bool TsError(const uchar *p)
Definition: remux.h:80
void SetPid(int Pid, int Type)
Sets the Pid and stream Type to detect frames for.
Definition: remux.c:1511
#define MAX_TS_PACKETS_FOR_VIDEO_FRAME_DETECTION
Definition: remux.c:26
#define DEFAULTFRAMESPERSECOND
Definition: recording.h:210
bool newFrame
Definition: remux.c:1125
int Dtype(int i) const
Definition: channels.h:178
int PesPayloadOffset(const uchar *p)
Definition: remux.h:172
void IncCounter(int &Counter, uchar *TsPacket)
Definition: remux.c:394
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:298
bool TsHasAdaptationField(const uchar *p)
Definition: remux.h:70
bool getCurrentNextIndicator() const
Definition: si.c:80
void ParsePmt(const uchar *Data, int Length)
Parses the PMT data from the single TS packet in Data.
Definition: remux.c:710
uint16_t ancillaryPageIds[MAXSPIDS]
Definition: remux.h:369
bool IsPmtPid(int Pid) const
Returns true if Pid the one of the PMT pids as defined by the current PAT.
Definition: remux.h:397
int framesPerPayloadUnit
Definition: remux.h:506
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:1195
int pmtSize
Definition: remux.h:351
uchar SubtitlingType(int i) const
Definition: channels.h:179
char alangs[MAXAPIDS][MAXLANGCODE2]
Definition: remux.h:361
bool IndependentFrame(void)
Definition: remux.c:1140
int Spid(int i) const
Definition: channels.h:173
cNaluDumper NaluDumper
Definition: remux.h:590
#define SETPID(p)
#define MAX33BIT
Definition: remux.h:57
int TotalTeletextSubtitlePages() const
Definition: channels.h:184
int LastContinuityInput
Definition: remux.h:543
bool TsPayloadStart(const uchar *p)
Definition: remux.h:75
int Dpid(int i) const
Definition: channels.h:172
uint32_t scanner
Definition: remux.c:1267
bool gotAccessUnitDelimiter
Definition: remux.c:1273
int MakeLanguageDescriptor(uchar *Target, const char *Language)
Definition: remux.c:478
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:512
int64_t PesGetPts(const uchar *p)
Definition: remux.h:187
int NaluOffset
Definition: remux.h:552
int Analyze(const uchar *Data, int Length)
Analyzes the TS packets pointed to by Data.
Definition: remux.c:1528
uchar pat[TS_SIZE]
Definition: remux.h:294
int numPacketsPid
Definition: remux.h:226
bool debug
Definition: remux.c:1124
bool TsHasPayload(const uchar *p)
Definition: remux.h:60
bool DropAllPayload
Definition: remux.h:547
StructureLoop< Association > associationLoop
Definition: section.h:39
uint32_t ptsValues[MaxPtsValues]
Definition: remux.h:499
#define esyslog(a...)
Definition: tools.h:34
StructureLoop< Stream > streamLoop
Definition: section.h:71
char slangs[MAXSPIDS][MAXLANGCODE2]
Definition: remux.h:366
#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:407
int MakeCRC(uchar *Target, const uchar *Data, int Length)
Definition: remux.c:497
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:951
int Vpid(void) const
Returns the video pid as defined by the current PMT, or 0 if no video pid has been detected...
Definition: remux.h:400
T max(T a, T b)
Definition: tools.h:55
int MakeTeletextDescriptor(uchar *Target, const tTeletextSubtitlePage *pages, int pageCount)
Definition: remux.c:455
#define WRN_TS_PACKETS_FOR_FRAME_DETECTOR
Definition: remux.c:28
#define MAXTXTPAGES
Definition: channels.h:38
void SetChannel(const cChannel *Channel)
Sets the Channel for which the PAT/PMT shall be generated.
Definition: remux.c:636
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:246
bool PesHasPts(const uchar *p)
Definition: remux.h:177
#define PTSTICKS
Definition: remux.h:55
cPatPmtGenerator(const cChannel *Channel=NULL)
Definition: remux.c:384
uchar SetEof(void)
Definition: remux.c:246
int MakeSubtitlingDescriptor(uchar *Target, const char *Language, uchar SubtitlingType, uint16_t CompositionPageId, uint16_t AncillaryPageId)
Definition: remux.c:438
DescriptorTag getDescriptorTag() const
Definition: si.c:100
int length
Definition: remux.h:438
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:259
int PesOffset
Definition: remux.h:550
int getServiceId() const
Definition: section.c:57
StructureLoop< Teletext > teletextLoop
Definition: descriptor.h:138
const char * Dlang(int i) const
Definition: channels.h:175
StructureLoop< Subtitling > subtitlingLoop
Definition: descriptor.h:331
bool isVideo
Definition: remux.h:503
void ParseSequenceParameterSet(void)
Definition: remux.c:1413
int pmtVersion
Definition: remux.h:353
int64_t TsGetDts(const uchar *p, int l)
Definition: remux.c:160
int numPtsValues
Definition: remux.h:500
void TsExtendAdaptionField(unsigned char *Packet, int ToLength)
Definition: remux.c:346
bool independentFrame
Definition: remux.c:1126
cPatPmtParser * pPatPmtParser
Definition: remux.h:589
int Ppid(void) const
Definition: channels.h:166
T min(T a, T b)
Definition: tools.h:54
bool independentFrame
Definition: remux.h:498
#define TS_SYNC_BYTE
Definition: remux.h:33
int lastLength
Definition: remux.h:441
int MakeAC3Descriptor(uchar *Target, uchar Type)
Definition: remux.c:428
tTeletextSubtitlePage teletextSubtitlePages[MAXTXTPAGES]
Definition: remux.h:372
static bool DebugPatPmt
Definition: remux.c:20
void GeneratePat(void)
Generates a PAT section for later use with GetPat().
Definition: remux.c:527
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:321
#define dbgpatpmt(a...)
Definition: remux.c:23
cFrameParser(void)
Definition: remux.c:1144
int SectionLength(const uchar *Data, int Length)
Definition: remux.h:374
int MakeStream(uchar *Target, uchar Type, int Pid)
Definition: remux.c:416
int getPid() const
Definition: section.c:65
uchar GetByte(bool Raw=false)
Gets the next data byte.
Definition: remux.c:1307
int iFrameTemporalReferenceOffset
Definition: remux.c:1127
int patCounter
Definition: remux.h:297
bool Eof(void) const
Returns true if all available bytes of the TS payload have been processed.
Definition: remux.h:256
uchar pmt[MAX_PMT_TS][TS_SIZE]
Definition: remux.h:295
uchar * lastData
Definition: remux.h:440
const char * Alang(int i) const
Definition: channels.h:174
bool PesLongEnough(int Length)
Definition: remux.h:157
void TsSetPcr(uchar *p, int64_t Pcr)
Definition: remux.c:131
#define MAX_SECTION_SIZE
Definition: remux.h:289
#define EMPTY_SCANNER
Definition: remux.c:30
int TsPid(const uchar *p)
Definition: remux.h:85
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:1363
int getPid() const
Definition: section.c:34
long long int DroppedPackets
Definition: remux.h:593
cFrameDetector(int Pid=0, int Type=0)
Sets up a frame detector for the given Pid and stream Type.
Definition: remux.c:1491
#define SETPIDS(l)
void ParseSliceHeader(void)
Definition: remux.c:1465
double framesPerSecond
Definition: remux.h:504
void EnsureSubtitleTrack(void)
Makes sure one of the preferred language subtitle tracks is selected.
Definition: device.c:1084
#define TS_PAYLOAD_EXISTS
Definition: remux.h:41
int getSectionNumber() const
Definition: si.c:88
int PesLength(const uchar *p)
Definition: remux.h:167
void PesSetPts(uchar *p, int64_t Pts)
Definition: remux.c:203
void ParseAccessUnitDelimiter(void)
Definition: remux.c:1406
Definition: remux.h:20
int lastIFrameTemporalReference
Definition: remux.c:1182
int zeroBytes
Definition: remux.c:1266
int Vtype(void) const
Returns the video stream type as defined by the current PMT, or 0 if no video stream type has been de...
Definition: remux.h:406
int ppid
Definition: remux.h:356
int TsContinuityCounter(const uchar *p)
Definition: remux.h:121
cH264Parser(void)
Sets up a new H.264 parser.
Definition: remux.c:1294
char dlangs[MAXDPIDS][MAXLANGCODE2]
Definition: remux.h:364
void Reset(void)
Resets the converter.
Definition: remux.c:1079
int ContinuityOffset
Definition: remux.h:545
#define MAXPID
Definition: remux.c:510
bool synced
Definition: remux.h:496
bool PesHasDts(const uchar *p)
Definition: remux.h:182
void PesSetDts(uchar *p, int64_t Dts)
Definition: remux.c:212
void BlockDump(const char *Name, const u_char *Data, int Length)
Definition: remux.c:1089
void TsSetDts(uchar *p, int l, int64_t Dts)
Definition: remux.c:187
const tTeletextSubtitlePage * TeletextSubtitlePages() const
Definition: channels.h:183
cPatPmtParser(bool UpdatePrimaryDevice=false)
Definition: remux.c:662
int Tpid(void) const
Definition: channels.h:182
int GetLastIndex(void)
Returns the index into the TS data of the payload byte that has most recently been read...
Definition: remux.c:310
int PesId
Definition: remux.h:549
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:233
int dtypes[MAXDPIDS+1]
Definition: remux.h:363
int dpids[MAXDPIDS+1]
Definition: remux.h:362
void TsDump(const char *Name, const u_char *Data, int Length)
Definition: remux.c:1100
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:1164
int64_t PtsDiff(int64_t Pts1, int64_t Pts2)
Returns the difference between two PTS values.
Definition: remux.c:221
void PutTs(const uchar *Data, int Length)
Puts the payload data of the single TS packet at Data into the converter.
Definition: remux.c:997
void ClrAvailableTracks(bool DescriptionsOnly=false, bool IdsOnly=false)
Clears the list of currently available tracks.
Definition: device.c:928
ePesHeader AnalyzePesHeader(const uchar *Data, int Count, int &PesPayloadOffset, bool *ContinuationHeader)
Definition: remux.c:32
int IFrameTemporalReferenceOffset(void)
Definition: remux.c:1141
int atypes[MAXAPIDS+1]
Definition: remux.h:360
unsigned int History
Definition: remux.h:541
uchar byte
Definition: remux.c:1264
uchar * GetPmt(int &Index)
Returns a pointer to the Index'th TS packet of the PMT section.
Definition: remux.c:651
int Atype(int i) const
Definition: channels.h:177
void TsSetContinuityCounter(uchar *p, uchar Counter)
Definition: remux.h:100
int numPmtPackets
Definition: remux.h:296
cSetup Setup
Definition: config.c:373
void reset()
Definition: remux.c:1648
void ProcessPayload(unsigned char *Payload, int size, bool PayloadStart, sPayloadInfo &Info)
Definition: remux.c:1660
StructureLoop< Language > languageLoop
Definition: descriptor.h:489
#define WRN_TS_PACKETS_FOR_VIDEO_FRAME_DETECTION
Definition: remux.c:27
~cTsToPes()
Definition: remux.c:992
#define MAXLANGCODE1
Definition: channels.h:40
int TsGetPayload(const uchar **p)
Definition: remux.h:111
#define MAXPESLENGTH
Definition: remux.c:1024
int pmtCounter
Definition: remux.h:298
int LastContinuityOutput
Definition: remux.h:544
long long int TotalPackets
Definition: remux.h:592
void GeneratePmt(const cChannel *Channel)
Generates a PMT section for the given Channel, for later use with GetPmt().
Definition: remux.c:556
uchar pmt[MAX_SECTION_SIZE]
Definition: remux.h:350
int32_t GetGolombSe(void)
Definition: remux.c:1351
void TsHidePayload(uchar *p)
Definition: remux.c:121
#define P_TSID
Definition: remux.c:508
int length
Definition: remux.h:223
#define TS_CONT_CNT_MASK
Definition: remux.h:42
uint16_t compositionPageIds[MAXSPIDS]
Definition: remux.h:368
int getStreamType() const
Definition: section.c:69
void PesDump(const char *Name, const u_char *Data, int Length)
Definition: remux.c:1115
int pmtPids[MAX_PMT_PIDS+1]
Definition: remux.h:354
bool CheckCRCAndParse()
Definition: si.c:65
bool isNITPid() const
Definition: section.h:31
uint32_t GetBits(int Bits)
Definition: remux.c:1335
bool frame_mbs_only_flag
Definition: remux.c:1271
static void SetBrokenLink(uchar *Data, int Length)
Definition: remux.c:102
char ttxtLanguage[MAXLANGCODE1]
Definition: channels.h:78
virtual ~cFrameParser()
Definition: remux.c:1130
static bool DebugFrames
Definition: remux.c:21
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:338
Definition: device.h:69
bool seenIndependentFrame
Definition: remux.c:1181
const int * Apids(void) const
Definition: channels.h:168
int getServiceId() const
Definition: section.c:30
int patVersion
Definition: remux.h:299
int UseDolbyDigital
Definition: config.h:310
cFrameParser * parser
Definition: remux.h:509
bool ProcessTSPacket(unsigned char *Packet)
Definition: remux.c:1747
int numPacketsOther
Definition: remux.h:227
#define MAXDPIDS
Definition: channels.h:35
int spids[MAXSPIDS+1]
Definition: remux.h:365
#define MIN_TS_PACKETS_FOR_FRAME_DETECTOR
Definition: remux.h:487
int size
Definition: remux.h:437
#define PCRFACTOR
Definition: remux.h:56
void EnsureAudioTrack(bool Force=false)
Makes sure an audio track is selected that is actually available.
Definition: device.c:1051
#define PATPID
Definition: remux.h:52
#define MAX_PMT_PIDS
Definition: remux.h:346
static cDevice * PrimaryDevice(void)
Returns the primary device.
Definition: device.h:132
int getVersionNumber() const
Definition: si.c:84
bool PesHasLength(const uchar *p)
Definition: remux.h:162
#define P_PMT_PID
Definition: remux.c:509
int64_t TsGetPts(const uchar *p, int l)
Definition: remux.c:147
#define KILOBYTE(n)
Definition: tools.h:43
uint16_t CompositionPageId(int i) const
Definition: channels.h:180
int Apid(int i) const
Definition: channels.h:171
unsigned char u_char
Definition: headers.h:24
int getLastSectionNumber() const
Definition: si.c:92
int getPCRPid() const
Definition: section.c:61
int totalTtxtSubtitlePages
Definition: remux.h:371
bool TsIsScrambled(const uchar *p)
Definition: remux.h:90
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:976
int64_t PesGetDts(const uchar *p)
Definition: remux.h:196
cTsPayload tsPayload
Definition: remux.c:1263
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:315
int tpid
Definition: remux.h:358
cNaluDumper()
Definition: remux.c:1642
int getTransportStreamId() const
Definition: section.c:26
uchar * esInfoLength
Definition: remux.h:302
#define TS_PAYLOAD_START
Definition: remux.h:36
bool updatePrimaryDevice
Definition: remux.h:370
DescriptorLoop streamDescriptors
Definition: section.h:63
void Reset(void)
Definition: remux.c:252
#define MAXSPIDS
Definition: channels.h:36
eNaluFillState NaluFillState
Definition: remux.h:561
bool newFrame
Definition: remux.h:497
bool gotSequenceParameterSet
Definition: remux.c:1274
const char * Slang(int i) const
Definition: channels.h:176
#define TS_SIZE
Definition: remux.h:34
cMpeg2Parser(void)
Definition: remux.c:1188
Definition: remux.h:19
void IncVersion(int &Version)
Definition: remux.c:401
const int * Spids(void) const
Definition: channels.h:170
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:1026
uint32_t GetGolombUe(void)
Definition: remux.c:1343
int bit
Definition: remux.c:1265
int log2_max_frame_num
Definition: remux.c:1270
void SetDebug(bool Debug)
Definition: remux.c:1138
int TsPayloadOffset(const uchar *p)
Definition: remux.h:105
bool scanning
Definition: remux.h:508
int offset
Definition: remux.h:439
#define TS_ADAPT_PCR
Definition: remux.h:46
int numIFrames
Definition: remux.h:502
int getTeletextMagazineNumber() const
Definition: descriptor.c:338
bool NewFrame(void)
Definition: remux.c:1139
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:1074
bool AtTsStart(void)
Returns true if this payload handler is currently pointing to first byte of a TS packet.
Definition: remux.h:243
void TsSetPts(uchar *p, int l, int64_t Pts)
Definition: remux.c:173
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:1504
void PutBuffer(uchar *Data, int Length)
Definition: remux.c:1840
void Reset(void)
Resets the parser.
Definition: remux.c:668
int Vtype(void) const
Definition: channels.h:167
Descriptor * getNext(Iterator &it)
Definition: si.c:112
uchar * data
Definition: remux.h:436
uchar * GetPat(void)
Returns a pointer to the PAT section, which consists of exactly one TS packet.
Definition: remux.c:645
uchar * GetBuffer(int &OutLength)
Definition: remux.c:1849
int patVersion
Definition: remux.h:352
int vtype
Definition: remux.h:357
#define dbgframes(a...)
Definition: remux.c:24
int pmtVersion
Definition: remux.h:300
bool SkipPesHeader(void)
Skips all bytes belonging to the PES header of the payload.
Definition: remux.c:305
uint32_t scanner
Definition: remux.c:1180
cTsToPes(void)
Definition: remux.c:985
int apids[MAXAPIDS+1]
Definition: remux.h:359
#define MAXAPIDS
Definition: channels.h:34
uchar tempBuffer[TS_SIZE]
Definition: remux.h:586
cAudioParser(void)
Definition: remux.c:1160
bool tempLengthAtEnd
Definition: remux.h:588