disabled unused md5* variables
[enigma2.git] / lib / dvb / epgcache.cpp
1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
3
4 #undef EPG_DEBUG  
5
6 #include <time.h>
7 #include <unistd.h>  // for usleep
8 #include <sys/vfs.h> // for statfs
9 // #include <libmd5sum.h>
10 #include <lib/base/eerror.h>
11 #include <lib/dvb/pmt.h>
12 #include <Python.h>
13
14 int eventData::CacheSize=0;
15 descriptorMap eventData::descriptors;
16 __u8 eventData::data[4108];
17 extern const uint32_t crc32_table[256];
18
19 eventData::eventData(const eit_event_struct* e, int size, int type)
20         :ByteSize(size&0xFF), type(type&0xFF)
21 {
22         if (!e)
23                 return;
24
25         __u32 descr[65];
26         __u32 *pdescr=descr;
27
28         __u8 *data = (__u8*)e;
29         int ptr=10;
30         int descriptors_length = (data[ptr++]&0x0F) << 8;
31         descriptors_length |= data[ptr++];
32         while ( descriptors_length > 0 )
33         {
34                 __u8 *descr = data+ptr;
35                 int descr_len = descr[1]+2;
36
37                 __u32 crc = 0;
38                 int cnt=0;
39                 while(cnt++ < descr_len)
40                         crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
41
42                 descriptorMap::iterator it =
43                         descriptors.find(crc);
44                 if ( it == descriptors.end() )
45                 {
46                         CacheSize+=descr_len;
47                         __u8 *d = new __u8[descr_len];
48                         memcpy(d, descr, descr_len);
49                         descriptors[crc] = descriptorPair(1, d);
50                 }
51                 else
52                         ++it->second.first;
53
54                 *pdescr++=crc;
55                 descriptors_length -= descr_len;
56         }
57         ByteSize = 12+((pdescr-descr)*4);
58         EITdata = new __u8[ByteSize];
59         CacheSize+=ByteSize;
60         memcpy(EITdata, (__u8*) e, 12);
61         memcpy(EITdata+12, descr, ByteSize-12);
62 }
63
64 const eit_event_struct* eventData::get() const
65 {
66         int pos = 12;
67         int tmp = ByteSize-12;
68
69         memcpy(data, EITdata, 12);
70         __u32 *p = (__u32*)(EITdata+12);
71         while(tmp>0)
72         {
73                 descriptorMap::iterator it =
74                         descriptors.find(*p++);
75                 if ( it != descriptors.end() )
76                 {
77                         int b = it->second.second[1]+2;
78                         memcpy(data+pos, it->second.second, b );
79                         pos += b;
80                 }
81                 tmp-=4;
82         }
83
84         return (const eit_event_struct*)data;
85 }
86
87 eventData::~eventData()
88 {
89         if ( ByteSize )
90         {
91                 CacheSize-=ByteSize;
92                 ByteSize-=12;
93                 __u32 *d = (__u32*)(EITdata+12);
94                 while(ByteSize)
95                 {
96                         descriptorMap::iterator it =
97                                 descriptors.find(*d++);
98                         if ( it != descriptors.end() )
99                         {
100                                 descriptorPair &p = it->second;
101                                 if (!--p.first) // no more used descriptor
102                                 {
103                                         CacheSize -= it->second.second[1];
104                                         delete [] it->second.second;    // free descriptor memory
105                                         descriptors.erase(it);  // remove entry from descriptor map
106                                 }
107                         }
108                         ByteSize-=4;
109                 }
110                 delete [] EITdata;
111         }
112 }
113
114 void eventData::load(FILE *f)
115 {
116         int size=0;
117         int id=0;
118         __u8 header[2];
119         descriptorPair p;
120         fread(&size, sizeof(int), 1, f);
121         while(size)
122         {
123                 fread(&id, sizeof(__u32), 1, f);
124                 fread(&p.first, sizeof(int), 1, f);
125                 fread(header, 2, 1, f);
126                 int bytes = header[1]+2;
127                 p.second = new __u8[bytes];
128                 p.second[0] = header[0];
129                 p.second[1] = header[1];
130                 fread(p.second+2, bytes-2, 1, f);
131                 descriptors[id]=p;
132                 --size;
133                 CacheSize+=bytes;
134         }
135 }
136
137 void eventData::save(FILE *f)
138 {
139         int size=descriptors.size();
140         descriptorMap::iterator it(descriptors.begin());
141         fwrite(&size, sizeof(int), 1, f);
142         while(size)
143         {
144                 fwrite(&it->first, sizeof(__u32), 1, f);
145                 fwrite(&it->second.first, sizeof(int), 1, f);
146                 fwrite(it->second.second, it->second.second[1]+2, 1, f);
147                 ++it;
148                 --size;
149         }
150 }
151
152 eEPGCache* eEPGCache::instance;
153 pthread_mutex_t eEPGCache::cache_lock=
154         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
155 pthread_mutex_t eEPGCache::channel_map_lock=
156         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
157
158 DEFINE_REF(eEPGCache)
159
160 eEPGCache::eEPGCache()
161         :messages(this,1), cleanTimer(this)//, paused(0)
162 {
163         eDebug("[EPGC] Initialized EPGCache");
164
165         CONNECT(messages.recv_msg, eEPGCache::gotMessage);
166         CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
167         CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
168
169         ePtr<eDVBResourceManager> res_mgr;
170         eDVBResourceManager::getInstance(res_mgr);
171         if (!res_mgr)
172                 eDebug("[eEPGCache] no resource manager !!!!!!!");
173         else
174                 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
175         instance=this;
176 }
177
178 void eEPGCache::timeUpdated()
179 {
180         if ( !thread_running() )
181         {
182                 eDebug("[EPGC] time updated.. start EPG Mainloop");
183                 run();
184         }
185         else
186                 messages.send(Message(Message::timeChanged));
187 }
188
189 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
190 {
191         if ( chan )
192         {
193 //              eDebug("[eEPGCache] add channel %p", chan);
194                 channel_data *data = new channel_data(this);
195                 data->channel = chan;
196                 data->prevChannelState = -1;
197 #ifdef ENABLE_PRIVATE_EPG
198                 data->m_PrivatePid = -1;
199 #endif
200                 singleLock s(channel_map_lock);
201                 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
202                 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
203         }
204 }
205
206 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
207 {
208         singleLock s(channel_map_lock);
209         channelMapIterator it =
210                 m_knownChannels.find(chan);
211         if ( it == m_knownChannels.end() )
212                 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
213         else
214         {
215                 channel_data &data = *it->second;
216                 ePtr<eDVBResourceManager> res_mgr;
217                 if ( eDVBResourceManager::getInstance( res_mgr ) )
218                         eDebug("[eEPGCache] no res manager!!");
219                 else
220                 {
221                         ePtr<iDVBDemux> demux;
222                         if ( data.channel->getDemux(demux, 0) )
223                         {
224                                 eDebug("[eEPGCache] no demux!!");
225                                 return;
226                         }
227                         else
228                         {
229                                 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
230                                 if ( res )
231                                 {
232                                         eDebug("[eEPGCache] couldnt initialize nownext reader!!");
233                                         return;
234                                 }
235
236                                 res = demux->createSectionReader( this, data.m_ScheduleReader );
237                                 if ( res )
238                                 {
239                                         eDebug("[eEPGCache] couldnt initialize schedule reader!!");
240                                         return;
241                                 }
242
243                                 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
244                                 if ( res )
245                                 {
246                                         eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
247                                         return;
248                                 }
249 #ifdef ENABLE_PRIVATE_EPG
250                                 res = demux->createSectionReader( this, data.m_PrivateReader );
251                                 if ( res )
252                                 {
253                                         eDebug("[eEPGCache] couldnt initialize private reader!!");
254                                         return;
255                                 }
256 #endif
257                                 messages.send(Message(Message::startChannel, chan));
258                                 // -> gotMessage -> changedService
259                         }
260                 }
261         }
262 }
263
264 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
265 {
266         channelMapIterator it =
267                 m_knownChannels.find(chan);
268         if ( it != m_knownChannels.end() )
269         {
270                 int state=0;
271                 chan->getState(state);
272                 if ( it->second->prevChannelState != state )
273                 {
274                         switch (state)
275                         {
276                                 case iDVBChannel::state_ok:
277                                 {
278                                         eDebug("[eEPGCache] channel %p running", chan);
279                                         DVBChannelRunning(chan);
280                                         break;
281                                 }
282                                 case iDVBChannel::state_release:
283                                 {
284                                         eDebug("[eEPGCache] remove channel %p", chan);
285                                         messages.send(Message(Message::leaveChannel, chan));
286                                         while(!it->second->can_delete)
287                                                 usleep(1000);
288                                         delete it->second;
289                                         m_knownChannels.erase(it);
290                                         // -> gotMessage -> abortEPG
291                                         break;
292                                 }
293                                 default: // ignore all other events
294                                         return;
295                         }
296                         it->second->prevChannelState = state;
297                 }
298         }
299 }
300
301 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
302 {
303         eit_t *eit = (eit_t*) data;
304
305         int len=HILO(eit->section_length)-1;//+3-4;
306         int ptr=EIT_SIZE;
307         if ( ptr >= len )
308                 return;
309
310         // This fixed the EPG on the Multichoice irdeto systems
311         // the EIT packet is non-compliant.. their EIT packet stinks
312         if ( data[ptr-1] < 0x40 )
313                 --ptr;
314
315         uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
316         eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
317         int eit_event_size;
318         int duration;
319
320         time_t TM = parseDVBtime( eit_event->start_time_1, eit_event->start_time_2,     eit_event->start_time_3, eit_event->start_time_4, eit_event->start_time_5);
321         time_t now = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
322
323         if ( TM != 3599 && TM > -1)
324                 channel->haveData |= source;
325
326         singleLock s(cache_lock);
327         // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
328         // oder eine durch [] erzeugte
329         std::pair<eventMap,timeMap> &servicemap = eventDB[service];
330         eventMap::iterator prevEventIt = servicemap.first.end();
331         timeMap::iterator prevTimeIt = servicemap.second.end();
332
333         while (ptr<len)
334         {
335                 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
336
337                 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
338                 TM = parseDVBtime(
339                         eit_event->start_time_1,
340                         eit_event->start_time_2,
341                         eit_event->start_time_3,
342                         eit_event->start_time_4,
343                         eit_event->start_time_5);
344
345                 if ( TM == 3599 )
346                         goto next;
347
348                 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
349                         goto next;
350
351                 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ )  // old events should not be cached
352                 {
353                         __u16 event_id = HILO(eit_event->event_id);
354 //                      eDebug("event_id is %d sid is %04x", event_id, service.sid);
355
356                         eventData *evt = 0;
357                         int ev_erase_count = 0;
358                         int tm_erase_count = 0;
359
360                         // search in eventmap
361                         eventMap::iterator ev_it =
362                                 servicemap.first.find(event_id);
363
364                         // entry with this event_id is already exist ?
365                         if ( ev_it != servicemap.first.end() )
366                         {
367                                 if ( source > ev_it->second->type )  // update needed ?
368                                         goto next; // when not.. the skip this entry
369
370                                 // search this event in timemap
371                                 timeMap::iterator tm_it_tmp = 
372                                         servicemap.second.find(ev_it->second->getStartTime());
373
374                                 if ( tm_it_tmp != servicemap.second.end() )
375                                 {
376                                         if ( tm_it_tmp->first == TM ) // correct eventData
377                                         {
378                                                 // exempt memory
379                                                 delete ev_it->second;
380                                                 evt = new eventData(eit_event, eit_event_size, source);
381                                                 ev_it->second=evt;
382                                                 tm_it_tmp->second=evt;
383                                                 goto next;
384                                         }
385                                         else
386                                         {
387                                                 tm_erase_count++;
388                                                 // delete the found record from timemap
389                                                 servicemap.second.erase(tm_it_tmp);
390                                                 prevTimeIt=servicemap.second.end();
391                                         }
392                                 }
393                         }
394
395                         // search in timemap, for check of a case if new time has coincided with time of other event 
396                         // or event was is not found in eventmap
397                         timeMap::iterator tm_it =
398                                 servicemap.second.find(TM);
399
400                         if ( tm_it != servicemap.second.end() )
401                         {
402                                 // i think, if event is not found on eventmap, but found on timemap updating nevertheless demands
403 #if 0
404                                 if ( source > tm_it->second->type && tm_erase_count == 0 ) // update needed ?
405                                         goto next; // when not.. the skip this entry
406 #endif
407
408                                 // search this time in eventmap
409                                 eventMap::iterator ev_it_tmp = 
410                                         servicemap.first.find(tm_it->second->getEventID());
411
412                                 if ( ev_it_tmp != servicemap.first.end() )
413                                 {
414                                         ev_erase_count++;                               
415                                         // delete the found record from eventmap
416                                         servicemap.first.erase(ev_it_tmp);
417                                         prevEventIt=servicemap.first.end();
418                                 }
419                         }
420                         
421                         evt = new eventData(eit_event, eit_event_size, source);
422 #if EPG_DEBUG
423                         bool consistencyCheck=true;
424 #endif
425                         if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
426                         {
427                                 // exempt memory
428                                 delete ev_it->second; 
429                                 delete tm_it->second;
430                                 ev_it->second=evt;
431                                 tm_it->second=evt;
432                         }
433                         else if (ev_erase_count == 0 && tm_erase_count > 0) 
434                         {
435                                 // exempt memory
436                                 delete ev_it->second;
437                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
438                                 ev_it->second=evt;
439                         }
440                         else if (ev_erase_count > 0 && tm_erase_count == 0)
441                         {
442                                 // exempt memory
443                                 delete tm_it->second;
444                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
445                                 tm_it->second=evt;
446                         }
447                         else // added new eventData
448                         {
449 #if EPG_DEBUG
450                                 consistencyCheck=false;
451 #endif
452                                 prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
453                                 prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
454                         }
455 #if EPG_DEBUG
456                         if ( consistencyCheck )
457                         {
458                                 if ( tm_it->second != evt || ev_it->second != evt )
459                                         eFatal("tm_it->second != ev_it->second");
460                                 else if ( tm_it->second->getStartTime() != tm_it->first )
461                                         eFatal("event start_time(%d) non equal timemap key(%d)", 
462                                                 tm_it->second->getStartTime(), tm_it->first );
463                                 else if ( tm_it->first != TM )
464                                         eFatal("timemap key(%d) non equal TM(%d)", 
465                                                 tm_it->first, TM);
466                                 else if ( ev_it->second->getEventID() != ev_it->first )
467                                         eFatal("event_id (%d) non equal event_map key(%d)",
468                                                 ev_it->second->getEventID(), ev_it->first);
469                                 else if ( ev_it->first != event_id )
470                                         eFatal("eventmap key(%d) non equal event_id(%d)", 
471                                                 ev_it->first, event_id );
472                         }
473 #endif
474                 }
475 next:
476 #if EPG_DEBUG
477                 if ( servicemap.first.size() != servicemap.second.size() )
478                 {
479                         FILE *f = fopen("/hdd/event_map.txt", "w+");
480                         int i=0;
481                         for (eventMap::iterator it(servicemap.first.begin())
482                                 ; it != servicemap.first.end(); ++it )
483                                 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
484                                         i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
485                         fclose(f);
486                         f = fopen("/hdd/time_map.txt", "w+");
487                         i=0;
488                         for (timeMap::iterator it(servicemap.second.begin())
489                                 ; it != servicemap.second.end(); ++it )
490                                         fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
491                                                 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
492                         fclose(f);
493
494                         eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d", 
495                                 service.sid, service.tsid, service.onid, 
496                                 servicemap.first.size(), servicemap.second.size() );
497                 }
498 #endif
499                 ptr += eit_event_size;
500                 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
501         }
502 }
503
504 void eEPGCache::flushEPG(const uniqueEPGKey & s)
505 {
506         eDebug("[EPGC] flushEPG %d", (int)(bool)s);
507         singleLock l(cache_lock);
508         if (s)  // clear only this service
509         {
510                 eventCache::iterator it = eventDB.find(s);
511                 if ( it != eventDB.end() )
512                 {
513                         eventMap &evMap = it->second.first;
514                         timeMap &tmMap = it->second.second;
515                         tmMap.clear();
516                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
517                                 delete i->second;
518                         evMap.clear();
519                         eventDB.erase(it);
520
521                         // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
522 #ifdef ENABLE_PRIVATE_EPG
523                         contentMaps::iterator it =
524                                 content_time_tables.find(s);
525                         if ( it != content_time_tables.end() )
526                         {
527                                 it->second.clear();
528                                 content_time_tables.erase(it);
529                         }
530 #endif
531                 }
532         }
533         else // clear complete EPG Cache
534         {
535                 for (eventCache::iterator it(eventDB.begin());
536                         it != eventDB.end(); ++it)
537                 {
538                         eventMap &evMap = it->second.first;
539                         timeMap &tmMap = it->second.second;
540                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
541                                 delete i->second;
542                         evMap.clear();
543                         tmMap.clear();
544                 }
545                 eventDB.clear();
546 #ifdef ENABLE_PRIVATE_EPG
547                 content_time_tables.clear();
548 #endif
549                 channelLastUpdated.clear();
550                 singleLock m(channel_map_lock);
551                 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
552                         it->second->startEPG();
553         }
554         eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
555 }
556
557 void eEPGCache::cleanLoop()
558 {
559         singleLock s(cache_lock);
560         if (!eventDB.empty())
561         {
562                 eDebug("[EPGC] start cleanloop");
563
564                 time_t now = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
565
566                 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
567                 {
568                         bool updated = false;
569                         for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
570                         {
571                                 if ( now > (It->first+It->second->getDuration()) )  // outdated normal entry (nvod references to)
572                                 {
573                                         // remove entry from eventMap
574                                         eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
575                                         if ( b != DBIt->second.first.end() )
576                                         {
577                                                 // release Heap Memory for this entry   (new ....)
578 //                                              eDebug("[EPGC] delete old event (evmap)");
579                                                 DBIt->second.first.erase(b);
580                                         }
581
582                                         // remove entry from timeMap
583 //                                      eDebug("[EPGC] release heap mem");
584                                         delete It->second;
585                                         DBIt->second.second.erase(It++);
586 //                                      eDebug("[EPGC] delete old event (timeMap)");
587                                         updated = true;
588                                 }
589                                 else
590                                         ++It;
591                         }
592 #ifdef ENABLE_PRIVATE_EPG
593                         if ( updated )
594                         {
595                                 contentMaps::iterator x =
596                                         content_time_tables.find( DBIt->first );
597                                 if ( x != content_time_tables.end() )
598                                 {
599                                         timeMap &tmMap = eventDB[DBIt->first].second;
600                                         for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
601                                         {
602                                                 for ( contentTimeMap::iterator it(i->second.begin());
603                                                         it != i->second.end(); )
604                                                 {
605                                                         if ( tmMap.find(it->second.first) == tmMap.end() )
606                                                                 i->second.erase(it++);
607                                                         else
608                                                                 ++it;
609                                                 }
610                                                 if ( i->second.size() )
611                                                         ++i;
612                                                 else
613                                                         x->second.erase(i++);
614                                         }
615                                 }
616                         }
617 #endif
618                 }
619                 eDebug("[EPGC] stop cleanloop");
620                 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
621         }
622         cleanTimer.start(CLEAN_INTERVAL,true);
623 }
624
625 eEPGCache::~eEPGCache()
626 {
627         messages.send(Message::quit);
628         kill(); // waiting for thread shutdown
629         singleLock s(cache_lock);
630         for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
631                 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
632                         delete It->second;
633 }
634
635 void eEPGCache::gotMessage( const Message &msg )
636 {
637         switch (msg.type)
638         {
639                 case Message::flush:
640                         flushEPG(msg.service);
641                         break;
642                 case Message::startChannel:
643                 {
644                         singleLock s(channel_map_lock);
645                         channelMapIterator channel =
646                                 m_knownChannels.find(msg.channel);
647                         if ( channel != m_knownChannels.end() )
648                                 channel->second->startChannel();
649                         break;
650                 }
651                 case Message::leaveChannel:
652                 {
653                         singleLock s(channel_map_lock);
654                         channelMapIterator channel =
655                                 m_knownChannels.find(msg.channel);
656                         if ( channel != m_knownChannels.end() )
657                                 channel->second->abortEPG();
658                         break;
659                 }
660                 case Message::quit:
661                         quit(0);
662                         break;
663 #ifdef ENABLE_PRIVATE_EPG
664                 case Message::got_private_pid:
665                 {
666                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
667                         {
668                                 eDVBChannel *channel = (eDVBChannel*) it->first;
669                                 channel_data *data = it->second;
670                                 eDVBChannelID chid = channel->getChannelID();
671                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
672                                         chid.original_network_id.get() == msg.service.onid &&
673                                         data->m_PrivatePid == -1 )
674                                 {
675                                         data->m_PrivatePid = msg.pid;
676                                         data->m_PrivateService = msg.service;
677                                         data->startPrivateReader(msg.pid, -1);
678                                         break;
679                                 }
680                         }
681                         break;
682                 }
683 #endif
684                 case Message::timeChanged:
685                         cleanLoop();
686                         break;
687                 default:
688                         eDebug("unhandled EPGCache Message!!");
689                         break;
690         }
691 }
692
693 void eEPGCache::thread()
694 {
695         nice(4);
696         load();
697         cleanLoop();
698         runLoop();
699         save();
700 }
701
702 void eEPGCache::load()
703 {
704         FILE *f = fopen("/hdd/epg.dat", "r");
705         if (f)
706         {
707                 int size=0;
708                 int cnt=0;
709 #if 0
710                 unsigned char md5_saved[16];
711                 unsigned char md5[16];
712                 bool md5ok=false;
713
714                 if (!md5_file("/hdd/epg.dat", 1, md5))
715                 {
716                         FILE *f = fopen("/hdd/epg.dat.md5", "r");
717                         if (f)
718                         {
719                                 fread( md5_saved, 16, 1, f);
720                                 fclose(f);
721                                 if ( !memcmp(md5_saved, md5, 16) )
722                                         md5ok=true;
723                         }
724                 }
725                 if ( md5ok )
726 #endif
727                 {
728                         char text1[13];
729                         fread( text1, 13, 1, f);
730                         if ( !strncmp( text1, "ENIGMA_EPG_V4", 13) )
731                         {
732                                 fread( &size, sizeof(int), 1, f);
733                                 while(size--)
734                                 {
735                                         uniqueEPGKey key;
736                                         eventMap evMap;
737                                         timeMap tmMap;
738                                         int size=0;
739                                         fread( &key, sizeof(uniqueEPGKey), 1, f);
740                                         fread( &size, sizeof(int), 1, f);
741                                         while(size--)
742                                         {
743                                                 __u8 len=0;
744                                                 __u8 type=0;
745                                                 eventData *event=0;
746                                                 fread( &type, sizeof(__u8), 1, f);
747                                                 fread( &len, sizeof(__u8), 1, f);
748                                                 event = new eventData(0, len, type);
749                                                 event->EITdata = new __u8[len];
750                                                 eventData::CacheSize+=len;
751                                                 fread( event->EITdata, len, 1, f);
752                                                 evMap[ event->getEventID() ]=event;
753                                                 tmMap[ event->getStartTime() ]=event;
754                                                 ++cnt;
755                                         }
756                                         eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
757                                 }
758                                 eventData::load(f);
759                                 eDebug("%d events read from /hdd/epg.dat", cnt);
760 #ifdef ENABLE_PRIVATE_EPG
761                                 char text2[11];
762                                 fread( text2, 11, 1, f);
763                                 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
764                                 {
765                                         size=0;
766                                         fread( &size, sizeof(int), 1, f);
767                                         while(size--)
768                                         {
769                                                 int size=0;
770                                                 uniqueEPGKey key;
771                                                 fread( &key, sizeof(uniqueEPGKey), 1, f);
772                                                 fread( &size, sizeof(int), 1, f);
773                                                 while(size--)
774                                                 {
775                                                         int size;
776                                                         int content_id;
777                                                         fread( &content_id, sizeof(int), 1, f);
778                                                         fread( &size, sizeof(int), 1, f);
779                                                         while(size--)
780                                                         {
781                                                                 time_t time1, time2;
782                                                                 __u16 event_id;
783                                                                 fread( &time1, sizeof(time_t), 1, f);
784                                                                 fread( &time2, sizeof(time_t), 1, f);
785                                                                 fread( &event_id, sizeof(__u16), 1, f);
786                                                                 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
787                                                         }
788                                                 }
789                                         }
790                                 }
791 #endif // ENABLE_PRIVATE_EPG
792                         }
793                         else
794                                 eDebug("[EPGC] don't read old epg database");
795                         fclose(f);
796                 }
797         }
798 }
799
800 void eEPGCache::save()
801 {
802         struct statfs s;
803         off64_t tmp;
804         if (statfs("/hdd", &s)<0)
805                 tmp=0;
806         else
807         {
808                 tmp=s.f_blocks;
809                 tmp*=s.f_bsize;
810         }
811
812         // prevent writes to builtin flash
813         if ( tmp < 1024*1024*50 ) // storage size < 50MB
814                 return;
815
816         // check for enough free space on storage
817         tmp=s.f_bfree;
818         tmp*=s.f_bsize;
819         if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
820                 return;
821
822         FILE *f = fopen("/hdd/epg.dat", "w");
823         int cnt=0;
824         if ( f )
825         {
826                 const char *text = "ENIGMA_EPG_V4";
827                 fwrite( text, 13, 1, f );
828                 int size = eventDB.size();
829                 fwrite( &size, sizeof(int), 1, f );
830                 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
831                 {
832                         timeMap &timemap = service_it->second.second;
833                         fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
834                         size = timemap.size();
835                         fwrite( &size, sizeof(int), 1, f);
836                         for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
837                         {
838                                 __u8 len = time_it->second->ByteSize;
839                                 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
840                                 fwrite( &len, sizeof(__u8), 1, f);
841                                 fwrite( time_it->second->EITdata, len, 1, f);
842                                 ++cnt;
843                         }
844                 }
845                 eDebug("%d events written to /hdd/epg.dat", cnt);
846                 eventData::save(f);
847 #ifdef ENABLE_PRIVATE_EPG
848                 const char* text3 = "PRIVATE_EPG";
849                 fwrite( text3, 11, 1, f );
850                 size = content_time_tables.size();
851                 fwrite( &size, sizeof(int), 1, f);
852                 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
853                 {
854                         contentMap &content_time_table = a->second;
855                         fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
856                         int size = content_time_table.size();
857                         fwrite( &size, sizeof(int), 1, f);
858                         for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
859                         {
860                                 int size = i->second.size();
861                                 fwrite( &i->first, sizeof(int), 1, f);
862                                 fwrite( &size, sizeof(int), 1, f);
863                                 for ( contentTimeMap::iterator it(i->second.begin());
864                                         it != i->second.end(); ++it )
865                                 {
866                                         fwrite( &it->first, sizeof(time_t), 1, f);
867                                         fwrite( &it->second.first, sizeof(time_t), 1, f);
868                                         fwrite( &it->second.second, sizeof(__u16), 1, f);
869                                 }
870                         }
871                 }
872 #endif
873                 fclose(f);
874 #if 0
875                 unsigned char md5[16];
876                 if (!md5_file("/hdd/epg.dat", 1, md5))
877                 {
878                         FILE *f = fopen("/hdd/epg.dat.md5", "w");
879                         if (f)
880                         {
881                                 fwrite( md5, 16, 1, f);
882                                 fclose(f);
883                         }
884                 }
885 #endif
886         }
887 }
888
889 eEPGCache::channel_data::channel_data(eEPGCache *ml)
890         :cache(ml)
891         ,abortTimer(ml), zapTimer(ml)
892         ,state(0), isRunning(0), haveData(0), can_delete(1)
893 {
894         CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
895         CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
896 }
897
898 bool eEPGCache::channel_data::finishEPG()
899 {
900         if (!isRunning)  // epg ready
901         {
902                 eDebug("[EPGC] stop caching events(%d)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
903                 zapTimer.start(UPDATE_INTERVAL, 1);
904                 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
905                 for (int i=0; i < 3; ++i)
906                 {
907                         seenSections[i].clear();
908                         calcedSections[i].clear();
909                 }
910                 singleLock l(cache->cache_lock);
911                 cache->channelLastUpdated[channel->getChannelID()] = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
912 #ifdef ENABLE_PRIVATE_EPG
913                 if (seenPrivateSections.empty())
914 #endif
915                 can_delete=1;
916                 return true;
917         }
918         return false;
919 }
920
921 void eEPGCache::channel_data::startEPG()
922 {
923         eDebug("[EPGC] start caching events(%d)", eDVBLocalTimeHandler::getInstance()->difference()+time(0));
924         state=0;
925         haveData=0;
926         can_delete=0;
927         for (int i=0; i < 3; ++i)
928         {
929                 seenSections[i].clear();
930                 calcedSections[i].clear();
931         }
932
933         eDVBSectionFilterMask mask;
934         memset(&mask, 0, sizeof(mask));
935         mask.pid = 0x12;
936         mask.flags = eDVBSectionFilterMask::rfCRC;
937
938         mask.data[0] = 0x4E;
939         mask.mask[0] = 0xFE;
940         m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
941         m_NowNextReader->start(mask);
942         isRunning |= NOWNEXT;
943
944         mask.data[0] = 0x50;
945         mask.mask[0] = 0xF0;
946         m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
947         m_ScheduleReader->start(mask);
948         isRunning |= SCHEDULE;
949
950         mask.data[0] = 0x60;
951         mask.mask[0] = 0xF0;
952         m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
953         m_ScheduleOtherReader->start(mask);
954         isRunning |= SCHEDULE_OTHER;
955
956         abortTimer.start(7000,true);
957 }
958
959 void eEPGCache::channel_data::abortNonAvail()
960 {
961         if (!state)
962         {
963                 if ( !(haveData&eEPGCache::NOWNEXT) && (isRunning&eEPGCache::NOWNEXT) )
964                 {
965                         eDebug("[EPGC] abort non avail nownext reading");
966                         isRunning &= ~eEPGCache::NOWNEXT;
967                         m_NowNextReader->stop();
968                         m_NowNextConn=0;
969                 }
970                 if ( !(haveData&eEPGCache::SCHEDULE) && (isRunning&eEPGCache::SCHEDULE) )
971                 {
972                         eDebug("[EPGC] abort non avail schedule reading");
973                         isRunning &= ~SCHEDULE;
974                         m_ScheduleReader->stop();
975                         m_ScheduleConn=0;
976                 }
977                 if ( !(haveData&eEPGCache::SCHEDULE_OTHER) && (isRunning&eEPGCache::SCHEDULE_OTHER) )
978                 {
979                         eDebug("[EPGC] abort non avail schedule_other reading");
980                         isRunning &= ~SCHEDULE_OTHER;
981                         m_ScheduleOtherReader->stop();
982                         m_ScheduleOtherConn=0;
983                 }
984                 if ( isRunning )
985                         abortTimer.start(90000, true);
986                 else
987                 {
988                         ++state;
989                         for (int i=0; i < 3; ++i)
990                         {
991                                 seenSections[i].clear();
992                                 calcedSections[i].clear();
993                         }
994 #ifdef ENABLE_PRIVATE_EPG
995                         if (seenPrivateSections.empty())
996 #endif
997                         can_delete=1;
998                 }
999         }
1000         ++state;
1001 }
1002
1003 void eEPGCache::channel_data::startChannel()
1004 {
1005         updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1006
1007         int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (time(0)+eDVBLocalTimeHandler::getInstance()->difference()-It->second) * 1000 ) ) : ZAP_DELAY );
1008
1009         if (update < ZAP_DELAY)
1010                 update = ZAP_DELAY;
1011
1012         zapTimer.start(update, 1);
1013         if (update >= 60000)
1014                 eDebug("[EPGC] next update in %i min", update/60000);
1015         else if (update >= 1000)
1016                 eDebug("[EPGC] next update in %i sec", update/1000);
1017 }
1018
1019 void eEPGCache::channel_data::abortEPG()
1020 {
1021         for (int i=0; i < 3; ++i)
1022         {
1023                 seenSections[i].clear();
1024                 calcedSections[i].clear();
1025         }
1026         abortTimer.stop();
1027         zapTimer.stop();
1028         if (isRunning)
1029         {
1030                 eDebug("[EPGC] abort caching events !!");
1031                 if (isRunning & eEPGCache::SCHEDULE)
1032                 {
1033                         isRunning &= ~eEPGCache::SCHEDULE;
1034                         m_ScheduleReader->stop();
1035                         m_ScheduleConn=0;
1036                 }
1037                 if (isRunning & eEPGCache::NOWNEXT)
1038                 {
1039                         isRunning &= ~eEPGCache::NOWNEXT;
1040                         m_NowNextReader->stop();
1041                         m_NowNextConn=0;
1042                 }
1043                 if (isRunning & SCHEDULE_OTHER)
1044                 {
1045                         isRunning &= ~eEPGCache::SCHEDULE_OTHER;
1046                         m_ScheduleOtherReader->stop();
1047                         m_ScheduleOtherConn=0;
1048                 }
1049         }
1050 #ifdef ENABLE_PRIVATE_EPG
1051         if (m_PrivateReader)
1052                 m_PrivateReader->stop();
1053         if (m_PrivateConn)
1054                 m_PrivateConn=0;
1055 #endif
1056         can_delete=1;
1057 }
1058
1059 void eEPGCache::channel_data::readData( const __u8 *data)
1060 {
1061         if (!data)
1062                 eDebug("get Null pointer from section reader !!");
1063         else
1064         {
1065                 int source;
1066                 int map;
1067                 iDVBSectionReader *reader=NULL;
1068                 switch(data[0])
1069                 {
1070                         case 0x4E ... 0x4F:
1071                                 reader=m_NowNextReader;
1072                                 source=eEPGCache::NOWNEXT;
1073                                 map=0;
1074                                 break;
1075                         case 0x50 ... 0x5F:
1076                                 reader=m_ScheduleReader;
1077                                 source=eEPGCache::SCHEDULE;
1078                                 map=1;
1079                                 break;
1080                         case 0x60 ... 0x6F:
1081                                 reader=m_ScheduleOtherReader;
1082                                 source=eEPGCache::SCHEDULE_OTHER;
1083                                 map=2;
1084                                 break;
1085                         default:
1086                                 eDebug("[EPGC] unknown table_id !!!");
1087                                 return;
1088                 }
1089                 tidMap &seenSections = this->seenSections[map];
1090                 tidMap &calcedSections = this->calcedSections[map];
1091                 if ( state == 1 && calcedSections == seenSections || state > 1 )
1092                 {
1093                         eDebugNoNewLine("[EPGC] ");
1094                         switch (source)
1095                         {
1096                                 case eEPGCache::NOWNEXT:
1097                                         m_NowNextConn=0;
1098                                         eDebugNoNewLine("nownext");
1099                                         break;
1100                                 case eEPGCache::SCHEDULE:
1101                                         m_ScheduleConn=0;
1102                                         eDebugNoNewLine("schedule");
1103                                         break;
1104                                 case eEPGCache::SCHEDULE_OTHER:
1105                                         m_ScheduleOtherConn=0;
1106                                         eDebugNoNewLine("schedule other");
1107                                         break;
1108                                 default: eDebugNoNewLine("unknown");break;
1109                         }
1110                         eDebug(" finished(%d)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
1111                         if ( reader )
1112                                 reader->stop();
1113                         isRunning &= ~source;
1114                         if (!isRunning)
1115                                 finishEPG();
1116                 }
1117                 else
1118                 {
1119                         eit_t *eit = (eit_t*) data;
1120                         __u32 sectionNo = data[0] << 24;
1121                         sectionNo |= data[3] << 16;
1122                         sectionNo |= data[4] << 8;
1123                         sectionNo |= eit->section_number;
1124
1125                         tidMap::iterator it =
1126                                 seenSections.find(sectionNo);
1127
1128                         if ( it == seenSections.end() )
1129                         {
1130                                 seenSections.insert(sectionNo);
1131                                 calcedSections.insert(sectionNo);
1132                                 __u32 tmpval = sectionNo & 0xFFFFFF00;
1133                                 __u8 incr = source == NOWNEXT ? 1 : 8;
1134                                 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1135                                 {
1136                                         if ( i == eit->section_number )
1137                                         {
1138                                                 for (int x=i; x <= eit->segment_last_section_number; ++x)
1139                                                         calcedSections.insert(tmpval|(x&0xFF));
1140                                         }
1141                                         else
1142                                                 calcedSections.insert(tmpval|(i&0xFF));
1143                                 }
1144                                 cache->sectionRead(data, source, this);
1145                         }
1146                 }
1147         }
1148 }
1149
1150 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1151 // if t == -1 we search the current event...
1152 {
1153         singleLock s(cache_lock);
1154         uniqueEPGKey key(service);
1155
1156         // check if EPG for this service is ready...
1157         eventCache::iterator It = eventDB.find( key );
1158         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1159         {
1160                 if (t==-1)
1161                         t = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
1162                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1163                         It->second.second.upper_bound(t); // just >
1164                 if ( i != It->second.second.end() )
1165                 {
1166                         if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1167                         {
1168                                 timeMap::iterator x = i;
1169                                 --x;
1170                                 if ( x != It->second.second.end() )
1171                                 {
1172                                         time_t start_time = x->second->getStartTime();
1173                                         if (direction >= 0)
1174                                         {
1175                                                 if (t < start_time)
1176                                                         return -1;
1177                                                 if (t > (start_time+x->second->getDuration()))
1178                                                         return -1;
1179                                         }
1180                                         i = x;
1181                                 }
1182                                 else
1183                                         return -1;
1184                         }
1185                         result = i->second;
1186                         return 0;
1187                 }
1188         }
1189         return -1;
1190 }
1191
1192 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1193 {
1194         singleLock s(cache_lock);
1195         const eventData *data=0;
1196         RESULT ret = lookupEventTime(service, t, data, direction);
1197         if ( !ret && data )
1198                 result = data->get();
1199         return ret;
1200 }
1201
1202 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1203 {
1204         singleLock s(cache_lock);
1205         const eventData *data=0;
1206         RESULT ret = lookupEventTime(service, t, data, direction);
1207         if ( !ret && data )
1208                 result = new Event((uint8_t*)data->get());
1209         return ret;
1210 }
1211
1212 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1213 {
1214         singleLock s(cache_lock);
1215         const eventData *data=0;
1216         RESULT ret = lookupEventTime(service, t, data, direction);
1217         if ( !ret && data )
1218         {
1219                 Event ev((uint8_t*)data->get());
1220                 result = new eServiceEvent();
1221                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1222                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1223         }
1224         return ret;
1225 }
1226
1227 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1228 {
1229         singleLock s(cache_lock);
1230         uniqueEPGKey key( service );
1231
1232         eventCache::iterator It = eventDB.find( key );
1233         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1234         {
1235                 eventMap::iterator i( It->second.first.find( event_id ));
1236                 if ( i != It->second.first.end() )
1237                 {
1238                         result = i->second;
1239                         return 0;
1240                 }
1241                 else
1242                 {
1243                         result = 0;
1244                         eDebug("event %04x not found in epgcache", event_id);
1245                 }
1246         }
1247         return -1;
1248 }
1249
1250 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1251 {
1252         singleLock s(cache_lock);
1253         const eventData *data=0;
1254         RESULT ret = lookupEventId(service, event_id, data);
1255         if ( !ret && data )
1256                 result = data->get();
1257         return ret;
1258 }
1259
1260 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1261 {
1262         singleLock s(cache_lock);
1263         const eventData *data=0;
1264         RESULT ret = lookupEventId(service, event_id, data);
1265         if ( !ret && data )
1266                 result = new Event((uint8_t*)data->get());
1267         return ret;
1268 }
1269
1270 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1271 {
1272         singleLock s(cache_lock);
1273         const eventData *data=0;
1274         RESULT ret = lookupEventId(service, event_id, data);
1275         if ( !ret && data )
1276         {
1277                 Event ev((uint8_t*)data->get());
1278                 result = new eServiceEvent();
1279                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1280                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1281         }
1282         return ret;
1283 }
1284
1285 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1286 {
1287         eventCache::iterator It = eventDB.find( service );
1288         if ( It != eventDB.end() && It->second.second.size() )
1289         {
1290                 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1291                 if ( begin != -1 )
1292                 {
1293                         m_timemap_cursor = It->second.second.lower_bound(begin);
1294                         if ( m_timemap_cursor != It->second.second.end() )
1295                         {
1296                                 if ( m_timemap_cursor->second->getStartTime() != begin )
1297                                 {
1298                                         timeMap::iterator x = m_timemap_cursor;
1299                                         --x;
1300                                         if ( x != It->second.second.end() )
1301                                         {
1302                                                 time_t start_time = x->second->getStartTime();
1303                                                 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1304                                                         m_timemap_cursor = x;
1305                                         }
1306                                 }
1307                         }
1308                 }
1309                 else
1310                         m_timemap_cursor = It->second.second.begin();
1311                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1312                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1313                 return 0;
1314         }
1315         return -1;
1316 }
1317
1318 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1319 {
1320         if ( m_timemap_cursor != m_timemap_end )
1321         {
1322                 result = m_timemap_cursor++->second;
1323                 return 0;
1324         }
1325         return -1;
1326 }
1327
1328 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1329 {
1330         if ( m_timemap_cursor != m_timemap_end )
1331         {
1332                 result = m_timemap_cursor++->second->get();
1333                 return 0;
1334         }
1335         return -1;
1336 }
1337
1338 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1339 {
1340         if ( m_timemap_cursor != m_timemap_end )
1341         {
1342                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1343                 return 0;
1344         }
1345         return -1;
1346 }
1347
1348 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1349 {
1350         if ( m_timemap_cursor != m_timemap_end )
1351         {
1352                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1353                 result = new eServiceEvent();
1354                 return result->parseFrom(&ev, currentQueryTsidOnid);
1355         }
1356         return -1;
1357 }
1358
1359 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1360 {
1361         PyObject *tmp=NULL;
1362         int pos=0;
1363         while(pos < argcount)
1364         {
1365                 bool inc_refcount=false;
1366                 switch(argstring[pos])
1367                 {
1368                         case 'I': // Event Id
1369                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1370                                 break;
1371                         case 'B': // Event Begin Time
1372                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1373                                 break;
1374                         case 'D': // Event Duration
1375                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1376                                 break;
1377                         case 'T': // Event Title
1378                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1379                                 break;
1380                         case 'S': // Event Short Description
1381                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1382                                 break;
1383                         case 'E': // Event Extended Description
1384                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1385                                 break;
1386                         case 'C': // Current Time
1387                                 tmp = nowTime;
1388                                 inc_refcount = true;
1389                                 break;
1390                         case 'R': // service reference string
1391                                 tmp = service;
1392                                 inc_refcount = true;
1393                                 break;
1394                         case 'N': // service name
1395                                 tmp = service_name;
1396                                 inc_refcount = true;
1397                 }
1398                 if (!tmp)
1399                 {
1400                         tmp = Py_None;
1401                         inc_refcount = true;
1402                 }
1403                 if (inc_refcount)
1404                         Py_INCREF(tmp);
1405                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1406         }
1407 }
1408
1409 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1410 {
1411         if (convertFunc)
1412         {
1413                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1414                 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1415                 if (result == NULL)
1416                 {
1417                         if (service_name)
1418                                 Py_DECREF(service_name);
1419                         if (nowTime)
1420                                 Py_DECREF(nowTime);
1421                         Py_DECREF(convertFuncArgs);
1422                         Py_DECREF(dest_list);
1423                         return result;
1424                 }
1425                 PyList_Append(dest_list, result);
1426                 Py_DECREF(result);
1427         }
1428         else
1429         {
1430                 PyObject *tuple = PyTuple_New(argcount);
1431                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1432                 PyList_Append(dest_list, tuple);
1433                 Py_DECREF(tuple);
1434         }
1435         return 0;
1436 }
1437
1438 // here we get a list with tuples
1439 // first tuple entry is the servicereference
1440 // the second is the type of query (0 = time, 1 = event_id)
1441 // the third
1442 //              when type is eventid it is the event_id
1443 //              when type is time then it is the start_time ( 0 for now_time )
1444 // the fourth is the end_time .. ( optional )
1445
1446 /* argv is a python string
1447    I = Event Id
1448    B = Event Begin Time
1449    D = Event Duration
1450    T = Event Title
1451    S = Event Short Description
1452    E = Event Extended Description
1453    C = Current Time
1454    R = Service Reference
1455    N = Service Name
1456 */
1457
1458 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1459 {
1460         PyObject *convertFuncArgs=NULL;
1461         int argcount=0;
1462         char *argstring=NULL;
1463         if (!PyList_Check(list))
1464         {
1465                 PyErr_SetString(PyExc_StandardError,
1466                         "type error");
1467                 eDebug("no list");
1468                 return NULL;
1469         }
1470         int listIt=0;
1471         int listSize=PyList_Size(list);
1472         if (!listSize)
1473         {
1474                 PyErr_SetString(PyExc_StandardError,
1475                         "not params given");
1476                 eDebug("not params given");
1477                 return NULL;
1478         }
1479         else 
1480         {
1481                 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1482                 if (PyString_Check(argv))
1483                 {
1484                         argstring = PyString_AS_STRING(argv);
1485                         ++listIt;
1486                 }
1487                 else
1488                         argstring = "I"; // just event id as default
1489                 argcount = strlen(argstring);
1490 //              eDebug("have %d args('%s')", argcount, argstring);
1491         }
1492         if (convertFunc)
1493         {
1494                 if (!PyCallable_Check(convertFunc))
1495                 {
1496                         PyErr_SetString(PyExc_StandardError,
1497                                 "convertFunc must be callable");
1498                         eDebug("convertFunc is not callable");
1499                         return NULL;
1500                 }
1501                 convertFuncArgs = PyTuple_New(argcount);
1502         }
1503
1504         PyObject *nowTime = strchr(argstring, 'C') ?
1505                 PyLong_FromLong(time(0)+eDVBLocalTimeHandler::getInstance()->difference()) :
1506                 NULL;
1507
1508         bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1509
1510         // create dest list
1511         PyObject *dest_list=PyList_New(0);
1512         while(listSize > listIt)
1513         {
1514                 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1515                 if (PyTuple_Check(item))
1516                 {
1517                         int type=0;
1518                         long event_id=-1;
1519                         time_t stime=-1;
1520                         int minutes=0;
1521                         int tupleSize=PyTuple_Size(item);
1522                         int tupleIt=0;
1523                         PyObject *service=NULL;
1524                         while(tupleSize > tupleIt)  // parse query args
1525                         {
1526                                 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1527                                 switch(tupleIt++)
1528                                 {
1529                                         case 0:
1530                                         {
1531                                                 if (!PyString_Check(entry))
1532                                                 {
1533                                                         eDebug("tuple entry 0 is no a string");
1534                                                         continue;
1535                                                 }
1536                                                 service = entry;
1537                                                 break;
1538                                         }
1539                                         case 1:
1540                                                 type=PyInt_AsLong(entry);
1541                                                 if (type < -1 || type > 2)
1542                                                 {
1543                                                         eDebug("unknown type %d", type);
1544                                                         continue;
1545                                                 }
1546                                                 break;
1547                                         case 2:
1548                                                 event_id=stime=PyInt_AsLong(entry);
1549                                                 break;
1550                                         case 3:
1551                                                 minutes=PyInt_AsLong(entry);
1552                                                 break;
1553                                         default:
1554                                                 eDebug("unneeded extra argument");
1555                                                 break;
1556                                 }
1557                         }
1558                         eServiceReference ref(PyString_AS_STRING(service));
1559                         if (ref.type != eServiceReference::idDVB)
1560                         {
1561                                 eDebug("service reference for epg query is not valid");
1562                                 continue;
1563                         }
1564                         PyObject *service_name=NULL;
1565                         if (must_get_service_name)
1566                         {
1567                                 ePtr<iStaticServiceInformation> sptr;
1568                                 eServiceCenterPtr service_center;
1569                                 eServiceCenter::getPrivInstance(service_center);
1570                                 if (service_center)
1571                                 {
1572                                         service_center->info(ref, sptr);
1573                                         if (sptr)
1574                                         {
1575                                                 std::string name;
1576                                                 sptr->getName(ref, name);
1577                                                 if (name.length())
1578                                                         service_name = PyString_FromString(name.c_str());
1579                                         }
1580                                 }
1581                                 if (!service_name)
1582                                         service_name = PyString_FromString("<n/a>");
1583                         }
1584                         if (minutes)
1585                         {
1586                                 Lock();
1587                                 if (!startTimeQuery(ref, stime, minutes))
1588                                 {
1589                                         ePtr<eServiceEvent> ptr;
1590                                         while (!getNextTimeEntry(ptr))
1591                                         {
1592                                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1593                                                 if (ret)
1594                                                         return ret;
1595                                         }
1596                                 }
1597                                 Unlock();
1598                         }
1599                         else
1600                         {
1601                                 ePtr<eServiceEvent> ptr;
1602                                 if (stime)
1603                                 {
1604                                         if (type == 2)
1605                                                 lookupEventId(ref, event_id, ptr);
1606                                         else
1607                                                 lookupEventTime(ref, stime, ptr, type);
1608                                 }
1609                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1610                                 if (ret)
1611                                         return ret;
1612                         }
1613                         if (service_name)
1614                                 Py_DECREF(service_name);
1615                 }
1616         }
1617         if (convertFuncArgs)
1618                 Py_DECREF(convertFuncArgs);
1619         if (nowTime)
1620                 Py_DECREF(nowTime);
1621         return dest_list;
1622 }
1623
1624 #ifdef ENABLE_PRIVATE_EPG
1625 #include <dvbsi++/descriptor_tag.h>
1626 #include <dvbsi++/unknown_descriptor.h>
1627 #include <dvbsi++/private_data_specifier_descriptor.h>
1628
1629 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
1630 {
1631         ePtr<eTable<ProgramMapSection> > ptr;
1632         if (!pmthandler->getPMT(ptr) && ptr)
1633         {
1634                 std::vector<ProgramMapSection*>::const_iterator i;
1635                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
1636                 {
1637                         const ProgramMapSection &pmt = **i;
1638
1639                         ElementaryStreamInfoConstIterator es;
1640                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
1641                         {
1642                                 int tmp=0;
1643                                 switch ((*es)->getType())
1644                                 {
1645                                 case 0x05: // private
1646                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
1647                                                 desc != (*es)->getDescriptors()->end(); ++desc)
1648                                         {
1649                                                 switch ((*desc)->getTag())
1650                                                 {
1651                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
1652                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
1653                                                                         tmp |= 1;
1654                                                                 break;
1655                                                         case 0x90:
1656                                                         {
1657                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
1658                                                                 int descr_len = descr->getLength();
1659                                                                 if (descr_len == 4)
1660                                                                 {
1661                                                                         uint8_t data[descr_len+2];
1662                                                                         descr->writeToBuffer(data);
1663                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
1664                                                                                 tmp |= 2;
1665                                                                 }
1666                                                                 break;
1667                                                         }
1668                                                         default:
1669                                                                 break;
1670                                                 }
1671                                         }
1672                                 default:
1673                                         break;
1674                                 }
1675                                 if (tmp==3)
1676                                 {
1677                                         eServiceReferenceDVB ref;
1678                                         if (!pmthandler->getService(ref))
1679                                         {
1680                                                 int pid = (*es)->getPid();
1681                                                 messages.send(Message(Message::got_private_pid, ref, pid));
1682                                                 return;
1683                                         }
1684                                 }
1685                         }
1686                 }
1687         }
1688         else
1689                 eDebug("PMTready but no pmt!!");
1690 }
1691
1692 struct date_time
1693 {
1694         __u8 data[5];
1695         time_t tm;
1696         date_time( const date_time &a )
1697         {
1698                 memcpy(data, a.data, 5);
1699                 tm = a.tm;
1700         }
1701         date_time( const __u8 data[5])
1702         {
1703                 memcpy(this->data, data, 5);
1704                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
1705         }
1706         date_time()
1707         {
1708         }
1709         const __u8& operator[](int pos) const
1710         {
1711                 return data[pos];
1712         }
1713 };
1714
1715 struct less_datetime
1716 {
1717         bool operator()( const date_time &a, const date_time &b ) const
1718         {
1719                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
1720         }
1721 };
1722
1723 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
1724 {
1725         contentMap &content_time_table = content_time_tables[current_service];
1726         singleLock s(cache_lock);
1727         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
1728         eventMap &evMap = eventDB[current_service].first;
1729         timeMap &tmMap = eventDB[current_service].second;
1730         int ptr=8;
1731         int content_id = data[ptr++] << 24;
1732         content_id |= data[ptr++] << 16;
1733         content_id |= data[ptr++] << 8;
1734         content_id |= data[ptr++];
1735
1736         contentTimeMap &time_event_map =
1737                 content_time_table[content_id];
1738         for ( contentTimeMap::iterator it( time_event_map.begin() );
1739                 it != time_event_map.end(); ++it )
1740         {
1741                 eventMap::iterator evIt( evMap.find(it->second.second) );
1742                 if ( evIt != evMap.end() )
1743                 {
1744                         delete evIt->second;
1745                         evMap.erase(evIt);
1746                 }
1747                 tmMap.erase(it->second.first);
1748         }
1749         time_event_map.clear();
1750
1751         __u8 duration[3];
1752         memcpy(duration, data+ptr, 3);
1753         ptr+=3;
1754         int duration_sec =
1755                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
1756
1757         const __u8 *descriptors[65];
1758         const __u8 **pdescr = descriptors;
1759
1760         int descriptors_length = (data[ptr++]&0x0F) << 8;
1761         descriptors_length |= data[ptr++];
1762         while ( descriptors_length > 0 )
1763         {
1764                 int descr_type = data[ptr];
1765                 int descr_len = data[ptr+1];
1766                 descriptors_length -= (descr_len+2);
1767                 if ( descr_type == 0xf2 )
1768                 {
1769                         ptr+=2;
1770                         int tsid = data[ptr++] << 8;
1771                         tsid |= data[ptr++];
1772                         int onid = data[ptr++] << 8;
1773                         onid |= data[ptr++];
1774                         int sid = data[ptr++] << 8;
1775                         sid |= data[ptr++];
1776                         uniqueEPGKey service( sid, onid, tsid );
1777                         descr_len -= 6;
1778                         while( descr_len > 0 )
1779                         {
1780                                 __u8 datetime[5];
1781                                 datetime[0] = data[ptr++];
1782                                 datetime[1] = data[ptr++];
1783                                 int tmp_len = data[ptr++];
1784                                 descr_len -= 3;
1785                                 while( tmp_len > 0 )
1786                                 {
1787                                         memcpy(datetime+2, data+ptr, 3);
1788                                         ptr+=3;
1789                                         descr_len -= 3;
1790                                         tmp_len -= 3;
1791                                         start_times[datetime].push_back(service);
1792                                 }
1793                         }
1794                 }
1795                 else
1796                 {
1797                         *pdescr++=data+ptr;
1798                         ptr += 2;
1799                         ptr += descr_len;
1800                 }
1801         }
1802         __u8 event[4098];
1803         eit_event_struct *ev_struct = (eit_event_struct*) event;
1804         ev_struct->running_status = 0;
1805         ev_struct->free_CA_mode = 1;
1806         memcpy(event+7, duration, 3);
1807         ptr = 12;
1808         const __u8 **d=descriptors;
1809         while ( d < pdescr )
1810         {
1811                 memcpy(event+ptr, *d, ((*d)[1])+2);
1812                 ptr+=(*d++)[1];
1813                 ptr+=2;
1814         }
1815         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
1816         {
1817                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
1818                 if ( (it->first.tm + duration_sec) < now )
1819                         continue;
1820                 memcpy(event+2, it->first.data, 5);
1821                 int bptr = ptr;
1822                 int cnt=0;
1823                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
1824                 {
1825                         event[bptr++] = 0x4A;
1826                         __u8 *len = event+(bptr++);
1827                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
1828                         event[bptr++] = (i->tsid & 0xFF);
1829                         event[bptr++] = (i->onid & 0xFF00) >> 8;
1830                         event[bptr++] = (i->onid & 0xFF);
1831                         event[bptr++] = (i->sid & 0xFF00) >> 8;
1832                         event[bptr++] = (i->sid & 0xFF);
1833                         event[bptr++] = 0xB0;
1834                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
1835                         *len = ((event+bptr) - len)-1;
1836                 }
1837                 int llen = bptr - 12;
1838                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
1839                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
1840
1841                 time_t stime = it->first.tm;
1842                 while( tmMap.find(stime) != tmMap.end() )
1843                         ++stime;
1844                 event[6] += (stime - it->first.tm);
1845                 __u16 event_id = 0;
1846                 while( evMap.find(event_id) != evMap.end() )
1847                         ++event_id;
1848                 event[0] = (event_id & 0xFF00) >> 8;
1849                 event[1] = (event_id & 0xFF);
1850                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
1851                 eventData *d = new eventData( ev_struct, bptr, eEPGCache::SCHEDULE );
1852                 evMap[event_id] = d;
1853                 tmMap[stime] = d;
1854         }
1855 }
1856
1857 void eEPGCache::channel_data::startPrivateReader(int pid, int version)
1858 {
1859         eDVBSectionFilterMask mask;
1860         memset(&mask, 0, sizeof(mask));
1861         mask.pid = pid;
1862         mask.flags = eDVBSectionFilterMask::rfCRC;
1863         mask.data[0] = 0xA0;
1864         mask.mask[0] = 0xFF;
1865         eDebug("start privatefilter for pid %04x and version %d", pid, version);
1866         if (version != -1)
1867         {
1868                 mask.data[3] = version << 1;
1869                 mask.mask[3] = 0x3E;
1870                 mask.mode[3] = 0x3E;
1871         }
1872         seenPrivateSections.clear();
1873         m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
1874         m_PrivateReader->start(mask);
1875 #ifdef NEED_DEMUX_WORKAROUND
1876         m_PrevVersion=version;
1877 #endif
1878 }
1879
1880 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
1881 {
1882         if (!data)
1883                 eDebug("get Null pointer from section reader !!");
1884         else
1885         {
1886                 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
1887                 {
1888 #ifdef NEED_DEMUX_WORKAROUND
1889                         int version = data[5];
1890                         version = ((version & 0x3E) >> 1);
1891                         can_delete = 0;
1892                         if ( m_PrevVersion != version )
1893                         {
1894                                 cache->privateSectionRead(m_PrivateService, data);
1895                                 seenPrivateSections.insert(data[6]);
1896                         }
1897                         else
1898                                 eDebug("ignore");
1899 #else
1900                         can_delete = 0;
1901                         cache->privateSectionRead(m_PrivateService, data);
1902                         seenPrivateSections.insert(data[6]);
1903 #endif
1904                 }
1905                 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
1906                 {
1907                         eDebug("[EPGC] private finished");
1908                         if (!isRunning)
1909                                 can_delete = 1;
1910                         int version = data[5];
1911                         version = ((version & 0x3E) >> 1);
1912                         startPrivateReader(m_PrivatePid, version);
1913                 }
1914         }
1915 }
1916
1917 #endif // ENABLE_PRIVATE_EPG