fix segfault on incorrect arguments
[vuplus_dvbapp] / 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                         unsigned int magic=0;
729                         fread( &magic, sizeof(int), 1, f);
730                         if (magic != 0x98765432)
731                         {
732                                 eDebug("epg file has incorrect byte order.. dont read it");
733                                 fclose(f);
734                                 return;
735                         }
736                         char text1[13];
737                         fread( text1, 13, 1, f);
738                         if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
739                         {
740                                 fread( &size, sizeof(int), 1, f);
741                                 while(size--)
742                                 {
743                                         uniqueEPGKey key;
744                                         eventMap evMap;
745                                         timeMap tmMap;
746                                         int size=0;
747                                         fread( &key, sizeof(uniqueEPGKey), 1, f);
748                                         fread( &size, sizeof(int), 1, f);
749                                         while(size--)
750                                         {
751                                                 __u8 len=0;
752                                                 __u8 type=0;
753                                                 eventData *event=0;
754                                                 fread( &type, sizeof(__u8), 1, f);
755                                                 fread( &len, sizeof(__u8), 1, f);
756                                                 event = new eventData(0, len, type);
757                                                 event->EITdata = new __u8[len];
758                                                 eventData::CacheSize+=len;
759                                                 fread( event->EITdata, len, 1, f);
760                                                 evMap[ event->getEventID() ]=event;
761                                                 tmMap[ event->getStartTime() ]=event;
762                                                 ++cnt;
763                                         }
764                                         eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
765                                 }
766                                 eventData::load(f);
767                                 eDebug("%d events read from /hdd/epg.dat", cnt);
768 #ifdef ENABLE_PRIVATE_EPG
769                                 char text2[11];
770                                 fread( text2, 11, 1, f);
771                                 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
772                                 {
773                                         size=0;
774                                         fread( &size, sizeof(int), 1, f);
775                                         while(size--)
776                                         {
777                                                 int size=0;
778                                                 uniqueEPGKey key;
779                                                 fread( &key, sizeof(uniqueEPGKey), 1, f);
780                                                 fread( &size, sizeof(int), 1, f);
781                                                 while(size--)
782                                                 {
783                                                         int size;
784                                                         int content_id;
785                                                         fread( &content_id, sizeof(int), 1, f);
786                                                         fread( &size, sizeof(int), 1, f);
787                                                         while(size--)
788                                                         {
789                                                                 time_t time1, time2;
790                                                                 __u16 event_id;
791                                                                 fread( &time1, sizeof(time_t), 1, f);
792                                                                 fread( &time2, sizeof(time_t), 1, f);
793                                                                 fread( &event_id, sizeof(__u16), 1, f);
794                                                                 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
795                                                         }
796                                                 }
797                                         }
798                                 }
799 #endif // ENABLE_PRIVATE_EPG
800                         }
801                         else
802                                 eDebug("[EPGC] don't read old epg database");
803                         fclose(f);
804                 }
805         }
806 }
807
808 void eEPGCache::save()
809 {
810         struct statfs s;
811         off64_t tmp;
812         if (statfs("/hdd", &s)<0)
813                 tmp=0;
814         else
815         {
816                 tmp=s.f_blocks;
817                 tmp*=s.f_bsize;
818         }
819
820         // prevent writes to builtin flash
821         if ( tmp < 1024*1024*50 ) // storage size < 50MB
822                 return;
823
824         // check for enough free space on storage
825         tmp=s.f_bfree;
826         tmp*=s.f_bsize;
827         if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
828                 return;
829
830         FILE *f = fopen("/hdd/epg.dat", "w");
831         int cnt=0;
832         if ( f )
833         {
834                 unsigned int magic = 0x98765432;
835                 fwrite( &magic, sizeof(int), 1, f);
836                 const char *text = "ENIGMA_EPG_V5";
837                 fwrite( text, 13, 1, f );
838                 int size = eventDB.size();
839                 fwrite( &size, sizeof(int), 1, f );
840                 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
841                 {
842                         timeMap &timemap = service_it->second.second;
843                         fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
844                         size = timemap.size();
845                         fwrite( &size, sizeof(int), 1, f);
846                         for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
847                         {
848                                 __u8 len = time_it->second->ByteSize;
849                                 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
850                                 fwrite( &len, sizeof(__u8), 1, f);
851                                 fwrite( time_it->second->EITdata, len, 1, f);
852                                 ++cnt;
853                         }
854                 }
855                 eDebug("%d events written to /hdd/epg.dat", cnt);
856                 eventData::save(f);
857 #ifdef ENABLE_PRIVATE_EPG
858                 const char* text3 = "PRIVATE_EPG";
859                 fwrite( text3, 11, 1, f );
860                 size = content_time_tables.size();
861                 fwrite( &size, sizeof(int), 1, f);
862                 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
863                 {
864                         contentMap &content_time_table = a->second;
865                         fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
866                         int size = content_time_table.size();
867                         fwrite( &size, sizeof(int), 1, f);
868                         for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
869                         {
870                                 int size = i->second.size();
871                                 fwrite( &i->first, sizeof(int), 1, f);
872                                 fwrite( &size, sizeof(int), 1, f);
873                                 for ( contentTimeMap::iterator it(i->second.begin());
874                                         it != i->second.end(); ++it )
875                                 {
876                                         fwrite( &it->first, sizeof(time_t), 1, f);
877                                         fwrite( &it->second.first, sizeof(time_t), 1, f);
878                                         fwrite( &it->second.second, sizeof(__u16), 1, f);
879                                 }
880                         }
881                 }
882 #endif
883                 fclose(f);
884 #if 0
885                 unsigned char md5[16];
886                 if (!md5_file("/hdd/epg.dat", 1, md5))
887                 {
888                         FILE *f = fopen("/hdd/epg.dat.md5", "w");
889                         if (f)
890                         {
891                                 fwrite( md5, 16, 1, f);
892                                 fclose(f);
893                         }
894                 }
895 #endif
896         }
897 }
898
899 eEPGCache::channel_data::channel_data(eEPGCache *ml)
900         :cache(ml)
901         ,abortTimer(ml), zapTimer(ml)
902         ,state(0), isRunning(0), haveData(0), can_delete(1)
903 {
904         CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
905         CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
906 }
907
908 bool eEPGCache::channel_data::finishEPG()
909 {
910         if (!isRunning)  // epg ready
911         {
912                 eDebug("[EPGC] stop caching events(%d)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
913                 zapTimer.start(UPDATE_INTERVAL, 1);
914                 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
915                 for (int i=0; i < 3; ++i)
916                 {
917                         seenSections[i].clear();
918                         calcedSections[i].clear();
919                 }
920                 singleLock l(cache->cache_lock);
921                 cache->channelLastUpdated[channel->getChannelID()] = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
922 #ifdef ENABLE_PRIVATE_EPG
923                 if (seenPrivateSections.empty())
924 #endif
925                 can_delete=1;
926                 return true;
927         }
928         return false;
929 }
930
931 void eEPGCache::channel_data::startEPG()
932 {
933         eDebug("[EPGC] start caching events(%d)", eDVBLocalTimeHandler::getInstance()->difference()+time(0));
934         state=0;
935         haveData=0;
936         can_delete=0;
937         for (int i=0; i < 3; ++i)
938         {
939                 seenSections[i].clear();
940                 calcedSections[i].clear();
941         }
942
943         eDVBSectionFilterMask mask;
944         memset(&mask, 0, sizeof(mask));
945         mask.pid = 0x12;
946         mask.flags = eDVBSectionFilterMask::rfCRC;
947
948         mask.data[0] = 0x4E;
949         mask.mask[0] = 0xFE;
950         m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
951         m_NowNextReader->start(mask);
952         isRunning |= NOWNEXT;
953
954         mask.data[0] = 0x50;
955         mask.mask[0] = 0xF0;
956         m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
957         m_ScheduleReader->start(mask);
958         isRunning |= SCHEDULE;
959
960         mask.data[0] = 0x60;
961         mask.mask[0] = 0xF0;
962         m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
963         m_ScheduleOtherReader->start(mask);
964         isRunning |= SCHEDULE_OTHER;
965
966         abortTimer.start(7000,true);
967 }
968
969 void eEPGCache::channel_data::abortNonAvail()
970 {
971         if (!state)
972         {
973                 if ( !(haveData&eEPGCache::NOWNEXT) && (isRunning&eEPGCache::NOWNEXT) )
974                 {
975                         eDebug("[EPGC] abort non avail nownext reading");
976                         isRunning &= ~eEPGCache::NOWNEXT;
977                         m_NowNextReader->stop();
978                         m_NowNextConn=0;
979                 }
980                 if ( !(haveData&eEPGCache::SCHEDULE) && (isRunning&eEPGCache::SCHEDULE) )
981                 {
982                         eDebug("[EPGC] abort non avail schedule reading");
983                         isRunning &= ~SCHEDULE;
984                         m_ScheduleReader->stop();
985                         m_ScheduleConn=0;
986                 }
987                 if ( !(haveData&eEPGCache::SCHEDULE_OTHER) && (isRunning&eEPGCache::SCHEDULE_OTHER) )
988                 {
989                         eDebug("[EPGC] abort non avail schedule_other reading");
990                         isRunning &= ~SCHEDULE_OTHER;
991                         m_ScheduleOtherReader->stop();
992                         m_ScheduleOtherConn=0;
993                 }
994                 if ( isRunning )
995                         abortTimer.start(90000, true);
996                 else
997                 {
998                         ++state;
999                         for (int i=0; i < 3; ++i)
1000                         {
1001                                 seenSections[i].clear();
1002                                 calcedSections[i].clear();
1003                         }
1004 #ifdef ENABLE_PRIVATE_EPG
1005                         if (seenPrivateSections.empty())
1006 #endif
1007                         can_delete=1;
1008                 }
1009         }
1010         ++state;
1011 }
1012
1013 void eEPGCache::channel_data::startChannel()
1014 {
1015         updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1016
1017         int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (time(0)+eDVBLocalTimeHandler::getInstance()->difference()-It->second) * 1000 ) ) : ZAP_DELAY );
1018
1019         if (update < ZAP_DELAY)
1020                 update = ZAP_DELAY;
1021
1022         zapTimer.start(update, 1);
1023         if (update >= 60000)
1024                 eDebug("[EPGC] next update in %i min", update/60000);
1025         else if (update >= 1000)
1026                 eDebug("[EPGC] next update in %i sec", update/1000);
1027 }
1028
1029 void eEPGCache::channel_data::abortEPG()
1030 {
1031         for (int i=0; i < 3; ++i)
1032         {
1033                 seenSections[i].clear();
1034                 calcedSections[i].clear();
1035         }
1036         abortTimer.stop();
1037         zapTimer.stop();
1038         if (isRunning)
1039         {
1040                 eDebug("[EPGC] abort caching events !!");
1041                 if (isRunning & eEPGCache::SCHEDULE)
1042                 {
1043                         isRunning &= ~eEPGCache::SCHEDULE;
1044                         m_ScheduleReader->stop();
1045                         m_ScheduleConn=0;
1046                 }
1047                 if (isRunning & eEPGCache::NOWNEXT)
1048                 {
1049                         isRunning &= ~eEPGCache::NOWNEXT;
1050                         m_NowNextReader->stop();
1051                         m_NowNextConn=0;
1052                 }
1053                 if (isRunning & SCHEDULE_OTHER)
1054                 {
1055                         isRunning &= ~eEPGCache::SCHEDULE_OTHER;
1056                         m_ScheduleOtherReader->stop();
1057                         m_ScheduleOtherConn=0;
1058                 }
1059         }
1060 #ifdef ENABLE_PRIVATE_EPG
1061         if (m_PrivateReader)
1062                 m_PrivateReader->stop();
1063         if (m_PrivateConn)
1064                 m_PrivateConn=0;
1065 #endif
1066         can_delete=1;
1067 }
1068
1069 void eEPGCache::channel_data::readData( const __u8 *data)
1070 {
1071         if (!data)
1072                 eDebug("get Null pointer from section reader !!");
1073         else
1074         {
1075                 int source;
1076                 int map;
1077                 iDVBSectionReader *reader=NULL;
1078                 switch(data[0])
1079                 {
1080                         case 0x4E ... 0x4F:
1081                                 reader=m_NowNextReader;
1082                                 source=eEPGCache::NOWNEXT;
1083                                 map=0;
1084                                 break;
1085                         case 0x50 ... 0x5F:
1086                                 reader=m_ScheduleReader;
1087                                 source=eEPGCache::SCHEDULE;
1088                                 map=1;
1089                                 break;
1090                         case 0x60 ... 0x6F:
1091                                 reader=m_ScheduleOtherReader;
1092                                 source=eEPGCache::SCHEDULE_OTHER;
1093                                 map=2;
1094                                 break;
1095                         default:
1096                                 eDebug("[EPGC] unknown table_id !!!");
1097                                 return;
1098                 }
1099                 tidMap &seenSections = this->seenSections[map];
1100                 tidMap &calcedSections = this->calcedSections[map];
1101                 if ( state == 1 && calcedSections == seenSections || state > 1 )
1102                 {
1103                         eDebugNoNewLine("[EPGC] ");
1104                         switch (source)
1105                         {
1106                                 case eEPGCache::NOWNEXT:
1107                                         m_NowNextConn=0;
1108                                         eDebugNoNewLine("nownext");
1109                                         break;
1110                                 case eEPGCache::SCHEDULE:
1111                                         m_ScheduleConn=0;
1112                                         eDebugNoNewLine("schedule");
1113                                         break;
1114                                 case eEPGCache::SCHEDULE_OTHER:
1115                                         m_ScheduleOtherConn=0;
1116                                         eDebugNoNewLine("schedule other");
1117                                         break;
1118                                 default: eDebugNoNewLine("unknown");break;
1119                         }
1120                         eDebug(" finished(%d)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
1121                         if ( reader )
1122                                 reader->stop();
1123                         isRunning &= ~source;
1124                         if (!isRunning)
1125                                 finishEPG();
1126                 }
1127                 else
1128                 {
1129                         eit_t *eit = (eit_t*) data;
1130                         __u32 sectionNo = data[0] << 24;
1131                         sectionNo |= data[3] << 16;
1132                         sectionNo |= data[4] << 8;
1133                         sectionNo |= eit->section_number;
1134
1135                         tidMap::iterator it =
1136                                 seenSections.find(sectionNo);
1137
1138                         if ( it == seenSections.end() )
1139                         {
1140                                 seenSections.insert(sectionNo);
1141                                 calcedSections.insert(sectionNo);
1142                                 __u32 tmpval = sectionNo & 0xFFFFFF00;
1143                                 __u8 incr = source == NOWNEXT ? 1 : 8;
1144                                 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1145                                 {
1146                                         if ( i == eit->section_number )
1147                                         {
1148                                                 for (int x=i; x <= eit->segment_last_section_number; ++x)
1149                                                         calcedSections.insert(tmpval|(x&0xFF));
1150                                         }
1151                                         else
1152                                                 calcedSections.insert(tmpval|(i&0xFF));
1153                                 }
1154                                 cache->sectionRead(data, source, this);
1155                         }
1156                 }
1157         }
1158 }
1159
1160 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1161 // if t == -1 we search the current event...
1162 {
1163         singleLock s(cache_lock);
1164         uniqueEPGKey key(service);
1165
1166         // check if EPG for this service is ready...
1167         eventCache::iterator It = eventDB.find( key );
1168         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1169         {
1170                 if (t==-1)
1171                         t = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
1172                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1173                         It->second.second.upper_bound(t); // just >
1174                 if ( i != It->second.second.end() )
1175                 {
1176                         if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1177                         {
1178                                 timeMap::iterator x = i;
1179                                 --x;
1180                                 if ( x != It->second.second.end() )
1181                                 {
1182                                         time_t start_time = x->second->getStartTime();
1183                                         if (direction >= 0)
1184                                         {
1185                                                 if (t < start_time)
1186                                                         return -1;
1187                                                 if (t > (start_time+x->second->getDuration()))
1188                                                         return -1;
1189                                         }
1190                                         i = x;
1191                                 }
1192                                 else
1193                                         return -1;
1194                         }
1195                         result = i->second;
1196                         return 0;
1197                 }
1198         }
1199         return -1;
1200 }
1201
1202 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&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 = data->get();
1209         return ret;
1210 }
1211
1212 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& 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                 result = new Event((uint8_t*)data->get());
1219         return ret;
1220 }
1221
1222 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1223 {
1224         singleLock s(cache_lock);
1225         const eventData *data=0;
1226         RESULT ret = lookupEventTime(service, t, data, direction);
1227         if ( !ret && data )
1228         {
1229                 Event ev((uint8_t*)data->get());
1230                 result = new eServiceEvent();
1231                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1232                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1233         }
1234         return ret;
1235 }
1236
1237 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1238 {
1239         singleLock s(cache_lock);
1240         uniqueEPGKey key( service );
1241
1242         eventCache::iterator It = eventDB.find( key );
1243         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1244         {
1245                 eventMap::iterator i( It->second.first.find( event_id ));
1246                 if ( i != It->second.first.end() )
1247                 {
1248                         result = i->second;
1249                         return 0;
1250                 }
1251                 else
1252                 {
1253                         result = 0;
1254                         eDebug("event %04x not found in epgcache", event_id);
1255                 }
1256         }
1257         return -1;
1258 }
1259
1260 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&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 = data->get();
1267         return ret;
1268 }
1269
1270 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& 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                 result = new Event((uint8_t*)data->get());
1277         return ret;
1278 }
1279
1280 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1281 {
1282         singleLock s(cache_lock);
1283         const eventData *data=0;
1284         RESULT ret = lookupEventId(service, event_id, data);
1285         if ( !ret && data )
1286         {
1287                 Event ev((uint8_t*)data->get());
1288                 result = new eServiceEvent();
1289                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1290                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1291         }
1292         return ret;
1293 }
1294
1295 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1296 {
1297         eventCache::iterator It = eventDB.find( service );
1298         if ( It != eventDB.end() && It->second.second.size() )
1299         {
1300                 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1301                 if ( begin != -1 )
1302                 {
1303                         m_timemap_cursor = It->second.second.lower_bound(begin);
1304                         if ( m_timemap_cursor != It->second.second.end() )
1305                         {
1306                                 if ( m_timemap_cursor->second->getStartTime() != begin )
1307                                 {
1308                                         timeMap::iterator x = m_timemap_cursor;
1309                                         --x;
1310                                         if ( x != It->second.second.end() )
1311                                         {
1312                                                 time_t start_time = x->second->getStartTime();
1313                                                 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1314                                                         m_timemap_cursor = x;
1315                                         }
1316                                 }
1317                         }
1318                 }
1319                 else
1320                         m_timemap_cursor = It->second.second.begin();
1321                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1322                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1323                 return 0;
1324         }
1325         return -1;
1326 }
1327
1328 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1329 {
1330         if ( m_timemap_cursor != m_timemap_end )
1331         {
1332                 result = m_timemap_cursor++->second;
1333                 return 0;
1334         }
1335         return -1;
1336 }
1337
1338 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1339 {
1340         if ( m_timemap_cursor != m_timemap_end )
1341         {
1342                 result = m_timemap_cursor++->second->get();
1343                 return 0;
1344         }
1345         return -1;
1346 }
1347
1348 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1349 {
1350         if ( m_timemap_cursor != m_timemap_end )
1351         {
1352                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1353                 return 0;
1354         }
1355         return -1;
1356 }
1357
1358 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1359 {
1360         if ( m_timemap_cursor != m_timemap_end )
1361         {
1362                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1363                 result = new eServiceEvent();
1364                 return result->parseFrom(&ev, currentQueryTsidOnid);
1365         }
1366         return -1;
1367 }
1368
1369 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1370 {
1371         PyObject *tmp=NULL;
1372         int pos=0;
1373         while(pos < argcount)
1374         {
1375                 bool inc_refcount=false;
1376                 switch(argstring[pos])
1377                 {
1378                         case 'I': // Event Id
1379                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1380                                 break;
1381                         case 'B': // Event Begin Time
1382                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1383                                 break;
1384                         case 'D': // Event Duration
1385                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1386                                 break;
1387                         case 'T': // Event Title
1388                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1389                                 break;
1390                         case 'S': // Event Short Description
1391                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1392                                 break;
1393                         case 'E': // Event Extended Description
1394                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1395                                 break;
1396                         case 'C': // Current Time
1397                                 tmp = nowTime;
1398                                 inc_refcount = true;
1399                                 break;
1400                         case 'R': // service reference string
1401                                 tmp = service;
1402                                 inc_refcount = true;
1403                                 break;
1404                         case 'N': // service name
1405                                 tmp = service_name;
1406                                 inc_refcount = true;
1407                 }
1408                 if (!tmp)
1409                 {
1410                         tmp = Py_None;
1411                         inc_refcount = true;
1412                 }
1413                 if (inc_refcount)
1414                         Py_INCREF(tmp);
1415                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1416         }
1417 }
1418
1419 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1420 {
1421         if (convertFunc)
1422         {
1423                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1424                 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1425                 if (result == NULL)
1426                 {
1427                         if (service_name)
1428                                 Py_DECREF(service_name);
1429                         if (nowTime)
1430                                 Py_DECREF(nowTime);
1431                         Py_DECREF(convertFuncArgs);
1432                         Py_DECREF(dest_list);
1433                         return result;
1434                 }
1435                 PyList_Append(dest_list, result);
1436                 Py_DECREF(result);
1437         }
1438         else
1439         {
1440                 PyObject *tuple = PyTuple_New(argcount);
1441                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1442                 PyList_Append(dest_list, tuple);
1443                 Py_DECREF(tuple);
1444         }
1445         return 0;
1446 }
1447
1448 // here we get a list with tuples
1449 // first tuple entry is the servicereference
1450 // the second is the type of query (0 = time, 1 = event_id)
1451 // the third
1452 //              when type is eventid it is the event_id
1453 //              when type is time then it is the start_time ( 0 for now_time )
1454 // the fourth is the end_time .. ( optional )
1455
1456 /* argv is a python string
1457    I = Event Id
1458    B = Event Begin Time
1459    D = Event Duration
1460    T = Event Title
1461    S = Event Short Description
1462    E = Event Extended Description
1463    C = Current Time
1464    R = Service Reference
1465    N = Service Name
1466 */
1467
1468 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1469 {
1470         PyObject *convertFuncArgs=NULL;
1471         int argcount=0;
1472         char *argstring=NULL;
1473         if (!PyList_Check(list))
1474         {
1475                 PyErr_SetString(PyExc_StandardError,
1476                         "type error");
1477                 eDebug("no list");
1478                 return NULL;
1479         }
1480         int listIt=0;
1481         int listSize=PyList_Size(list);
1482         if (!listSize)
1483         {
1484                 PyErr_SetString(PyExc_StandardError,
1485                         "not params given");
1486                 eDebug("not params given");
1487                 return NULL;
1488         }
1489         else 
1490         {
1491                 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1492                 if (PyString_Check(argv))
1493                 {
1494                         argstring = PyString_AS_STRING(argv);
1495                         ++listIt;
1496                 }
1497                 else
1498                         argstring = "I"; // just event id as default
1499                 argcount = strlen(argstring);
1500 //              eDebug("have %d args('%s')", argcount, argstring);
1501         }
1502         if (convertFunc)
1503         {
1504                 if (!PyCallable_Check(convertFunc))
1505                 {
1506                         PyErr_SetString(PyExc_StandardError,
1507                                 "convertFunc must be callable");
1508                         eDebug("convertFunc is not callable");
1509                         return NULL;
1510                 }
1511                 convertFuncArgs = PyTuple_New(argcount);
1512         }
1513
1514         PyObject *nowTime = strchr(argstring, 'C') ?
1515                 PyLong_FromLong(time(0)+eDVBLocalTimeHandler::getInstance()->difference()) :
1516                 NULL;
1517
1518         bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1519
1520         // create dest list
1521         PyObject *dest_list=PyList_New(0);
1522         while(listSize > listIt)
1523         {
1524                 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1525                 if (PyTuple_Check(item))
1526                 {
1527                         int type=0;
1528                         long event_id=-1;
1529                         time_t stime=-1;
1530                         int minutes=0;
1531                         int tupleSize=PyTuple_Size(item);
1532                         int tupleIt=0;
1533                         PyObject *service=NULL;
1534                         while(tupleSize > tupleIt)  // parse query args
1535                         {
1536                                 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1537                                 switch(tupleIt++)
1538                                 {
1539                                         case 0:
1540                                         {
1541                                                 if (!PyString_Check(entry))
1542                                                 {
1543                                                         eDebug("tuple entry 0 is no a string");
1544                                                         goto skip_entry;
1545                                                 }
1546                                                 service = entry;
1547                                                 break;
1548                                         }
1549                                         case 1:
1550                                                 type=PyInt_AsLong(entry);
1551                                                 if (type < -1 || type > 2)
1552                                                 {
1553                                                         eDebug("unknown type %d", type);
1554                                                         goto skip_entry;
1555                                                 }
1556                                                 break;
1557                                         case 2:
1558                                                 event_id=stime=PyInt_AsLong(entry);
1559                                                 break;
1560                                         case 3:
1561                                                 minutes=PyInt_AsLong(entry);
1562                                                 break;
1563                                         default:
1564                                                 eDebug("unneeded extra argument");
1565                                                 break;
1566                                 }
1567                         }
1568                         eServiceReference ref(PyString_AS_STRING(service));
1569                         if (ref.type != eServiceReference::idDVB)
1570                         {
1571                                 eDebug("service reference for epg query is not valid");
1572                                 continue;
1573                         }
1574                         PyObject *service_name=NULL;
1575                         if (must_get_service_name)
1576                         {
1577                                 ePtr<iStaticServiceInformation> sptr;
1578                                 eServiceCenterPtr service_center;
1579                                 eServiceCenter::getPrivInstance(service_center);
1580                                 if (service_center)
1581                                 {
1582                                         service_center->info(ref, sptr);
1583                                         if (sptr)
1584                                         {
1585                                                 std::string name;
1586                                                 sptr->getName(ref, name);
1587                                                 if (name.length())
1588                                                         service_name = PyString_FromString(name.c_str());
1589                                         }
1590                                 }
1591                                 if (!service_name)
1592                                         service_name = PyString_FromString("<n/a>");
1593                         }
1594                         if (minutes)
1595                         {
1596                                 Lock();
1597                                 if (!startTimeQuery(ref, stime, minutes))
1598                                 {
1599                                         ePtr<eServiceEvent> ptr;
1600                                         while (!getNextTimeEntry(ptr))
1601                                         {
1602                                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1603                                                 if (ret)
1604                                                         return ret;
1605                                         }
1606                                 }
1607                                 Unlock();
1608                         }
1609                         else
1610                         {
1611                                 ePtr<eServiceEvent> ptr;
1612                                 if (stime)
1613                                 {
1614                                         if (type == 2)
1615                                                 lookupEventId(ref, event_id, ptr);
1616                                         else
1617                                                 lookupEventTime(ref, stime, ptr, type);
1618                                 }
1619                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1620                                 if (ret)
1621                                         return ret;
1622                         }
1623                         if (service_name)
1624                                 Py_DECREF(service_name);
1625                 }
1626 skip_entry:
1627                 ;
1628         }
1629         if (convertFuncArgs)
1630                 Py_DECREF(convertFuncArgs);
1631         if (nowTime)
1632                 Py_DECREF(nowTime);
1633         return dest_list;
1634 }
1635
1636 #ifdef ENABLE_PRIVATE_EPG
1637 #include <dvbsi++/descriptor_tag.h>
1638 #include <dvbsi++/unknown_descriptor.h>
1639 #include <dvbsi++/private_data_specifier_descriptor.h>
1640
1641 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
1642 {
1643         ePtr<eTable<ProgramMapSection> > ptr;
1644         if (!pmthandler->getPMT(ptr) && ptr)
1645         {
1646                 std::vector<ProgramMapSection*>::const_iterator i;
1647                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
1648                 {
1649                         const ProgramMapSection &pmt = **i;
1650
1651                         ElementaryStreamInfoConstIterator es;
1652                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
1653                         {
1654                                 int tmp=0;
1655                                 switch ((*es)->getType())
1656                                 {
1657                                 case 0x05: // private
1658                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
1659                                                 desc != (*es)->getDescriptors()->end(); ++desc)
1660                                         {
1661                                                 switch ((*desc)->getTag())
1662                                                 {
1663                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
1664                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
1665                                                                         tmp |= 1;
1666                                                                 break;
1667                                                         case 0x90:
1668                                                         {
1669                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
1670                                                                 int descr_len = descr->getLength();
1671                                                                 if (descr_len == 4)
1672                                                                 {
1673                                                                         uint8_t data[descr_len+2];
1674                                                                         descr->writeToBuffer(data);
1675                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
1676                                                                                 tmp |= 2;
1677                                                                 }
1678                                                                 break;
1679                                                         }
1680                                                         default:
1681                                                                 break;
1682                                                 }
1683                                         }
1684                                 default:
1685                                         break;
1686                                 }
1687                                 if (tmp==3)
1688                                 {
1689                                         eServiceReferenceDVB ref;
1690                                         if (!pmthandler->getService(ref))
1691                                         {
1692                                                 int pid = (*es)->getPid();
1693                                                 messages.send(Message(Message::got_private_pid, ref, pid));
1694                                                 return;
1695                                         }
1696                                 }
1697                         }
1698                 }
1699         }
1700         else
1701                 eDebug("PMTready but no pmt!!");
1702 }
1703
1704 struct date_time
1705 {
1706         __u8 data[5];
1707         time_t tm;
1708         date_time( const date_time &a )
1709         {
1710                 memcpy(data, a.data, 5);
1711                 tm = a.tm;
1712         }
1713         date_time( const __u8 data[5])
1714         {
1715                 memcpy(this->data, data, 5);
1716                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
1717         }
1718         date_time()
1719         {
1720         }
1721         const __u8& operator[](int pos) const
1722         {
1723                 return data[pos];
1724         }
1725 };
1726
1727 struct less_datetime
1728 {
1729         bool operator()( const date_time &a, const date_time &b ) const
1730         {
1731                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
1732         }
1733 };
1734
1735 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
1736 {
1737         contentMap &content_time_table = content_time_tables[current_service];
1738         singleLock s(cache_lock);
1739         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
1740         eventMap &evMap = eventDB[current_service].first;
1741         timeMap &tmMap = eventDB[current_service].second;
1742         int ptr=8;
1743         int content_id = data[ptr++] << 24;
1744         content_id |= data[ptr++] << 16;
1745         content_id |= data[ptr++] << 8;
1746         content_id |= data[ptr++];
1747
1748         contentTimeMap &time_event_map =
1749                 content_time_table[content_id];
1750         for ( contentTimeMap::iterator it( time_event_map.begin() );
1751                 it != time_event_map.end(); ++it )
1752         {
1753                 eventMap::iterator evIt( evMap.find(it->second.second) );
1754                 if ( evIt != evMap.end() )
1755                 {
1756                         delete evIt->second;
1757                         evMap.erase(evIt);
1758                 }
1759                 tmMap.erase(it->second.first);
1760         }
1761         time_event_map.clear();
1762
1763         __u8 duration[3];
1764         memcpy(duration, data+ptr, 3);
1765         ptr+=3;
1766         int duration_sec =
1767                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
1768
1769         const __u8 *descriptors[65];
1770         const __u8 **pdescr = descriptors;
1771
1772         int descriptors_length = (data[ptr++]&0x0F) << 8;
1773         descriptors_length |= data[ptr++];
1774         while ( descriptors_length > 0 )
1775         {
1776                 int descr_type = data[ptr];
1777                 int descr_len = data[ptr+1];
1778                 descriptors_length -= (descr_len+2);
1779                 if ( descr_type == 0xf2 )
1780                 {
1781                         ptr+=2;
1782                         int tsid = data[ptr++] << 8;
1783                         tsid |= data[ptr++];
1784                         int onid = data[ptr++] << 8;
1785                         onid |= data[ptr++];
1786                         int sid = data[ptr++] << 8;
1787                         sid |= data[ptr++];
1788                         uniqueEPGKey service( sid, onid, tsid );
1789                         descr_len -= 6;
1790                         while( descr_len > 0 )
1791                         {
1792                                 __u8 datetime[5];
1793                                 datetime[0] = data[ptr++];
1794                                 datetime[1] = data[ptr++];
1795                                 int tmp_len = data[ptr++];
1796                                 descr_len -= 3;
1797                                 while( tmp_len > 0 )
1798                                 {
1799                                         memcpy(datetime+2, data+ptr, 3);
1800                                         ptr+=3;
1801                                         descr_len -= 3;
1802                                         tmp_len -= 3;
1803                                         start_times[datetime].push_back(service);
1804                                 }
1805                         }
1806                 }
1807                 else
1808                 {
1809                         *pdescr++=data+ptr;
1810                         ptr += 2;
1811                         ptr += descr_len;
1812                 }
1813         }
1814         __u8 event[4098];
1815         eit_event_struct *ev_struct = (eit_event_struct*) event;
1816         ev_struct->running_status = 0;
1817         ev_struct->free_CA_mode = 1;
1818         memcpy(event+7, duration, 3);
1819         ptr = 12;
1820         const __u8 **d=descriptors;
1821         while ( d < pdescr )
1822         {
1823                 memcpy(event+ptr, *d, ((*d)[1])+2);
1824                 ptr+=(*d++)[1];
1825                 ptr+=2;
1826         }
1827         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
1828         {
1829                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
1830                 if ( (it->first.tm + duration_sec) < now )
1831                         continue;
1832                 memcpy(event+2, it->first.data, 5);
1833                 int bptr = ptr;
1834                 int cnt=0;
1835                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
1836                 {
1837                         event[bptr++] = 0x4A;
1838                         __u8 *len = event+(bptr++);
1839                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
1840                         event[bptr++] = (i->tsid & 0xFF);
1841                         event[bptr++] = (i->onid & 0xFF00) >> 8;
1842                         event[bptr++] = (i->onid & 0xFF);
1843                         event[bptr++] = (i->sid & 0xFF00) >> 8;
1844                         event[bptr++] = (i->sid & 0xFF);
1845                         event[bptr++] = 0xB0;
1846                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
1847                         *len = ((event+bptr) - len)-1;
1848                 }
1849                 int llen = bptr - 12;
1850                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
1851                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
1852
1853                 time_t stime = it->first.tm;
1854                 while( tmMap.find(stime) != tmMap.end() )
1855                         ++stime;
1856                 event[6] += (stime - it->first.tm);
1857                 __u16 event_id = 0;
1858                 while( evMap.find(event_id) != evMap.end() )
1859                         ++event_id;
1860                 event[0] = (event_id & 0xFF00) >> 8;
1861                 event[1] = (event_id & 0xFF);
1862                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
1863                 eventData *d = new eventData( ev_struct, bptr, eEPGCache::SCHEDULE );
1864                 evMap[event_id] = d;
1865                 tmMap[stime] = d;
1866         }
1867 }
1868
1869 void eEPGCache::channel_data::startPrivateReader(int pid, int version)
1870 {
1871         eDVBSectionFilterMask mask;
1872         memset(&mask, 0, sizeof(mask));
1873         mask.pid = pid;
1874         mask.flags = eDVBSectionFilterMask::rfCRC;
1875         mask.data[0] = 0xA0;
1876         mask.mask[0] = 0xFF;
1877         eDebug("start privatefilter for pid %04x and version %d", pid, version);
1878         if (version != -1)
1879         {
1880                 mask.data[3] = version << 1;
1881                 mask.mask[3] = 0x3E;
1882                 mask.mode[3] = 0x3E;
1883         }
1884         seenPrivateSections.clear();
1885         m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
1886         m_PrivateReader->start(mask);
1887 #ifdef NEED_DEMUX_WORKAROUND
1888         m_PrevVersion=version;
1889 #endif
1890 }
1891
1892 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
1893 {
1894         if (!data)
1895                 eDebug("get Null pointer from section reader !!");
1896         else
1897         {
1898                 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
1899                 {
1900 #ifdef NEED_DEMUX_WORKAROUND
1901                         int version = data[5];
1902                         version = ((version & 0x3E) >> 1);
1903                         can_delete = 0;
1904                         if ( m_PrevVersion != version )
1905                         {
1906                                 cache->privateSectionRead(m_PrivateService, data);
1907                                 seenPrivateSections.insert(data[6]);
1908                         }
1909                         else
1910                                 eDebug("ignore");
1911 #else
1912                         can_delete = 0;
1913                         cache->privateSectionRead(m_PrivateService, data);
1914                         seenPrivateSections.insert(data[6]);
1915 #endif
1916                 }
1917                 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
1918                 {
1919                         eDebug("[EPGC] private finished");
1920                         if (!isRunning)
1921                                 can_delete = 1;
1922                         int version = data[5];
1923                         version = ((version & 0x3E) >> 1);
1924                         startPrivateReader(m_PrivatePid, version);
1925                 }
1926         }
1927 }
1928
1929 #endif // ENABLE_PRIVATE_EPG