/
mpegstreamdata.cpp
1960 lines (1602 loc) · 53.7 KB
/
mpegstreamdata.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: c++ -*-
// Copyright (c) 2003-2004, Daniel Thor Kristjansson
#include <algorithm> // for find & max
// POSIX headers
#include <sys/time.h> // for gettimeofday
// Qt headers
#include <QString>
// MythTV headers
#include "mpegstreamdata.h"
#include "mpegtables.h"
#include "mpegtables.h"
#include "atscstreamdata.h"
#include "atsctables.h"
//#define DEBUG_MPEG_RADIO // uncomment to strip video streams from TS stream
#define LOC QString("MPEGStream[%1](0x%2): ").arg(m_cardId).arg((intptr_t)this, QT_POINTER_SIZE, 16, QChar('0'))
/** \class MPEGStreamData
* \brief Encapsulates data about MPEG stream and emits events for each table.
*/
/** \fn MPEGStreamData::MPEGStreamData(int, bool)
* \brief Initializes MPEGStreamData.
*
* This adds the PID of the PAT table to "m_pidsListening"
*
* \param desiredProgram If you want rewritten PAT and PMTs, for
* a desired program set this to a value > -1
* \param cardnum The card number that this stream is on.
* Currently only used for differentiating streams
* in log messages.
* \param cacheTables If true PAT and PMT tables will be cached
*/
MPEGStreamData::MPEGStreamData(int desiredProgram, int cardnum,
bool cacheTables)
: m_cardId(cardnum),
m_cacheTables(cacheTables),
// Single program stuff
m_desiredProgram(desiredProgram)
{
MPEGStreamData::AddListeningPID(PID::MPEG_PAT_PID);
MPEGStreamData::AddListeningPID(PID::MPEG_CAT_PID);
}
MPEGStreamData::~MPEGStreamData()
{
MPEGStreamData::Reset(-1);
SetPATSingleProgram(nullptr);
SetPMTSingleProgram(nullptr);
// Delete any cached tables that haven't been returned
for (auto it = m_cachedSlatedForDeletion.cbegin();
it != m_cachedSlatedForDeletion.cend(); ++it)
delete it.key();
QMutexLocker locker(&m_listenerLock);
m_mpegListeners.clear();
m_mpegSpListeners.clear();
}
void MPEGStreamData::SetDesiredProgram(int p)
{
bool reset = true;
uint pid = 0;
const ProgramAssociationTable* pat = nullptr;
pat_vec_t pats = GetCachedPATs();
LOG(VB_RECORD, LOG_INFO, LOC + QString("SetDesiredProgram(%2)").arg(p));
for (uint i = (p) ? 0 : pats.size(); i < pats.size() && !pid; i++)
{
pat = pats[i];
pid = pats[i]->FindPID(p);
}
if (pid)
{
reset = false;
m_desiredProgram = p;
ProcessPAT(pat);
pmt_vec_t pmts = GetCachedPMTs();
for (auto & pmt : pmts)
{
if (pmt->ProgramNumber() == (uint)p)
ProcessPMT(pmt);
}
ReturnCachedPMTTables(pmts);
}
ReturnCachedPATTables(pats);
if (reset)
Reset(p);
}
void MPEGStreamData::SetRecordingType(const QString &recording_type)
{
m_recordingType = recording_type;
uint neededAudio = (m_recordingType == "audio") ? 1 : 0;
SetVideoStreamsRequired(0);
SetAudioStreamsRequired(neededAudio);
}
void MPEGStreamData::SetEITHelper(EITHelper *eit_helper)
{
QMutexLocker locker(&m_listenerLock);
m_eitHelper = eit_helper;
}
void MPEGStreamData::SetEITRate(float rate)
{
QMutexLocker locker(&m_listenerLock);
m_eitRate = rate;
}
void MPEGStreamData::Reset(int desiredProgram)
{
m_desiredProgram = desiredProgram;
m_recordingType = "all";
m_stripPmtDescriptors = false;
m_normalizeStreamType = true;
m_invalidPatSeen = false;
SetPATSingleProgram(nullptr);
SetPMTSingleProgram(nullptr);
pid_psip_map_t old = m_partialPsipPacketCache;
for (auto it = old.begin(); it != old.end(); ++it)
DeletePartialPSIP(it.key());
m_partialPsipPacketCache.clear();
m_pidsListening.clear();
m_pidsNotListening.clear();
m_pidsWriting.clear();
m_pidsAudio.clear();
m_pidsConditionalAccess.clear();
m_pidVideoSingleProgram = m_pidPmtSingleProgram = 0xffffffff;
m_patStatus.clear();
m_pmtStatus.clear();
{
QMutexLocker locker(&m_cacheLock);
for (const auto & cached : qAsConst(m_cachedPats))
DeleteCachedTable(cached);
m_cachedPats.clear();
for (const auto & cached : qAsConst(m_cachedPmts))
DeleteCachedTable(cached);
m_cachedPmts.clear();
for (const auto & cached : qAsConst(m_cachedCats))
DeleteCachedTable(cached);
m_cachedCats.clear();
}
ResetDecryptionMonitoringState();
AddListeningPID(PID::MPEG_PAT_PID);
AddListeningPID(PID::MPEG_CAT_PID);
}
void MPEGStreamData::DeletePartialPSIP(uint pid)
{
pid_psip_map_t::iterator it = m_partialPsipPacketCache.find(pid);
if (it != m_partialPsipPacketCache.end())
{
PSIPTable *pkt = *it;
m_partialPsipPacketCache.erase(it);
delete pkt;
}
}
/**
* \brief PSIP packet assembler.
*
* This is not a general purpose TS->PSIP packet converter,
* it is only designed to work with MPEG tables which comply
* with certain restrictions that simplify the conversion.
*
* DVB TSPackets may contain multiple segments of the PSI
* stream. (see ISO 13818-1 section 2.4.3.3, particularly
* the definition of payload_unit_start_indicator, which
* indicates there is at least one segment start, but not
* limited to only one segment start.)
*
* PSI stuffing bytes are 0xFF and will complete the
* remaining portion of the TSPacket. (Section 2.4.4)
*
* \note This method makes the assumption that AddTSPacket
* correctly handles duplicate packets.
*
* \param tspacket Pointer to the TS packet data.
* \param moreTablePackets returns true if we need more packets
*/
PSIPTable* MPEGStreamData::AssemblePSIP(const TSPacket* tspacket,
bool &moreTablePackets)
{
bool broken = true;
moreTablePackets = true;
PSIPTable* partial = GetPartialPSIP(tspacket->PID());
// Second and subsequent transport stream packets of PSIP packet
if (partial && partial->AddTSPacket(tspacket, m_cardId, broken) && !broken)
{
// check if it's safe to read pespacket's Length()
if ((partial->PSIOffset() + 1 + 3) > partial->TSSizeInBuffer())
{
LOG(VB_RECORD, LOG_ERR, LOC +
QString("Discarding broken PSIP packet. Packet's length at "
"position %1 isn't in the buffer of %2 bytes.")
.arg(partial->PSIOffset() + 1 + 3)
.arg(partial->TSSizeInBuffer()));
DeletePartialPSIP(tspacket->PID());
return nullptr;
}
// Discard broken packets
bool buggy = m_haveCrcBug &&
((TableID::PMT == partial->StreamID()) ||
(TableID::PAT == partial->StreamID()));
if (!buggy && !partial->IsGood())
{
LOG(VB_RECORD, LOG_ERR, LOC + QString("Discarding broken PSIP packet on PID 0x%1")
.arg(tspacket->PID(),2,16,QChar('0')));
DeletePartialPSIP(tspacket->PID());
return nullptr;
}
auto* psip = new PSIPTable(*partial);
// Advance to the next packet
// pesdata starts only at PSIOffset()+1
uint packetStart = partial->PSIOffset() + 1 + psip->SectionLength();
if (packetStart < partial->TSSizeInBuffer())
{
if (partial->pesdata()[psip->SectionLength()] != 0xff)
{
#if 0 /* This doesn't work, you can't start PSIP packet like this
because the PayloadStart() flag won't be set in this TSPacket
-- dtk May 4th, 2007
*/
// If the next section starts in the new tspacket
// create a new partial packet to prevent overflow
if ((partial->TSSizeInBuffer() > TSPacket::kSize) &&
(packetStart >
partial->TSSizeInBuffer() - TSPacket::kPayloadSize))
{
// Saving will handle deleting the old one
SavePartialPSIP(tspacket->PID(),
new PSIPTable(*tspacket));
}
else
#endif
{
partial->SetPSIOffset(partial->PSIOffset() +
psip->SectionLength());
}
return psip;
}
}
// discard incomplete packets
if (packetStart > partial->TSSizeInBuffer())
{
LOG(VB_RECORD, LOG_ERR, LOC +
QString("TSPacket pid(0x%3) ").arg(tspacket->PID(),2,16,QChar('0')) +
QString("Discarding broken PSIP packet. ") +
QString("Packet with %1 bytes doesn't fit into a buffer of %2 bytes.")
.arg(packetStart).arg(partial->TSSizeInBuffer()));
delete psip;
psip = nullptr;
}
moreTablePackets = false;
DeletePartialPSIP(tspacket->PID());
return psip;
}
if (partial)
{
if (broken)
{
DeletePartialPSIP(tspacket->PID());
}
moreTablePackets = false;
return nullptr; // partial packet is not yet complete.
}
// First transport stream packet of PSIP packet after here
if (!tspacket->PayloadStart())
{
// We didn't see this PSIP packet's start, so this must be the
// tail end of something we missed. Ignore it.
moreTablePackets = false;
return nullptr;
}
// table_id (8 bits) and section_length(12), syntax(1), priv(1), res(2)
// pointer_field (+8 bits), since payload start is true if we are here.
const unsigned int extra_offset = 4;
const unsigned int offset = tspacket->AFCOffset() + tspacket->StartOfFieldPointer();
const unsigned char* pesdata = tspacket->data() + offset;
// Get the table length if it is in this packet
int pes_length = 0;
if (offset + 3 < TSPacket::kSize)
{
pes_length = (pesdata[2] & 0x0f) << 8 | pesdata[3];
}
// If the table is not completely in this packet we need another packet.
if (pes_length == 0 || (pes_length + offset + extra_offset) > TSPacket::kSize)
{
SavePartialPSIP(tspacket->PID(), new PSIPTable(*tspacket));
moreTablePackets = false;
return nullptr;
}
// Complete table in one packet after here
auto *psip = new PSIPTable(*tspacket);
// There might be another section after this one in the
// current packet. We need room before the end of the
// packet, and it must not be packet stuffing.
if ((offset + psip->SectionLength() + 1 < TSPacket::kSize) &&
(pesdata[psip->SectionLength() + 1] != 0xff))
{
// This isn't stuffing, so we need to put this
// on as a partial packet.
auto *pesp = new PSIPTable(*tspacket);
pesp->SetPSIOffset(offset + psip->SectionLength());
SavePartialPSIP(tspacket->PID(), pesp);
return psip;
}
moreTablePackets = false;
return psip;
}
bool MPEGStreamData::CreatePATSingleProgram(
const ProgramAssociationTable& pat)
{
LOG(VB_RECORD, LOG_DEBUG, LOC + "CreatePATSingleProgram()");
LOG(VB_RECORD, LOG_DEBUG, LOC + "PAT in input stream");
LOG(VB_RECORD, LOG_DEBUG, LOC + pat.toString());
if (m_desiredProgram < 0)
{
LOG(VB_RECORD, LOG_ERR, LOC + "Desired program not set yet");
return false;
}
m_pidPmtSingleProgram = pat.FindPID(m_desiredProgram);
LOG(VB_RECORD, LOG_DEBUG, LOC + QString("desired_program(%1) pid(0x%2)").
arg(m_desiredProgram).arg(m_pidPmtSingleProgram, 0, 16));
if (!m_pidPmtSingleProgram)
{
m_pidPmtSingleProgram = pat.FindAnyPID();
if (!m_pidPmtSingleProgram)
{
LOG(VB_GENERAL, LOG_ERR, LOC + "No program found in PAT. "
"This recording will not play in MythTV.");
}
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("Desired program #%1 not found in PAT."
"\n\t\t\tCannot create single program PAT.")
.arg(m_desiredProgram));
SetPATSingleProgram(nullptr);
return false;
}
AddListeningPID(m_pidPmtSingleProgram);
std::vector<uint> pnums;
std::vector<uint> pids;
pnums.push_back(1);
pids.push_back(m_pidPmtSingleProgram);
uint tsid = pat.TableIDExtension();
uint ver = pat.Version();
ProgramAssociationTable* pat2 =
ProgramAssociationTable::Create(tsid, ver, pnums, pids);
if (!pat2)
{
LOG(VB_GENERAL, LOG_ERR, LOC +
"MPEGStreamData::CreatePATSingleProgram: "
"Failed to create Program Association Table.");
return false;
}
pat2->tsheader()->SetContinuityCounter(pat.tsheader()->ContinuityCounter());
LOG(VB_RECORD, LOG_DEBUG, LOC + QString("pmt_pid(0x%1)")
.arg(m_pidPmtSingleProgram, 0, 16));
LOG(VB_RECORD, LOG_DEBUG, LOC + "PAT for output stream");
LOG(VB_RECORD, LOG_DEBUG, LOC + pat2->toString());
SetPATSingleProgram(pat2);
return true;
}
static desc_list_t extract_atsc_desc(const tvct_vec_t &tvct,
const cvct_vec_t &cvct,
uint pnum)
{
desc_list_t desc;
std::vector<const VirtualChannelTable*> vct;
for (const auto *i : tvct)
vct.push_back(i);
for (const auto *i : cvct)
vct.push_back(i);
for (size_t i = 0; i < tvct.size(); i++)
{
for (uint j = 0; j < vct[i]->ChannelCount(); j++)
{
if (vct[i]->ProgramNumber(j) == pnum)
{
desc_list_t ldesc = MPEGDescriptor::ParseOnlyInclude(
vct[i]->Descriptors(j), vct[i]->DescriptorsLength(j),
DescriptorID::caption_service);
if (!ldesc.empty())
desc.insert(desc.end(), ldesc.begin(), ldesc.end());
}
}
if (0 != vct[i]->GlobalDescriptorsLength())
{
desc_list_t vdesc = MPEGDescriptor::ParseOnlyInclude(
vct[i]->GlobalDescriptors(),
vct[i]->GlobalDescriptorsLength(),
DescriptorID::caption_service);
if (!vdesc.empty())
desc.insert(desc.end(), vdesc.begin(), vdesc.end());
}
}
return desc;
}
bool MPEGStreamData::CreatePMTSingleProgram(const ProgramMapTable &pmt)
{
LOG(VB_RECORD, LOG_DEBUG, LOC + "CreatePMTSingleProgram()");
LOG(VB_RECORD, LOG_DEBUG, LOC + "PMT in input stream");
LOG(VB_RECORD, LOG_DEBUG, LOC + pmt.toString());
if (!PATSingleProgram())
{
LOG(VB_RECORD, LOG_ERR, LOC + "no PAT yet...");
return false; // no way to properly rewrite pids without PAT
}
pmt.Parse();
uint programNumber = 1; // MPEG Program Number
ATSCStreamData *sd = nullptr;
tvct_vec_t tvct;
cvct_vec_t cvct;
desc_list_t gdesc;
if (!m_stripPmtDescriptors)
{
gdesc = MPEGDescriptor::ParseAndExclude(
pmt.ProgramInfo(), pmt.ProgramInfoLength(),
DescriptorID::conditional_access);
// If there is no caption descriptor in PMT, copy any caption
// descriptor found in VCT to global descriptors...
sd = dynamic_cast<ATSCStreamData*>(this);
if (sd && !MPEGDescriptor::Find(gdesc, DescriptorID::caption_service))
{
tvct = sd->GetCachedTVCTs();
cvct = sd->GetCachedCVCTs();
desc_list_t vdesc = extract_atsc_desc(
tvct, cvct, pmt.ProgramNumber());
if (!vdesc.empty())
gdesc.insert(gdesc.end(), vdesc.begin(), vdesc.end());
}
}
std::vector<uint> pids;
std::vector<uint> types;
std::vector<desc_list_t> pdesc;
uint video_cnt = 0;
uint audio_cnt = 0;
std::vector<uint> videoPIDs;
std::vector<uint> audioPIDs;
std::vector<uint> dataPIDs;
for (uint i = 0; i < pmt.StreamCount(); i++)
{
uint pid = pmt.StreamPID(i);
desc_list_t desc = MPEGDescriptor::ParseAndExclude(
pmt.StreamInfo(i), pmt.StreamInfoLength(i),
DescriptorID::conditional_access);
uint type = StreamID::Normalize(
pmt.StreamType(i), desc, m_siStandard);
bool is_video = StreamID::IsVideo(type);
bool is_audio = StreamID::IsAudio(type);
if (is_audio)
{
audio_cnt++;
audioPIDs.push_back(pid);
}
else if (m_recordingType == "audio" )
{
// If not an audio PID but we only want audio,
// ignore this PID.
continue;
}
#ifdef DEBUG_MPEG_RADIO
if (is_video)
continue;
#endif // DEBUG_MPEG_RADIO
if (is_video)
{
video_cnt++;
videoPIDs.push_back(pid);
}
if (m_stripPmtDescriptors)
desc.clear();
// Filter out streams not used for basic television
if (m_recordingType == "tv" && !is_audio && !is_video &&
!MPEGDescriptor::Find(desc, DescriptorID::teletext) &&
!MPEGDescriptor::Find(desc, DescriptorID::subtitling) &&
pid != pmt.PCRPID()) // We must not strip the PCR!
{
continue;
}
if (!is_audio && !is_video) //NOTE: Anything which isn't audio or video is data
dataPIDs.push_back(pid);
pdesc.push_back(desc);
pids.push_back(pid);
types.push_back(type);
}
if (video_cnt < m_pmtSingleProgramNumVideo)
{
LOG(VB_RECORD, LOG_ERR, LOC +
QString("Only %1 video streams seen in PMT, but %2 are required.")
.arg(video_cnt).arg(m_pmtSingleProgramNumVideo));
return false;
}
if (audioPIDs.size() < m_pmtSingleProgramNumAudio)
{
LOG(VB_RECORD, LOG_ERR, LOC +
QString("Only %1 audio streams seen in PMT, but %2 are required.")
.arg(audioPIDs.size()).arg(m_pmtSingleProgramNumAudio));
return false;
}
desc_list_t cdesc = MPEGDescriptor::ParseOnlyInclude(
pmt.ProgramInfo(), pmt.ProgramInfoLength(),
DescriptorID::conditional_access);
for (auto & i : cdesc)
{
ConditionalAccessDescriptor cad(i);
if (cad.IsValid())
{
AddListeningPID(cad.PID());
AddConditionalAccessPID(cad.PID());
}
}
m_pidsAudio.clear();
for (uint pid : audioPIDs)
AddAudioPID(pid);
m_pidsWriting.clear();
m_pidVideoSingleProgram = !videoPIDs.empty() ? videoPIDs[0] : 0xffffffff;
for (size_t i = 1; i < videoPIDs.size(); i++)
AddWritingPID(videoPIDs[i]);
for (uint pid : dataPIDs)
AddWritingPID(pid);
// Timebase
int pcrpidIndex = pmt.FindPID(pmt.PCRPID());
if (pcrpidIndex < 0)
{
// the timecode reference stream is not in the PMT,
// add stream to misc record streams
AddWritingPID(pmt.PCRPID());
}
// Create the PMT
ProgramMapTable *pmt2 = ProgramMapTable::Create(
programNumber, m_pidPmtSingleProgram, pmt.PCRPID(),
pmt.Version(), gdesc, pids, types, pdesc);
// Return any TVCT & CVCT tables, once we've copied any descriptors.
if (sd)
{
sd->ReturnCachedTVCTTables(tvct);
sd->ReturnCachedCVCTTables(cvct);
}
// Set Continuity Header
uint cc_cnt = pmt.tsheader()->ContinuityCounter();
pmt2->tsheader()->SetContinuityCounter(cc_cnt);
SetPMTSingleProgram(pmt2);
LOG(VB_RECORD, LOG_DEBUG, LOC + "PMT for output stream");
LOG(VB_RECORD, LOG_DEBUG, LOC + pmt2->toString());
return true;
}
/** \fn MPEGStreamData::IsRedundant(uint pid, const PSIPTable&) const
* \brief Returns true if table already seen.
*/
bool MPEGStreamData::IsRedundant(uint pid, const PSIPTable &psip) const
{
(void) pid;
const int table_id = psip.TableID();
const int version = psip.Version();
if (TableID::PAT == table_id)
{
return m_patStatus.IsSectionSeen(psip.TableIDExtension(), version, psip.Section());
}
if (TableID::CAT == table_id)
{
return m_catStatus.IsSectionSeen(psip.TableIDExtension(), version, psip.Section());
}
if (TableID::PMT == table_id)
{
return m_pmtStatus.IsSectionSeen(psip.TableIDExtension(), version, psip.Section());
}
return false;
}
/** \fn MPEGStreamData::HandleTables(uint pid, const PSIPTable &psip)
* \brief Process PSIP packets.
*/
bool MPEGStreamData::HandleTables(uint pid, const PSIPTable &psip)
{
if (MPEGStreamData::IsRedundant(pid, psip))
return true;
const int version = psip.Version();
// If we get this far decode table
switch (psip.TableID())
{
case TableID::PAT:
{
uint tsid = psip.TableIDExtension();
m_patStatus.SetSectionSeen(tsid, version, psip.Section(), psip.LastSection());
ProgramAssociationTable pat(psip);
if (m_cacheTables)
CachePAT(&pat);
ProcessPAT(&pat);
return true;
}
case TableID::CAT:
{
uint tsid = psip.TableIDExtension();
m_catStatus.SetSectionSeen(tsid, version, psip.Section(), psip.LastSection());
ConditionalAccessTable cat(psip);
if (m_cacheTables)
CacheCAT(&cat);
ProcessCAT(&cat);
return true;
}
case TableID::PMT:
{
uint prog_num = psip.TableIDExtension();
m_pmtStatus.SetSectionSeen(prog_num, version, psip.Section(), psip.LastSection());
ProgramMapTable pmt(psip);
if (m_cacheTables)
CachePMT(&pmt);
ProcessPMT(&pmt);
return true;
}
case TableID::SITscte:
{
SpliceInformationTable sit(psip);
sit.setSCTEPID(pid);
m_listenerLock.lock();
for (auto & listener : m_mpegListeners)
listener->HandleSplice(&sit);
m_listenerLock.unlock();
return true;
}
}
return false;
}
void MPEGStreamData::ProcessPAT(const ProgramAssociationTable *pat)
{
bool foundProgram = pat->FindPID(m_desiredProgram) != 0U;
m_listenerLock.lock();
for (auto & listener : m_mpegListeners)
listener->HandlePAT(pat);
m_listenerLock.unlock();
if (m_desiredProgram < 0)
return;
bool send_single_program = false;
if (!m_invalidPatSeen && !foundProgram)
{
m_invalidPatSeen = true;
m_invalidPatWarning = false;
m_invalidPatTimer.start();
LOG(VB_RECORD, LOG_WARNING, LOC +
"ProcessPAT: PAT is missing program, setting timeout");
}
else if (m_invalidPatSeen && !foundProgram &&
(m_invalidPatTimer.elapsed() > 400) && !m_invalidPatWarning)
{
m_invalidPatWarning = true; // only emit one warning...
// After 400ms emit error if we haven't found correct PAT.
LOG(VB_GENERAL, LOG_ERR, LOC + "ProcessPAT: Program not found in PAT. "
"Rescan your transports.");
send_single_program = CreatePATSingleProgram(*pat);
}
else if (foundProgram)
{
if (m_invalidPatSeen)
LOG(VB_RECORD, LOG_INFO, LOC +
"ProcessPAT: Good PAT seen after a bad PAT");
m_invalidPatSeen = false;
send_single_program = CreatePATSingleProgram(*pat);
}
if (send_single_program)
{
QMutexLocker locker(&m_listenerLock);
ProgramAssociationTable *pat_sp = PATSingleProgram();
for (auto & listener : m_mpegSpListeners)
listener->HandleSingleProgramPAT(pat_sp, false);
}
}
void MPEGStreamData::ProcessCAT(const ConditionalAccessTable *cat)
{
m_listenerLock.lock();
for (auto & listener : m_mpegListeners)
listener->HandleCAT(cat);
m_listenerLock.unlock();
desc_list_t cdesc = MPEGDescriptor::ParseOnlyInclude(
cat->Descriptors(), cat->DescriptorsLength(),
DescriptorID::conditional_access);
for (auto & i : cdesc)
{
ConditionalAccessDescriptor cad(i);
if (cad.IsValid())
{
AddListeningPID(cad.PID());
AddConditionalAccessPID(cad.PID());
}
}
}
void MPEGStreamData::ProcessPMT(const ProgramMapTable *pmt)
{
m_listenerLock.lock();
for (auto & listener : m_mpegListeners)
listener->HandlePMT(pmt->ProgramNumber(), pmt);
m_listenerLock.unlock();
bool desired = pmt->ProgramNumber() == (uint) m_desiredProgram;
if (desired && CreatePMTSingleProgram(*pmt))
{
QMutexLocker locker(&m_listenerLock);
ProgramMapTable *pmt_sp = PMTSingleProgram();
for (auto & listener : m_mpegSpListeners)
listener->HandleSingleProgramPMT(pmt_sp, false);
}
}
double MPEGStreamData::TimeOffset(void) const
{
QMutexLocker locker(&m_siTimeLock);
if (!m_siTimeOffsetCnt)
return 0.0;
double avg_offset = 0.0;
double mult = 1.0 / m_siTimeOffsetCnt;
for (uint i = 0; i < m_siTimeOffsetCnt; i++)
avg_offset += m_siTimeOffsets[i] * mult;
return avg_offset;
}
void MPEGStreamData::UpdateTimeOffset(uint64_t _si_utc_time)
{
struct timeval tm {};
if (gettimeofday(&tm, nullptr) != 0)
return;
double utc_time = tm.tv_sec + (tm.tv_usec * 0.000001);
double si_time = _si_utc_time;
QMutexLocker locker(&m_siTimeLock);
m_siTimeOffsets[m_siTimeOffsetIndx] = si_time - utc_time;
if (m_siTimeOffsetIndx + 1 > m_siTimeOffsetCnt)
m_siTimeOffsetCnt = m_siTimeOffsetIndx + 1;
m_siTimeOffsetIndx = (m_siTimeOffsetIndx + 1) & 0xf;
}
#define DONE_WITH_PSIP_PACKET() { delete psip; \
if (morePSIPTables) goto HAS_ANOTHER_PSIP; else return; }
/** \fn MPEGStreamData::HandleTSTables(const TSPacket*)
* \brief Assembles PSIP packets and processes them.
*/
void MPEGStreamData::HandleTSTables(const TSPacket* tspacket)
{
bool morePSIPTables = false;
HAS_ANOTHER_PSIP:
// Assemble PSIP
PSIPTable *psip = AssemblePSIP(tspacket, morePSIPTables);
if (!psip)
return;
// drop stuffing packets
if ((TableID::ST == psip->TableID()) ||
(TableID::STUFFING == psip->TableID()))
{
LOG(VB_RECORD, LOG_DEBUG, LOC + "Dropping Stuffing table");
DONE_WITH_PSIP_PACKET();
}
// Don't do validation on tables without CRC
if (!psip->HasCRC())
{
HandleTables(tspacket->PID(), *psip);
DONE_WITH_PSIP_PACKET();
}
// Validate PSIP
// but don't validate PMT/PAT if our driver has the PMT/PAT CRC bug.
bool buggy = m_haveCrcBug &&
((TableID::PMT == psip->TableID()) ||
(TableID::PAT == psip->TableID()));
if (!buggy && !psip->IsGood())
{
LOG(VB_RECORD, LOG_ERR, LOC +
QString("PSIP packet failed CRC check. pid(0x%1) type(0x%2)")
.arg(tspacket->PID(),0,16).arg(psip->TableID(),0,16));
DONE_WITH_PSIP_PACKET();
}
if (TableID::MGT <= psip->TableID() && psip->TableID() <= TableID::STT &&
!psip->IsCurrent())
{ // we don't cache the next table, for now
LOG(VB_RECORD, LOG_DEBUG, LOC + QString("Table not current 0x%1")
.arg(psip->TableID(),2,16,QChar('0')));
DONE_WITH_PSIP_PACKET();
}
if (tspacket->Scrambled())
{ // scrambled! ATSC, DVB require tables not to be scrambled
LOG(VB_RECORD, LOG_ERR, LOC +
"PSIP packet is scrambled, not ATSC/DVB compiant");
DONE_WITH_PSIP_PACKET();
}
if (!psip->VerifyPSIP(!m_haveCrcBug))
{
LOG(VB_RECORD, LOG_ERR, LOC + QString("PSIP table 0x%1 is invalid")
.arg(psip->TableID(),2,16,QChar('0')));
DONE_WITH_PSIP_PACKET();
}
// Don't decode redundant packets,
// but if it is a desired PAT or PMT emit a "heartbeat" signal.
if (MPEGStreamData::IsRedundant(tspacket->PID(), *psip))
{
if (TableID::PAT == psip->TableID())
{
QMutexLocker locker(&m_listenerLock);
ProgramAssociationTable *pat_sp = PATSingleProgram();
for (auto & listener : m_mpegSpListeners)
listener->HandleSingleProgramPAT(pat_sp, false);
}
if (TableID::PMT == psip->TableID() &&
tspacket->PID() == m_pidPmtSingleProgram)
{
QMutexLocker locker(&m_listenerLock);
ProgramMapTable *pmt_sp = PMTSingleProgram();
for (auto & listener : m_mpegSpListeners)
listener->HandleSingleProgramPMT(pmt_sp, false);
}
DONE_WITH_PSIP_PACKET(); // already parsed this table, toss it.
}
HandleTables(tspacket->PID(), *psip);
DONE_WITH_PSIP_PACKET();
}
#undef DONE_WITH_PSIP_PACKET
int MPEGStreamData::ProcessData(const unsigned char *buffer, int len)
{
int pos = 0;
bool resync = false;
if (!m_psListeners.empty())
{
for (auto & listener : m_psListeners)
listener->FindPSKeyFrames(buffer, len);
return 0;
}
while (pos + int(TSPacket::kSize) <= len)
{ // while we have a whole packet left...
if (buffer[pos] != SYNC_BYTE || resync)
{
int newpos = ResyncStream(buffer, pos+1, len);
LOG(VB_RECORD, LOG_DEBUG, LOC +
QString("Resyncing @ %1+1 w/len %2 -> %3")
.arg(pos).arg(len).arg(newpos));
if (newpos == -1)
return len - pos;
if (newpos == -2)
return TSPacket::kSize;
pos = newpos;
}
const auto *pkt = reinterpret_cast<const TSPacket*>(&buffer[pos]);
pos += TSPacket::kSize; // Advance to next TS packet
resync = false;
if (!ProcessTSPacket(*pkt))
{
if (pos + int(TSPacket::kSize) > len)
continue;
if (buffer[pos] != SYNC_BYTE)
{
// if ProcessTSPacket fails, and we don't appear to be
// in sync on the next packet, then resync. Otherwise
// just process the next packet normally.
pos -= TSPacket::kSize;
resync = true;
}
}