/
epgcache.cpp
3504 lines (3229 loc) · 103 KB
/
epgcache.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
#include <lib/dvb/epgcache.h>
#undef EPG_DEBUG
#include <lib/service/event.h>
#include <fcntl.h>
#include <fstream>
#include <regex>
#include <sys/vfs.h> // for statfs
#include <lib/base/encoding.h>
#include <lib/base/estring.h>
#include <lib/dvb/db.h>
#include <lib/dvb/dvb.h>
#include <lib/dvb/epgchanneldata.h>
#include <lib/dvb/epgtransponderdatareader.h>
#include <lib/dvb/lowlevel/eit.h>
#include <lib/base/nconfig.h>
#include <dvbsi++/content_identifier_descriptor.h>
#include <dvbsi++/descriptor_tag.h>
#include <unordered_set>
/* Interval between "garbage collect" cycles */
#define CLEAN_INTERVAL (60 * 1000) // 1 minute
struct DescriptorPair
{
int reference_count;
__u8* data;
DescriptorPair() {}
DescriptorPair(int c, __u8* d): reference_count(c), data(d) {}
};
typedef std::tr1::unordered_map<uint32_t, DescriptorPair> DescriptorMap;
struct eventData
{
uint8_t rawEITdata[10];
uint8_t n_crc;
uint16_t type;
uint32_t *crc_list;
static DescriptorMap descriptors;
static uint8_t data[];
static unsigned int CacheSize;
static bool isCacheCorrupt;
eventData(const eit_event_struct* e = NULL, int size = 0, int type = 0, int tsidonid = 0);
~eventData();
static void load(FILE *);
static void save(FILE *);
static void cacheCorrupt(const char* context);
const eit_event_struct* get() const;
int getEventID() const
{
return (rawEITdata[0] << 8) | rawEITdata[1];
}
time_t getStartTime() const
{
return parseDVBtime(&rawEITdata[2]);
}
int getDuration() const
{
return fromBCD(rawEITdata[7])*3600+fromBCD(rawEITdata[8])*60+fromBCD(rawEITdata[9]);
}
};
unsigned int eventData::CacheSize = 0;
bool eventData::isCacheCorrupt = 0;
DescriptorMap eventData::descriptors;
uint8_t eventData::data[2 * 4096 + 12];
extern const uint32_t crc32_table[256];
const eServiceReference &handleGroup(const eServiceReference &ref)
{
if (ref.flags & eServiceReference::isGroup)
{
ePtr<eDVBResourceManager> res;
if (!eDVBResourceManager::getInstance(res))
{
ePtr<iDVBChannelList> db;
if (!res->getChannelList(db))
{
eBouquet *bouquet = NULL;
if (!db->getBouquet(ref, bouquet))
{
std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
if (it != bouquet->m_services.end())
return *it;
}
}
}
}
return ref;
}
static uint32_t calculate_crc_hash(const uint8_t *data, int size)
{
uint32_t crc = 0;
for (int i = 0; i < size; ++i)
crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[i]) & 0xFF];
return crc;
}
eventData::eventData(const eit_event_struct* e, int size, int _type, int tsidonid)
:n_crc(0), type(_type & 0xFFFF), crc_list(NULL)
{
if (!e)
return; /* Used when loading from file */
uint32_t descr[65];
uint32_t *pdescr=descr;
uint8_t *data = (uint8_t*)e;
int ptr=12;
size -= 12;
while(size > 1)
{
uint8_t *descr = data + ptr;
int descr_len = descr[1];
descr_len += 2;
if (size >= descr_len)
{
switch (descr[0])
{
case EXTENDED_EVENT_DESCRIPTOR:
case LINKAGE_DESCRIPTOR:
case COMPONENT_DESCRIPTOR:
case CONTENT_DESCRIPTOR:
case CONTENT_IDENTIFIER_DESCRIPTOR:
case PARENTAL_RATING_DESCRIPTOR:
case PDC_DESCRIPTOR:
{
uint32_t crc = calculate_crc_hash(descr, descr_len);
DescriptorMap::iterator it = descriptors.find(crc);
if ( it == descriptors.end() )
{
CacheSize+=descr_len;
uint8_t *d = new uint8_t[descr_len];
memcpy(d, descr, descr_len);
descriptors[crc] = DescriptorPair(1, d);
}
else
++it->second.reference_count;
*pdescr++ = crc;
break;
}
case SHORT_EVENT_DESCRIPTOR:
{
//parse the data out from the short event descriptor
//get the country code, which will be used for converting to UTF8
std::string cc( (const char*)&descr[2], 3);
std::transform(cc.begin(), cc.end(), cc.begin(), tolower);
int table = encodingHandler.getCountryCodeDefaultMapping(cc);
int eventNameLen = descr[5];
int eventTextLen = descr[6 + eventNameLen];
//convert our strings to UTF8
std::string eventNameUTF8 = convertDVBUTF8((const unsigned char*)&descr[6], eventNameLen, table, tsidonid);
std::string text((const char*)&descr[7 + eventNameLen], eventTextLen);
unsigned int eventNameUTF8len = eventNameUTF8.length();
//Rebuild the short event descriptor with UTF-8 strings
//Save the title first
if( eventNameUTF8len > 0 ) //only store the data if there is something to store
{
/*this will actually cause us to save some memory
previously some descriptors didnt match because there text was different and titles the same.
Now that we store them seperatly we can save some space on title data some rough calculation show anywhere from 20 - 40% savings
*/
eventNameUTF8len = truncateUTF8(eventNameUTF8, 255 - 6);
int title_len = 6 + eventNameUTF8len;
uint8_t *title_data = new uint8_t[title_len + 2];
title_data[0] = SHORT_EVENT_DESCRIPTOR;
title_data[1] = title_len;
title_data[2] = descr[2];
title_data[3] = descr[3];
title_data[4] = descr[4];
title_data[5] = eventNameUTF8len + 1;
title_data[6] = 0x15; //identify event name as UTF-8
memcpy(&title_data[7], eventNameUTF8.data(), eventNameUTF8len);
title_data[7 + eventNameUTF8len] = 0;
//Calculate the CRC, based on our new data
title_len += 2; //add 2 the length to include the 2 bytes in the header
uint32_t title_crc = calculate_crc_hash(title_data, title_len);
DescriptorMap::iterator it = descriptors.find(title_crc);
if ( it == descriptors.end() )
{
CacheSize += title_len;
descriptors[title_crc] = DescriptorPair(1, title_data);
}
else
{
++it->second.reference_count;
delete [] title_data;
}
*pdescr++ = title_crc;
}
//save the text with original encoding
if( eventTextLen > 0 ) //only store the data if there is something to store
{
int text_len = 6 + eventTextLen;
uint8_t *text_data = new uint8_t[text_len + 2];
text_data[0] = SHORT_EVENT_DESCRIPTOR;
text_data[1] = text_len;
text_data[2] = descr[2];
text_data[3] = descr[3];
text_data[4] = descr[4];
text_data[5] = 0;
text_data[6] = eventTextLen;
memcpy(&text_data[7], text.data(), eventTextLen);
text_len += 2; //add 2 the length to include the 2 bytes in the header
uint32_t text_crc = calculate_crc_hash(text_data, text_len);
DescriptorMap::iterator it = descriptors.find(text_crc);
if ( it == descriptors.end() )
{
CacheSize += text_len;
descriptors[text_crc] = DescriptorPair(1, text_data);
}
else
{
++it->second.reference_count;
delete [] text_data;
}
*pdescr++ = text_crc;
}
break;
}
default: // do not cache all other descriptors
break;
}
ptr += descr_len;
size -= descr_len;
}
else
break;
}
memcpy(rawEITdata, (uint8_t*)e, 10);
ASSERT(pdescr <= &descr[65]);
n_crc = pdescr - descr;
if (n_crc)
{
crc_list = new uint32_t[n_crc];
memcpy(crc_list, descr, n_crc * sizeof(uint32_t));
}
CacheSize += sizeof(*this) + n_crc * sizeof(uint32_t);
}
const eit_event_struct* eventData::get() const
{
unsigned int pos = 12;
memcpy(data, rawEITdata, 10);
unsigned int descriptors_length = 0;
for (uint8_t i = 0; i < n_crc; ++i)
{
DescriptorMap::iterator it = descriptors.find(crc_list[i]);
if (it != descriptors.end())
{
unsigned int b = it->second.data[1] + 2;
if (pos + b < sizeof(data))
{
memcpy(data + pos, it->second.data, b);
pos += b;
descriptors_length += b;
}
}
else
cacheCorrupt("eventData::get");
}
data[10] = (descriptors_length >> 8) & 0x0F;
data[11] = descriptors_length & 0xFF;
return (eit_event_struct*)data;
}
eventData::~eventData()
{
for ( uint8_t i = 0; i < n_crc; ++i )
{
DescriptorMap::iterator it = descriptors.find(crc_list[i]);
if ( it != descriptors.end() )
{
DescriptorPair &p = it->second;
if (p.reference_count == 0)
{
eDebug("[eEPGCache] Eventdata reference count is already zero!");
}
if (!--p.reference_count) // no more used descriptor
{
CacheSize -= it->second.data[1];
delete [] it->second.data; // free descriptor memory
descriptors.erase(it); // remove entry from descriptor map
}
}
else
{
cacheCorrupt("eventData::~eventData");
}
}
delete [] crc_list;
CacheSize -= sizeof(*this) + n_crc * sizeof(uint32_t);
}
void eventData::load(FILE *f)
{
int size = 0;
int id=0;
DescriptorPair p;
uint8_t header[2];
size_t ret; /* dummy value to store fread return values */
ret = fread(&size, sizeof(int), 1, f);
descriptors.rehash(size);
while(size)
{
ret = fread(&id, sizeof(uint32_t), 1, f);
ret = fread(&p.reference_count, sizeof(int), 1, f);
ret = fread(header, 2, 1, f);
int bytes = header[1]+2;
p.data = new uint8_t[bytes];
p.data[0] = header[0];
p.data[1] = header[1];
ret = fread(p.data+2, bytes-2, 1, f);
// make sure we are not leaking memory
DescriptorMap::iterator it = descriptors.find(id);
if (it != descriptors.end())
{
delete [] it->second.data; // free descriptor memory
}
descriptors[id] = p;
--size;
}
(void)ret;
}
void eventData::save(FILE *f)
{
if (isCacheCorrupt)
return;
int size=descriptors.size();
DescriptorMap::iterator it(descriptors.begin());
fwrite(&size, sizeof(int), 1, f);
while(size)
{
fwrite(&it->first, sizeof(uint32_t), 1, f);
fwrite(&it->second.reference_count, sizeof(int), 1, f);
fwrite(it->second.data, it->second.data[1]+2, 1, f);
++it;
--size;
}
}
void eventData::cacheCorrupt(const char* context)
{
eDebug("[eventData] EPG Cache is corrupt (%s), you should restart Enigma!", context);
if (!isCacheCorrupt)
{
isCacheCorrupt = true;
if (!eEPGCache::instance->m_filename.empty())
unlink(eEPGCache::instance->m_filename.c_str()); // Remove corrupt EPG data
}
}
eEPGCache* eEPGCache::instance;
static pthread_mutex_t cache_lock =
PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
DEFINE_REF(eEPGCache)
eEPGCache::eEPGCache()
:messages(this,1,"eEPGCache"), m_running(false), m_enabledEpgSources(0), cleanTimer(eTimer::create(this)), m_debug(false), m_timeQueryRef(nullptr)
{
eDebug("[eEPGCache] Initialized EPGCache (wait for setCacheFile call now)");
load_epg = eConfigManager::getConfigValue("config.usage.remote_fallback_import").find("epg") == std::string::npos;
historySeconds = 0;
maxdays = 7;
CONNECT(messages.recv_msg, eEPGCache::gotMessage);
CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
CONNECT(cleanTimer->timeout, eEPGCache::cleanLoop);
std::ifstream onid_file;
onid_file.open("/etc/enigma2/blacklist.onid");
int tmp_onid;
while (onid_file >> std::hex >>tmp_onid)
onid_blacklist.insert(onid_blacklist.end(),1,tmp_onid);
onid_file.close();
m_debug = eConfigManager::getConfigBoolValue("config.crash.debugEPG");
instance = this;
}
void eEPGCache::setCacheFile(const char *path)
{
bool inited = !m_filename.empty();
m_filename = path;
if (!inited)
{
eDebug("[eEPGCache] setCacheFile read/write epg data from/to '%s'", m_filename.c_str());
if (eDVBLocalTimeHandler::getInstance()->ready())
timeUpdated();
}
}
void eEPGCache::timeUpdated()
{
if (!m_filename.empty())
{
if (!m_running)
{
eDebug("[eEPGCache] time updated.. start EPG Mainloop");
run();
m_running = true;
} else
messages.send(Message(Message::timeChanged));
}
else
eDebug("[eEPGCache] time updated.. but cache file not set yet.. dont start epg!!");
}
/**
* @brief Parse EIT section data and update the EPG cache timeMap and eventMap
*
* @param data EIT section data
* @param source The type of EIT source
* @param channel The channel for which the EPG is being updated
* @return void
*/
void eEPGCache::sectionRead(const uint8_t *data, int source, eEPGChannelData *channel)
{
const eit_t *eit = (const eit_t*) data;
int len = eit->getSectionLength() - 1;
int ptr = EIT_SIZE;
if ( ptr >= len )
return;
#if 0
/*
* disable for now, as this hack breaks EIT parsing for
* services with a low segment_last_table_id
*
* Multichoice should be the exception, not the rule...
*/
// This fixed the EPG on the Multichoice irdeto systems
// the EIT packet is non-compliant.. their EIT packet stinks
if ( data[ptr-1] < 0x40 )
--ptr;
#endif
int onid = eit->getOriginalNetworkId();
int tsid = eit->getTransportStreamId();
// Cablecom HACK .. tsid / onid in eit data are incorrect.. so we use
// it from running channel (just for current transport stream eit data)
/*
* Make an exception for BEV (onid 0x100, 0x101), which doesn't use
* SCHEDULE_OTHER. As a result SCHEDULE will contain data for different tsid's,
* so we should not replace it with the current tsid.
*/
bool use_transponder_chid = onid != 0x101 && onid != 0x100 && (source == SCHEDULE || (source == NOWNEXT && data[0] == 0x4E));
if (use_transponder_chid && channel)
{
eDVBChannelID chid = channel->channel->getChannelID();
onid = chid.original_network_id.get();
tsid = chid.transport_stream_id.get();
}
uniqueEPGKey service( eit->getServiceID(), onid, tsid);
eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
int eit_event_size;
int duration;
time_t start_time = parseDVBtime((const uint8_t*)eit_event + 2);
time_t now = ::time(0) - historySeconds;
// Set a flag in the channel to signify that the source is available
if ( start_time != 3599 && start_time > -1 && channel)
channel->haveData |= source;
singleLock s(cache_lock);
// here an eventMap is always given back to results .. either an existing one or one generated by []
EventCacheItem &servicemap = eventDB[service];
eventMap &eventmap = servicemap.byEvent;
timeMap &timemap = servicemap.byTime;
if (!(source & EPG_IMPORT) && (servicemap.sources & EPG_IMPORT))
return;
else if ((source & EPG_IMPORT) && !(servicemap.sources & EPG_IMPORT))
{
if (!eventmap.empty() || !timemap.empty())
{
flushEPG(service);
servicemap = eventDB[service];
eventmap = servicemap.byEvent;
timemap = servicemap.byTime;
}
servicemap.sources = source;
}
else
servicemap.sources |= source;
while (ptr<len)
{
uint16_t event_hash;
eit_event_size = eit_event->getDescriptorsLoopLength()+EIT_LOOP_SIZE;
duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
start_time = parseDVBtime((const uint8_t*)eit_event + 2, &event_hash);
std::vector<int>::iterator m_it=find(onid_blacklist.begin(),onid_blacklist.end(),onid);
if (m_it != onid_blacklist.end())
goto next;
if ((start_time != 3599) && // NVOD Service
(start_time < (now+maxdays*24*60*60)) && // maxdays for EPG - no more than maxdays in future
((onid != 1714) || (duration != (24*3600-1)))) // PlatformaHD invalid event
{
uint16_t event_id = eit_event->getEventId();
if (event_id == 0) {
// hack for some polsat services on 13.0E..... but this also replaces other valid event_ids with value 0..
// but we dont care about it...
event_id = event_hash;
eit_event->event_id_hi = event_hash >> 8;
eit_event->event_id_lo = event_hash & 0xFF;
}
eventData *new_evt = new eventData(eit_event, eit_event_size, source, (tsid<<16)|onid);
time_t new_start = new_evt->getStartTime();
time_t new_end = new_start + new_evt->getDuration();
// Ignore zero-length events
if (new_start == new_end)
{
delete new_evt;
goto next;
}
// if(m_debug)
// eDebug("[eEPGCache] created event %04x at %ld", new_evt->getEventID(), new_start);
// Remove existing event if the id matches
eventMap::iterator ev_it = eventmap.find(event_id);
if (ev_it != eventmap.end())
{
if ((source & ~EPG_IMPORT) > (ev_it->second->type & ~EPG_IMPORT))
{
if(m_debug)
eDebug("[eEPGCache] event %04x skip update: source=0x%x > type=0x%x", event_id, source, ev_it->second->type);
delete new_evt;
goto next;
}
if(m_debug)
eDebug("[eEPGCache] removing event %04x at %ld", ev_it->second->getEventID(), ev_it->second->getStartTime());
// Remove existing event
if (timemap.erase(ev_it->second->getStartTime()) == 0)
{
eDebug("[eEPGCache] Event %04x not found in timeMap at %ld", event_id, ev_it->second->getStartTime());
}
eventData *data = ev_it->second;
eventmap.erase(ev_it);
delete data;
}
timeMap::iterator it;
if (timemap.empty())
it = timemap.begin();
else
{
it = timemap.lower_bound(new_start);
if(it == timemap.end() || it != timemap.begin())
{
--it;
}
}
while (it != timemap.end())
{
time_t old_start = it->second->getStartTime();
time_t old_end = old_start + it->second->getDuration();
// if(m_debug)
// eDebug("[eEPGCache] checking against event %04x at %ld", it->second->getEventID(), it->second->getStartTime());
if ((old_start < new_end) && (old_end > new_start))
{
if(m_debug) {
eDebug("[eEPGCache] removing old overlapping event %04x\n"
" old %ld ~ %ld\n"
" new %ld ~ %ld",
it->second->getEventID(), old_start, old_end, new_start, new_end);
}
if (eventmap.erase(it->second->getEventID()) == 0)
{
eDebug("[eEPGCache] Event %04x not found in eventMap at %ld", it->second->getEventID(), it->second->getStartTime());
}
delete it->second;
timemap.erase(it++);
}
else
{
++it;
}
if (old_start > new_end)
break;
}
if(m_debug)
eDebug("[eEPGCache] Inserting event %04x at %ld", event_id, new_start);
eventmap[event_id] = new_evt;
timemap[new_start] = new_evt;
}
next:
#ifdef EPG_DEBUG
if (eventmap.size() != timemap.size())
{
eDebug("[eEPGCache] svc(%04x:%04x:%04x) eventmap.size(%d) != timemap.size(%d)",
service.onid, service.tsid, service.sid, eventmap.size(), timemap.size());
{
CFile f("/hdd/event_map.txt", "w+");
int i = 0;
for (eventMap::iterator it(eventmap.begin()); it != eventmap.end(); ++it)
{
fprintf(f, "%d(key %d) -> time %ld, event_id %d, data %p\n",
i++, (int)it->first, (long)it->second->getStartTime(), (int)it->second->getEventID(), it->second);
}
}
{
CFile f("/hdd/time_map.txt", "w+");
int i = 0;
for (timeMap::iterator it(timemap.begin()); it != timemap.end(); ++it)
{
fprintf(f, "%d(key %d) -> time %ld, event_id %d, data %p\n",
i++, (int)it->first, (long)it->second->getStartTime(), (int)it->second->getEventID(), it->second);
}
}
eFatal("[eEPGCache] /hdd/event_map.txt and /hdd/time_map.txt generated for debugging purposes");
}
#endif
ptr += eit_event_size;
eit_event = (eit_event_struct*)(((uint8_t*)eit_event) + eit_event_size);
}
}
void eEPGCache::flushEPG(int sid, int onid, int tsid)
{
flushEPG(uniqueEPGKey(sid, onid, tsid));
}
// epg cache needs to be locked(cache_lock) before calling the procedure
void eEPGCache::clearCompleteEPGCache()
{
// cache_lock needs to be set in calling procedure!
for (eventCache::iterator it(eventDB.begin()); it != eventDB.end(); ++it)
{
eventMap &evMap = it->second.byEvent;
timeMap &tmMap = it->second.byTime;
for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
delete i->second;
evMap.clear();
tmMap.clear();
}
eventDB.clear();
#ifdef ENABLE_PRIVATE_EPG
content_time_tables.clear();
#endif
eEPGTransponderDataReader::getInstance()->restartReader();
}
void eEPGCache::flushEPG(const uniqueEPGKey & s, bool lock) // lock only affects complete flush
{
eDebug("[eEPGCache] flushEPG %d", (int)(bool)s);
if (s) // clear only this service
{
singleLock l(cache_lock); // TODO : Probably double lock ( Sonar : This lock has already been acquired elock.h line 13)
eDebug("[eEPGCache] flushEPG svc(%04x:%04x:%04x)", s.onid, s.tsid, s.sid);
eventCache::iterator it = eventDB.find(s);
if (it != eventDB.end())
{
eventMap &eventmap = it->second.byEvent;
timeMap &timemap = it->second.byTime;
for (eventMap::iterator i = eventmap.begin(); i != eventmap.end(); ++i)
delete i->second;
eventmap.clear();
timemap.clear();
eventDB.erase(it);
#ifdef ENABLE_PRIVATE_EPG
contentMaps::iterator it = content_time_tables.find(s);
if (it != content_time_tables.end())
{
it->second.clear();
content_time_tables.erase(it);
}
#endif
// remove this service's channel from lastupdated map
{
singleLock l(eEPGTransponderDataReader::last_channel_update_lock);
for (updateMap::iterator it = eEPGTransponderDataReader::getInstance()->m_channelLastUpdated.begin(); it != eEPGTransponderDataReader::getInstance()->m_channelLastUpdated.end(); )
{
const eDVBChannelID &chid = it->first;
if(chid.original_network_id == s.onid && chid.transport_stream_id == s.tsid)
it = eEPGTransponderDataReader::getInstance()->m_channelLastUpdated.erase(it);
else
++it;
}
}
singleLock m(eEPGTransponderDataReader::known_channel_lock);
for (ChannelMap::const_iterator it(eEPGTransponderDataReader::getInstance()->m_knownChannels.begin()); it != eEPGTransponderDataReader::getInstance()->m_knownChannels.end(); ++it)
{
const eDVBChannelID chid = it->second->channel->getChannelID();
if(chid.original_network_id == s.onid && chid.transport_stream_id == s.tsid)
{
it->second->abortEPG();
it->second->startChannel();
}
}
}
}
else // clear complete EPG Cache
{
eDebug("[eEPGCache] flushEPG all services");
if (lock)
{
singleLock l(cache_lock);
clearCompleteEPGCache();
}
else
clearCompleteEPGCache();
}
}
/**
* @brief Remove old events from the cache. An event is considered old
* if it's end time is earlier than @p eEPGCache::historySeconds ago.
*
* @return void
*/
void eEPGCache::cleanLoop()
{
{ /* scope for cache lock */
time_t now = ::time(0) - historySeconds;
singleLock s(cache_lock);
for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
{
EventCacheItem &servicemap = DBIt->second;
eventMap &eventmap = servicemap.byEvent;
timeMap &timemap = servicemap.byTime;
bool updated = false;
for (timeMap::iterator It = timemap.begin(); It != timemap.end() && It->second->getStartTime() < now;)
{
time_t start_time = It->second->getStartTime();
time_t end_time = start_time + It->second->getDuration();
if (end_time < now)
{
if(m_debug) {
eDebug("[eEPGCache] cleanLoop: svc(%04x:%04x:%04x) delete old event %04x at time %ld",
DBIt->first.onid, DBIt->first.tsid, DBIt->first.sid,
It->second->getEventID(), (long)start_time);
}
if (eventmap.erase(It->second->getEventID()) == 0)
{
eDebug("[eEPGCache] Event %04x not found in timeMap at %ld", It->second->getEventID(), start_time);
}
delete It->second;
timemap.erase(It++);
updated = true;
}
else
++It;
}
#ifdef ENABLE_PRIVATE_EPG
if ( updated )
{
contentMaps::iterator x = content_time_tables.find(DBIt->first);
if (x != content_time_tables.end())
{
for (contentMap::iterator i = x->second.begin(); i != x->second.end(); )
{
for (contentTimeMap::iterator it(i->second.begin());
it != i->second.end(); )
{
if (timemap.find(it->second.first) == timemap.end())
i->second.erase(it++);
else
++it;
}
if ( i->second.size() )
++i;
else
x->second.erase(i++);
}
}
}
#endif
}
} /* release lock */
cleanTimer->start(CLEAN_INTERVAL,true);
}
eEPGCache::~eEPGCache()
{
m_running = false;
messages.send(Message::quit);
kill(); // waiting for thread shutdown
singleLock s(cache_lock);
for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
for (eventMap::iterator It = evIt->second.byEvent.begin(); It != evIt->second.byEvent.end(); It++)
delete It->second;
}
void eEPGCache::gotMessage( const Message &msg )
{
switch (msg.type)
{
case Message::flush:
flushEPG(msg.service);
break;
case Message::quit:
quit(0);
break;
case Message::timeChanged:
cleanLoop();
break;
default:
eDebug("[eEPGCache] unhandled EPGCache Message!!");
break;
}
}
void eEPGCache::thread()
{
hasStarted();
if (nice(4) == -1)
{
eDebug("[eEPGCache] thread failed to modify scheduling priority (%m)");
}
if (load_epg) { load(); }
/*emit*/ epgCacheStarted();
cleanLoop();
runLoop();
save();
}
static const char* EPGDAT_IN_FLASH = "/epg.dat";
void eEPGCache::clear()
{
flushEPG();
}
const static unsigned int EPG_MAGIC = 0x98765432;
void eEPGCache::load()
{
if(m_debug)
eDebug("[eEPGCache] load()");
if (m_filename.empty())
m_filename = "/hdd/epg.dat";
std::vector<char> vEPGDAT(m_filename.begin(), m_filename.end());
vEPGDAT.push_back('\0');
const char* EPGDAT = &vEPGDAT[0];
std::string filenamex = m_filename + ".loading";
std::vector<char> vEPGDATX(filenamex.begin(), filenamex.end());
vEPGDATX.push_back('\0');
const char* EPGDATX = &vEPGDATX[0];
FILE *f = fopen(EPGDAT, "rb");
int renameResult;
size_t ret; /* dummy value to store fread return values */
if (f == NULL)
{
/* No EPG on harddisk, so try internal flash */
eDebug("[eEPGCache] %s not found, try %s", EPGDAT, EPGDAT_IN_FLASH);
EPGDAT = EPGDAT_IN_FLASH;
f = fopen(EPGDAT, "rb");
if (f == NULL)
{
eDebug("[eEPGCache] %s not found, giving up", EPGDAT);
return;
}
renameResult = -1;
}
else
{
unlink(EPGDATX);
renameResult = rename(EPGDAT, EPGDATX);
if (renameResult) eDebug("[eEPGCache] failed to rename %s to %s: %m", EPGDAT, EPGDATX);
}
{
int size=0;
int cnt=0;
unsigned int magic=0;
unlink(EPGDAT_IN_FLASH);/* Don't keep it around when in flash */
ret = fread( &magic, sizeof(int), 1, f);
if (magic != EPG_MAGIC)
{
eDebug("[eEPGCache] epg file load failed magic test expected 0x%08x, got 0x%08x (%m)", EPG_MAGIC, magic);
fclose(f);
return;
}
char text1[13];
ret = fread( text1, 13, 1, f);
if ( !memcmp( text1, "ENIGMA_EPG_V8", 13) )
{
singleLock s(cache_lock);
if (eventDB.size() > 0)
{
clearCompleteEPGCache();
}
std::unordered_set<uniqueEPGKey, hash_uniqueEPGKey > overlaps;
ret = fread( &size, sizeof(int), 1, f);
eventDB.rehash(size); /* Reserve buckets in advance */
while(size--)
{
uniqueEPGKey key;
int size=0;
ret = fread( &key, sizeof(uniqueEPGKey), 1, f);
ret = fread( &size, sizeof(int), 1, f);
EventCacheItem& item = eventDB[key]; /* Constructs new entry */
bool overlap = false; // Actually overlaps, zero-length event or not time ordered
time_t last_end = 0;
if (!item.byTime.empty())
{
timeMap::iterator last_entry = item.byTime.end();
--last_entry;
last_end = last_entry->second->getStartTime() + last_entry->second->getDuration();
}
while(size--)
{
uint8_t len=0;
uint16_t type=0;
eventData *event=0;
ret = fread( &type, sizeof(uint16_t), 1, f);
ret = fread( &len, sizeof(uint8_t), 1, f);
event = new eventData(0, len, type);
event->n_crc = (len-10) / sizeof(uint32_t);
ret = fread( event->rawEITdata, 10, 1, f);
if (event->n_crc)
{
event->crc_list = new uint32_t[event->n_crc];
ret = fread( event->crc_list, sizeof(uint32_t), event->n_crc, f);
}
eventData::CacheSize += sizeof(eventData) + event->n_crc * sizeof(uint32_t);
item.byEvent[event->getEventID()] = event;
item.byTime[event->getStartTime()] = event;
time_t this_start = event->getStartTime();
time_t this_end = this_start + event->getDuration();
if (this_start < last_end || this_start == this_end)
overlap = true;
else
last_end = this_end;
++cnt;
}
if (overlap)
overlaps.insert(key);
}
eventData::load(f);
eDebug("[eEPGCache] %d events read from %s", cnt, EPGDAT);
#ifdef ENABLE_PRIVATE_EPG
char text2[11];
ret = fread( text2, 11, 1, f);
if ( !memcmp( text2, "PRIVATE_EPG", 11) )
{
size=0;
ret = fread( &size, sizeof(int), 1, f);
while(size--)
{
int size=0;
uniqueEPGKey key;
ret = fread( &key, sizeof(uniqueEPGKey), 1, f);
eventMap &evMap = eventDB[key].byEvent;
ret = fread( &size, sizeof(int), 1, f);