/
channelscan_sm.cpp
2557 lines (2177 loc) · 81.8 KB
/
channelscan_sm.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++ -*-
* vim: set expandtab tabstop=4 shiftwidth=4:
*
* Original Project
* MythTV http://www.mythtv.org
*
* Copyright (c) 2004, 2005 John Pullan <john@pullan.org>
* Copyright (c) 2005 - 2007 Daniel Kristjansson
*
* Description:
* Collection of classes to provide channel scanning functionallity
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*
*/
// C includes
#include <unistd.h>
// C++ includes
#include <algorithm>
using namespace std;
// Qt includes
#include <QObject>
#include <QMutexLocker>
// MythTV includes - General
#include "channelscan_sm.h"
#include "frequencies.h"
#include "scanwizardconfig.h"
#include "mythdbcon.h"
#include "channelutil.h"
#include "cardutil.h"
#include "sourceutil.h"
#include "mthread.h"
#include "mythdb.h"
#include "mythlogging.h"
// MythTV includes - DTV
#include "dtvsignalmonitor.h"
#include "scanstreamdata.h"
// MythTV includes - ATSC
#include "atsctables.h"
// MythTV includes - DVB
#include "dvbsignalmonitor.h"
#include "dvbtables.h"
#include "dvbchannel.h"
#include "hdhrchannel.h"
#include "v4lchannel.h"
/// SDT's should be sent every 2 seconds and NIT's every
/// 10 seconds, so lets wait at least 30 seconds, in
/// case of bad transmitter or lost packets.
const uint ChannelScanSM::kDVBTableTimeout = 30 * 1000;
/// No logic here, lets just wait at least 10 seconds.
const uint ChannelScanSM::kATSCTableTimeout = 10 * 1000;
/// No logic here, lets just wait at least 15 seconds.
const uint ChannelScanSM::kMPEGTableTimeout = 15 * 1000;
// Astra 28.2E satellite Logical Channel Number selection default values
static const uint kBouquetID = 272; // Freesat England HD
static const uint kRegionID = 1; // London
static const uint kRegionUndefined = 0xFFFF; // Not regional
QString ChannelScanSM::loc(const ChannelScanSM *siscan)
{
if (siscan && siscan->m_channel)
return QString("ChannelScanSM(%1)").arg(siscan->m_channel->GetDevice());
return "ChannelScanSM(u)";
}
#define LOC (ChannelScanSM::loc(this) + ": ")
#define kDecryptionTimeout 4250
class ScannedChannelInfo
{
public:
ScannedChannelInfo() = default;
bool IsEmpty() const
{
return m_pats.empty() && m_pmts.empty() &&
m_program_encryption_status.isEmpty() &&
!m_mgt && m_cvcts.empty() &&
m_tvcts.empty() && m_nits.empty() &&
m_sdts.empty() && m_bats.empty();
}
// MPEG
pat_map_t m_pats;
pmt_vec_t m_pmts;
QMap<uint,uint> m_program_encryption_status; // pnum->enc_status
// ATSC
const MasterGuideTable *m_mgt {nullptr};
cvct_vec_t m_cvcts;
tvct_vec_t m_tvcts;
// DVB
nit_vec_t m_nits;
sdt_map_t m_sdts;
bat_vec_t m_bats;
};
/** \class ChannelScanSM
* \brief Scanning class for cards that support a SignalMonitor class.
*
* With ScanStreamData, we call ScanTransport() on each transport
* and frequency offset in the list of transports. This list is
* created from a FrequencyTable object.
*
* Each ScanTransport() call resets the ScanStreamData and the
* SignalMonitor, then tunes to a new frequency and notes the tuning
* time in the "timer" QTime object.
*
* HandleActiveScan is called every time through the event loop
* and is what calls ScanTransport(), as well as checking when
* the current time is "timeoutTune" or "channelTimeout" milliseconds
* ahead of "timer". When the "timeoutTune" is exceeded we check
* to see if we have a signal lock on the channel, if we don't we
* check the next transport. When the larger "channelTimeout" is
* exceeded we do nothing unless "waitingForTables" is still true,
*
* TODO
*
*/
ChannelScanSM::ChannelScanSM(ScanMonitor *_scan_monitor,
const QString &_cardtype, ChannelBase *_channel,
int _sourceID, uint signal_timeout,
uint channel_timeout, const QString &_inputname,
bool test_decryption)
: // Set in constructor
m_scanMonitor(_scan_monitor),
m_channel(_channel),
m_signalMonitor(SignalMonitor::Init(_cardtype, m_channel->GetInputID(),
_channel, true)),
m_sourceID(_sourceID),
m_signalTimeout(signal_timeout),
m_channelTimeout(channel_timeout),
m_inputName(_inputname),
m_testDecryption(test_decryption),
// Misc
m_analogSignalHandler(new AnalogSignalHandler(this))
{
m_current = m_scanTransports.end();
// Create a stream data for digital signal monitors
DTVSignalMonitor* dtvSigMon = GetDTVSignalMonitor();
if (dtvSigMon)
{
LOG(VB_CHANSCAN, LOG_INFO, LOC + "Connecting up DTVSignalMonitor");
ScanStreamData *data = new ScanStreamData();
if (gCoreContext->GetNumSetting("DBSchemaVer") > 1350)
{
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(
"SELECT dvb_nit_id, bouquet_id, region_id "
"FROM videosource "
"WHERE videosource.sourceid = :SOURCEID");
query.bindValue(":SOURCEID", _sourceID);
if (!query.exec() || !query.isActive())
{
MythDB::DBError("ChannelScanSM", query);
}
else if (query.next())
{
int nitid = query.value(0).toInt();
data->SetRealNetworkID(nitid);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Setting NIT-ID to %1").arg(nitid));
m_bouquet_id = query.value(1).toUInt();
m_region_id = query.value(2).toUInt();
}
}
else
{
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(
"SELECT dvb_nit_id "
"FROM videosource "
"WHERE videosource.sourceid = :SOURCEID");
query.bindValue(":SOURCEID", _sourceID);
if (!query.exec() || !query.isActive())
{
MythDB::DBError("ChannelScanSM", query);
}
else if (query.next())
{
int nitid = query.value(0).toInt();
data->SetRealNetworkID(nitid);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Setting NIT-ID to %1").arg(nitid));
// Bouquet and region default or from the environment
QString bouquet_id = QString(getenv("FSAT_BOUQUET_ID"));
m_bouquet_id = bouquet_id.isEmpty() ? kBouquetID : bouquet_id.toUInt();
QString region_id = QString(getenv("FSAT_REGION_ID"));
m_region_id = region_id.isEmpty() ? kRegionID : region_id.toUInt();
}
}
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Freesat/BSkyB bouquet_id:%1 region_id:%2")
.arg(m_bouquet_id).arg(m_region_id));
dtvSigMon->SetStreamData(data);
dtvSigMon->AddFlags(SignalMonitor::kDTVSigMon_WaitForMGT |
SignalMonitor::kDTVSigMon_WaitForVCT |
SignalMonitor::kDTVSigMon_WaitForNIT |
SignalMonitor::kDTVSigMon_WaitForSDT);
#ifdef USING_DVB
DVBChannel *dvbchannel = dynamic_cast<DVBChannel*>(m_channel);
if (dvbchannel && dvbchannel->GetRotor())
dtvSigMon->AddFlags(SignalMonitor::kDVBSigMon_WaitForPos);
#endif
data->AddMPEGListener(this);
data->AddATSCMainListener(this);
data->AddDVBMainListener(this);
data->AddDVBOtherListener(this);
}
}
ChannelScanSM::~ChannelScanSM(void)
{
StopScanner();
LOG(VB_CHANSCAN, LOG_INFO, LOC + "ChannelScanSM Stopped");
ScanStreamData *sd = nullptr;
if (GetDTVSignalMonitor())
{
sd = GetDTVSignalMonitor()->GetScanStreamData();
}
if (m_signalMonitor)
{
m_signalMonitor->RemoveListener(m_analogSignalHandler);
delete m_signalMonitor;
m_signalMonitor = nullptr;
}
delete sd;
if (m_analogSignalHandler)
{
delete m_analogSignalHandler;
m_analogSignalHandler = nullptr;
}
teardown_frequency_tables();
}
void ChannelScanSM::SetAnalog(bool is_analog)
{
m_signalMonitor->RemoveListener(m_analogSignalHandler);
if (is_analog)
m_signalMonitor->AddListener(m_analogSignalHandler);
}
void ChannelScanSM::HandleAllGood(void)
{
QMutexLocker locker(&m_lock);
QString cur_chan = (*m_current).m_friendlyName;
QStringList list = cur_chan.split(" ", QString::SkipEmptyParts);
QString freqid = (list.size() >= 2) ? list[1] : cur_chan;
QString msg = QObject::tr("Updated Channel %1").arg(cur_chan);
if (!ChannelUtil::FindChannel(m_sourceID, freqid))
{
int chanid = ChannelUtil::CreateChanID(m_sourceID, freqid);
QString callsign = QString("%1-%2")
.arg(ChannelUtil::GetUnknownCallsign()).arg(chanid);
bool ok = ChannelUtil::CreateChannel(
0 /* mplexid */,
m_sourceID,
chanid,
callsign,
"" /* service name */,
freqid /* channum */,
0 /* service id */,
0 /* ATSC major channel */,
0 /* ATSC minor channel */,
false /* use on air guide */,
false /* hidden */,
false /* hidden in guide */,
freqid);
msg = (ok) ?
QObject::tr("Added Channel %1").arg(cur_chan) :
QObject::tr("Failed to add channel %1").arg(cur_chan);
}
else
{
// nothing to do here, XMLTV has better info
}
m_scanMonitor->ScanAppendTextToLog(msg);
// tell UI we are done with these channels
if (m_scanning)
{
UpdateScanPercentCompleted();
m_waitingForTables = false;
m_nextIt = m_current.nextTransport();
m_dvbt2Tried = true;
}
}
/**
* \brief If we are not already scanning a frequency table, this creates
* a new frequency table from database and begins scanning it.
*
* This is used by DVB to scan for channels we are told about from other
* channels.
*
* Note: Something similar could be used with ATSC when EIT for other
* channels is available on another ATSC channel, as encouraged by the
* ATSC specification.
*/
bool ChannelScanSM::ScanExistingTransports(uint sourceid, bool follow_nit)
{
if (m_scanning)
return false;
m_scanTransports.clear();
m_nextIt = m_scanTransports.end();
vector<uint> multiplexes = SourceUtil::GetMplexIDs(sourceid);
if (multiplexes.empty())
{
LOG(VB_CHANSCAN, LOG_ERR, LOC + "Unable to find any transports for " +
QString("sourceid %1").arg(sourceid));
return false;
}
for (size_t i = 0; i < multiplexes.size(); ++i)
AddToList(multiplexes[i]);
m_extendScanList = follow_nit;
m_waitingForTables = false;
m_transportsScanned = 0;
if (!m_scanTransports.empty())
{
m_nextIt = m_scanTransports.begin();
m_scanning = true;
}
else
{
LOG(VB_CHANSCAN, LOG_ERR, LOC +
"Unable to find add any transports for " +
QString("sourceid %1").arg(sourceid));
return false;
}
return m_scanning;
}
void ChannelScanSM::LogLines(const QString& string) const
{
QStringList lines = string.split('\n');
for (int i = 0; i < lines.size(); ++i)
LOG(VB_CHANSCAN, LOG_DEBUG, lines[i]);
}
void ChannelScanSM::HandlePAT(const ProgramAssociationTable *pat)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Got a Program Association Table for %1")
.arg((*m_current).m_friendlyName));
LogLines(pat->toString());
// Add pmts to list, so we can do MPEG scan properly.
ScanStreamData *sd = GetDTVSignalMonitor()->GetScanStreamData();
for (uint i = 0; i < pat->ProgramCount(); ++i)
{
if (pat->ProgramPID(i)) // don't add NIT "program", MPEG/ATSC safe.
sd->AddListeningPID(pat->ProgramPID(i));
}
}
void ChannelScanSM::HandlePMT(uint /*program_num*/, const ProgramMapTable *pmt)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC + QString("Got a Program Map Table for %1 program %2 (0x%3)")
.arg((*m_current).m_friendlyName).arg(pmt->ProgramNumber())
.arg(pmt->ProgramNumber(),4,16,QChar('0')));
LogLines(pmt->toString());
if (!m_currentTestingDecryption &&
pmt->IsEncrypted(GetDTVChannel()->GetSIStandard()))
m_currentEncryptionStatus[pmt->ProgramNumber()] = kEncUnknown;
}
void ChannelScanSM::HandleVCT(uint /*pid*/, const VirtualChannelTable *vct)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Got a Virtual Channel Table for %1")
.arg((*m_current).m_friendlyName));
LogLines(vct->toString());
for (uint i = 0; !m_currentTestingDecryption && i < vct->ChannelCount(); ++i)
{
if (vct->IsAccessControlled(i))
{
m_currentEncryptionStatus[vct->ProgramNumber(i)] = kEncUnknown;
}
}
UpdateChannelInfo(true);
}
void ChannelScanSM::HandleMGT(const MasterGuideTable *mgt)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC + QString("Got the Master Guide for %1")
.arg((*m_current).m_friendlyName));
LogLines(mgt->toString());
UpdateChannelInfo(true);
}
/**
* \fn ChannelScanSM::HandleSDT
*
* \param tsid Unused. Present so that the HandleSDT and HandleSDTo
* functions have the same type signature.
* \param sdt A pointer to the service description table.
*/
void ChannelScanSM::HandleSDT(uint /*tsid*/, const ServiceDescriptionTable *sdt)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Got a Service Description Table for %1 section %2/%3")
.arg((*m_current).m_friendlyName)
.arg(sdt->Section()).arg(sdt->LastSection()));
LogLines(sdt->toString());
// If this is Astra 28.2 add start listening for Freesat BAT and SDTo
if (!m_setOtherTables && (
sdt->OriginalNetworkID() == OriginalNetworkID::SES2 ||
sdt->OriginalNetworkID() == OriginalNetworkID::BBC))
{
GetDTVSignalMonitor()->GetScanStreamData()->
SetFreesatAdditionalSI(true);
m_setOtherTables = true;
// The whole BAT & SDTo group comes round in 10s
m_otherTableTimeout = 10000;
// Delay processing the SDT until we've seen BATs and SDTos
m_otherTableTime = m_timer.elapsed() + m_otherTableTimeout;
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("SDT has OriginalNetworkID %1, look for "
"additional Freesat SI").arg(sdt->OriginalNetworkID()));
}
if ((uint)m_timer.elapsed() < m_otherTableTime)
{
// Set the version for the SDT so we see it again.
GetDTVSignalMonitor()->GetDVBStreamData()->
SetVersionSDT(sdt->TSID(), -1, 0);
}
uint id = sdt->OriginalNetworkID() << 16 | sdt->TSID();
m_tsScanned.insert(id);
for (uint i = 0; !m_currentTestingDecryption && i < sdt->ServiceCount(); ++i)
{
if (sdt->IsEncrypted(i))
{
m_currentEncryptionStatus[sdt->ServiceID(i)] = kEncUnknown;
}
}
UpdateChannelInfo(true);
}
void ChannelScanSM::HandleNIT(const NetworkInformationTable *nit)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Got a Network Information Table id %1 for %2 section %3/%4")
.arg(nit->NetworkID()).arg((*m_current).m_friendlyName)
.arg(nit->Section()).arg(nit->LastSection()));
LogLines(nit->toString());
UpdateChannelInfo(true);
}
void ChannelScanSM::HandleBAT(const BouquetAssociationTable *bat)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Got a Bouquet Association Table id %1 for %2 section %3/%4")
.arg(bat->BouquetID()).arg((*m_current).m_friendlyName)
.arg(bat->Section()).arg(bat->LastSection()));
LogLines(bat->toString());
m_otherTableTime = m_timer.elapsed() + m_otherTableTimeout;
for (uint i = 0; i < bat->TransportStreamCount(); ++i)
{
uint tsid = bat->TSID(i);
uint netid = bat->OriginalNetworkID(i);
desc_list_t parsed =
MPEGDescriptor::Parse(bat->TransportDescriptors(i),
bat->TransportDescriptorsLength(i));
// Look for default authority
const unsigned char *def_auth =
MPEGDescriptor::Find(parsed, DescriptorID::default_authority);
const unsigned char *serv_list =
MPEGDescriptor::Find(parsed, DescriptorID::service_list);
if (def_auth && serv_list)
{
DefaultAuthorityDescriptor authority(def_auth);
ServiceListDescriptor services(serv_list);
if (!authority.IsValid() || !services.IsValid())
continue;
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Found default authority '%1' in BAT for services in %2 %3")
.arg(authority.DefaultAuthority())
.arg(netid).arg(tsid));
for (uint j = 0; j < services.ServiceCount(); ++j)
{
// If the default authority is given in the SDT this
// overrides any definition in the BAT (or in the NIT)
LOG(VB_CHANSCAN, LOG_DEBUG, LOC +
QString("Found default authority '%1' in BAT for service %2 %3 %4")
.arg(authority.DefaultAuthority())
.arg(netid).arg(tsid).arg(services.ServiceID(j)));
uint64_t index = ((uint64_t)netid << 32) | (tsid << 16) |
services.ServiceID(j);
if (! m_defAuthorities.contains(index))
m_defAuthorities[index] = authority.DefaultAuthority();
}
}
}
UpdateChannelInfo(true);
}
void ChannelScanSM::HandleSDTo(uint tsid, const ServiceDescriptionTable *sdt)
{
QMutexLocker locker(&m_lock);
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Got a Service Description Table (other) for Transport ID %1 section %2/%3")
.arg(tsid).arg(sdt->Section()).arg(sdt->LastSection()));
LogLines(sdt->toString());
m_otherTableTime = m_timer.elapsed() + m_otherTableTimeout;
uint netid = sdt->OriginalNetworkID();
for (uint i = 0; i < sdt->ServiceCount(); ++i)
{
uint serviceId = sdt->ServiceID(i);
desc_list_t parsed =
MPEGDescriptor::Parse(sdt->ServiceDescriptors(i),
sdt->ServiceDescriptorsLength(i));
// Look for default authority
const unsigned char *def_auth =
MPEGDescriptor::Find(parsed, DescriptorID::default_authority);
if (def_auth)
{
DefaultAuthorityDescriptor authority(def_auth);
if (!authority.IsValid())
continue;
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("Found default authority '%1' in SDTo for service %2 %3 %4")
.arg(authority.DefaultAuthority())
.arg(netid).arg(tsid).arg(serviceId));
m_defAuthorities[((uint64_t)netid << 32) | (tsid << 16) | serviceId] =
authority.DefaultAuthority();
}
}
}
void ChannelScanSM::HandleEncryptionStatus(uint pnum, bool encrypted)
{
QMutexLocker locker(&m_lock);
m_currentEncryptionStatus[pnum] = encrypted ? kEncEncrypted : kEncDecrypted;
if (kEncDecrypted == m_currentEncryptionStatus[pnum])
m_currentTestingDecryption = false;
UpdateChannelInfo(true);
}
bool ChannelScanSM::TestNextProgramEncryption(void)
{
if (!m_currentInfo || m_currentInfo->m_pmts.empty())
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Can't monitor decryption -- no pmts");
m_currentTestingDecryption = false;
return false;
}
do
{
uint pnum = 0;
QMap<uint, uint>::const_iterator it = m_currentEncryptionStatus.begin();
#if 0
LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("%1/%2 checked")
.arg(currentEncryptionStatusChecked.size())
.arg(currentEncryptionStatus.size()));
#endif
while (it != m_currentEncryptionStatus.end())
{
if (!m_currentEncryptionStatusChecked[it.key()])
{
pnum = it.key();
break;
}
++it;
}
if (!pnum)
break;
m_currentEncryptionStatusChecked[pnum] = true;
if (!m_testDecryption)
{
m_currentEncryptionStatus[pnum] = kEncEncrypted;
continue;
}
const ProgramMapTable *pmt = nullptr;
for (uint i = 0; !pmt && (i < m_currentInfo->m_pmts.size()); ++i)
{
pmt = (m_currentInfo->m_pmts[i]->ProgramNumber() == pnum) ?
m_currentInfo->m_pmts[i] : nullptr;
}
if (pmt)
{
QString cur_chan, cur_chan_tr;
GetCurrentTransportInfo(cur_chan, cur_chan_tr);
QString msg_tr =
QObject::tr("%1 -- Testing decryption of program %2")
.arg(cur_chan_tr).arg(pnum);
QString msg =
QString("%1 -- Testing decryption of program %2")
.arg(cur_chan).arg(pnum);
m_scanMonitor->ScanAppendTextToLog(msg_tr);
LOG(VB_CHANSCAN, LOG_INFO, LOC + msg);
#ifdef USING_DVB
if (GetDVBChannel())
GetDVBChannel()->SetPMT(pmt);
#endif // USING_DVB
GetDTVSignalMonitor()->GetStreamData()->TestDecryption(pmt);
m_currentTestingDecryption = true;
m_timer.start();
return true;
}
LOG(VB_GENERAL, LOG_INFO, LOC +
QString("Can't monitor decryption of program %1 -- no pmt")
.arg(pnum));
} while (true);
m_currentTestingDecryption = false;
return false;
}
DTVTunerType ChannelScanSM::GuessDTVTunerType(DTVTunerType type) const
{
if (m_scanDTVTunerType != (int)DTVTunerType::kTunerTypeUnknown)
type = m_scanDTVTunerType;
const DTVChannel *chan = GetDTVChannel();
if (!chan)
return type;
vector<DTVTunerType> tts = chan->GetTunerTypes();
for (size_t i = 0; i < tts.size(); ++i)
{
if (tts[i] == type)
return type;
}
if (!tts.empty())
return tts[0];
return type;
}
void ChannelScanSM::UpdateScanTransports(const NetworkInformationTable *nit)
{
for (uint i = 0; i < nit->TransportStreamCount(); ++i)
{
uint32_t tsid = nit->TSID(i);
uint32_t netid = nit->OriginalNetworkID(i);
uint32_t id = netid << 16 | tsid;
if (m_tsScanned.contains(id) || m_extendTransports.contains(id))
continue;
const desc_list_t& list =
MPEGDescriptor::Parse(nit->TransportDescriptors(i),
nit->TransportDescriptorsLength(i));
for (size_t j = 0; j < list.size(); ++j)
{
int mplexid = -1;
uint64_t frequency = 0;
const MPEGDescriptor desc(list[j]);
uint tag = desc.DescriptorTag();
uint length = desc.DescriptorLength();
QString tagString = desc.DescriptorTagString();
DTVTunerType tt(DTVTunerType::kTunerTypeUnknown);
LOG(VB_CHANSCAN, LOG_DEBUG, LOC + QString("ts-loop j:%1 tag:%2 %3 length:%4")
.arg(j).arg(tag).arg(tagString).arg(length));
switch (tag)
{
case DescriptorID::terrestrial_delivery_system:
{
const TerrestrialDeliverySystemDescriptor cd(desc);
frequency = cd.FrequencyHz();
tt = DTVTunerType::kTunerTypeDVBT;
break;
}
case DescriptorID::satellite_delivery_system:
{
const SatelliteDeliverySystemDescriptor cd(desc);
frequency = cd.FrequencyHz()/1000;
tt = DTVTunerType::kTunerTypeDVBS1;
break;
}
case DescriptorID::cable_delivery_system:
{
const CableDeliverySystemDescriptor cd(desc);
frequency = cd.FrequencyHz();
tt = DTVTunerType::kTunerTypeDVBC;
break;
}
default:
LOG(VB_CHANSCAN, LOG_ERR, LOC +
"unknown delivery system descriptor");
continue;
}
mplexid = ChannelUtil::GetMplexID(m_sourceID, frequency, tsid, netid);
mplexid = max(0, mplexid);
tt = GuessDTVTunerType(tt);
DTVMultiplex tuning;
if (mplexid)
{
if (!tuning.FillFromDB(tt, mplexid))
continue;
}
else if (!tuning.FillFromDeliverySystemDesc(tt, desc))
{
continue;
}
m_extendTransports[id] = tuning;
break;
}
}
}
bool ChannelScanSM::UpdateChannelInfo(bool wait_until_complete)
{
QMutexLocker locker(&m_mutex);
if (m_current == m_scanTransports.end())
return true;
if (wait_until_complete && !m_waitingForTables)
return true;
if (wait_until_complete && m_currentTestingDecryption)
return false;
DTVSignalMonitor *dtv_sm = GetDTVSignalMonitor();
if (!dtv_sm)
return false;
const ScanStreamData *sd = dtv_sm->GetScanStreamData();
if (!m_currentInfo)
m_currentInfo = new ScannedChannelInfo();
bool transport_tune_complete = true;
// MPEG
// Grab PAT tables
pat_vec_t pattmp = sd->GetCachedPATs();
QMap<uint,bool> tsid_checked;
for (size_t i = 0; i < pattmp.size(); ++i)
{
uint tsid = pattmp[i]->TransportStreamID();
if (tsid_checked[tsid])
continue;
tsid_checked[tsid] = true;
if (m_currentInfo->m_pats.contains(tsid))
continue;
if (!wait_until_complete || sd->HasCachedAllPAT(tsid))
{
m_currentInfo->m_pats[tsid] = sd->GetCachedPATs(tsid);
if (!m_currentInfo->m_pmts.empty())
{
sd->ReturnCachedPMTTables(m_currentInfo->m_pmts);
m_currentInfo->m_pmts.clear();
}
}
else
transport_tune_complete = false;
}
transport_tune_complete &= !pattmp.empty();
sd->ReturnCachedPATTables(pattmp);
// Grab PMT tables
if ((!wait_until_complete || sd->HasCachedAllPMTs()) &&
m_currentInfo->m_pmts.empty())
m_currentInfo->m_pmts = sd->GetCachedPMTs();
// ATSC
if (!m_currentInfo->m_mgt && sd->HasCachedMGT())
m_currentInfo->m_mgt = sd->GetCachedMGT();
if ((!wait_until_complete || sd->HasCachedAllCVCTs()) &&
m_currentInfo->m_cvcts.empty())
{
m_currentInfo->m_cvcts = sd->GetCachedCVCTs();
}
if ((!wait_until_complete || sd->HasCachedAllTVCTs()) &&
m_currentInfo->m_tvcts.empty())
{
m_currentInfo->m_tvcts = sd->GetCachedTVCTs();
}
// DVB
if ((!wait_until_complete || sd->HasCachedAllNIT()) &&
(m_currentInfo->m_nits.empty() ||
m_timer.elapsed() > (int)m_otherTableTime))
{
m_currentInfo->m_nits = sd->GetCachedNIT();
}
sdt_vec_t sdttmp = sd->GetCachedSDTs();
tsid_checked.clear();
for (size_t i = 0; i < sdttmp.size(); ++i)
{
uint tsid = sdttmp[i]->TSID();
if (tsid_checked[tsid])
continue;
tsid_checked[tsid] = true;
if (m_currentInfo->m_sdts.contains(tsid))
continue;
if (!wait_until_complete || sd->HasCachedAllSDT(tsid))
m_currentInfo->m_sdts[tsid] = sd->GetCachedSDTSections(tsid);
}
sd->ReturnCachedSDTTables(sdttmp);
if ((!wait_until_complete || sd->HasCachedAllBATs()) &&
(m_currentInfo->m_bats.empty() ||
m_timer.elapsed() > (int)m_otherTableTime))
{
m_currentInfo->m_bats = sd->GetCachedBATs();
}
// Check if transport tuning is complete
if (transport_tune_complete)
{
transport_tune_complete &= !m_currentInfo->m_pmts.empty();
if (sd->HasCachedMGT() || sd->HasCachedAnyVCTs())
{
transport_tune_complete &= sd->HasCachedMGT();
transport_tune_complete &=
(!m_currentInfo->m_tvcts.empty() || !m_currentInfo->m_cvcts.empty());
}
if (sd->HasCachedAnyNIT() || sd->HasCachedAnySDTs())
{
transport_tune_complete &= !m_currentInfo->m_nits.empty();
transport_tune_complete &= !m_currentInfo->m_sdts.empty();
}
if (sd->HasCachedAnyBATs())
{
transport_tune_complete &= !m_currentInfo->m_bats.empty();
}
if (transport_tune_complete)
{
uint tsid = dtv_sm->GetTransportID();
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("transport_tune_complete: ") +
QString("\n\t\t\tsd->HasCachedAnyNIT(): %1").arg(sd->HasCachedAnyNIT()) +
QString("\n\t\t\tsd->HasCachedAnySDTs(): %1").arg(sd->HasCachedAnySDTs()) +
QString("\n\t\t\tsd->HasCachedAnyBATs(): %1").arg(sd->HasCachedAnyBATs()) +
QString("\n\t\t\tsd->HasCachedAllPMTs(): %1").arg(sd->HasCachedAllPMTs()) +
QString("\n\t\t\tsd->HasCachedAllNIT(): %1").arg(sd->HasCachedAllNIT()) +
QString("\n\t\t\tsd->HasCachedAllSDT(%1): %2").arg(tsid,5).arg(sd->HasCachedAllSDT(tsid)) +
QString("\n\t\t\tsd->HasCachedAllBATs(): %1").arg(sd->HasCachedAllBATs()) +
QString("\n\t\t\tcurrentInfo->m_pmts.empty(): %1").arg(m_currentInfo->m_pmts.empty()) +
QString("\n\t\t\tcurrentInfo->m_nits.empty(): %1").arg(m_currentInfo->m_nits.empty()) +
QString("\n\t\t\tcurrentInfo->m_sdts.empty(): %1").arg(m_currentInfo->m_sdts.empty()) +
QString("\n\t\t\tcurrentInfo->m_bats.empty(): %1").arg(m_currentInfo->m_bats.empty()));
}
}
if (!wait_until_complete)
transport_tune_complete = true;
if (transport_tune_complete)
{
LOG(VB_CHANSCAN, LOG_INFO, LOC +
QString("transport_tune_complete: wait_until_complete %1")
.arg(wait_until_complete));
}
if (transport_tune_complete &&
/*!ignoreEncryptedServices &&*/ !m_currentEncryptionStatus.empty())
{
//GetDTVSignalMonitor()->GetStreamData()->StopTestingDecryption();
if (TestNextProgramEncryption())
return false;
QMap<uint, uint>::const_iterator it = m_currentEncryptionStatus.begin();
for (; it != m_currentEncryptionStatus.end(); ++it)
{
m_currentInfo->m_program_encryption_status[it.key()] = *it;
if (m_testDecryption)
{
QString msg_tr1 = QObject::tr("Program %1").arg(it.key());
QString msg_tr2 = QObject::tr("Unknown decryption status");
if (kEncEncrypted == *it)
msg_tr2 = QObject::tr("Encrypted");
else if (kEncDecrypted == *it)
msg_tr2 = QObject::tr("Decrypted");
QString msg_tr =QString("%1, %2").arg(msg_tr1).arg(msg_tr2);
m_scanMonitor->ScanAppendTextToLog(msg_tr);
}
QString msg = QString("Program %1").arg(it.key());
if (kEncEncrypted == *it)
msg = msg + " -- Encrypted";
else if (kEncDecrypted == *it)
msg = msg + " -- Decrypted";
else if (kEncUnknown == *it)
msg = msg + " -- Unknown decryption status";