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