6a00b6be37634a66708224ada1819e7717f0ceeb
[enigma2.git] / lib / dvb / epgcache.cpp
1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
3
4 #undef EPG_DEBUG  
5
6 #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         channelMapIterator it =
212                 m_knownChannels.find(chan);
213         if ( it == m_knownChannels.end() )
214                 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
215         else
216         {
217                 channel_data &data = *it->second;
218                 ePtr<eDVBResourceManager> res_mgr;
219                 if ( eDVBResourceManager::getInstance( res_mgr ) )
220                         eDebug("[eEPGCache] no res manager!!");
221                 else
222                 {
223                         ePtr<iDVBDemux> demux;
224                         if ( data.channel->getDemux(demux, 0) )
225                         {
226                                 eDebug("[eEPGCache] no demux!!");
227                                 return;
228                         }
229                         else
230                         {
231                                 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
232                                 if ( res )
233                                 {
234                                         eDebug("[eEPGCache] couldnt initialize nownext reader!!");
235                                         return;
236                                 }
237
238                                 res = demux->createSectionReader( this, data.m_ScheduleReader );
239                                 if ( res )
240                                 {
241                                         eDebug("[eEPGCache] couldnt initialize schedule reader!!");
242                                         return;
243                                 }
244
245                                 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
246                                 if ( res )
247                                 {
248                                         eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
249                                         return;
250                                 }
251 #ifdef ENABLE_PRIVATE_EPG
252                                 res = demux->createSectionReader( this, data.m_PrivateReader );
253                                 if ( res )
254                                 {
255                                         eDebug("[eEPGCache] couldnt initialize private reader!!");
256                                         return;
257                                 }
258 #endif
259 #ifdef ENABLE_MHW_EPG
260                                 res = demux->createSectionReader( this, data.m_MHWReader );
261                                 if ( res )
262                                 {
263                                         eDebug("[eEPGCache] couldnt initialize mhw reader!!");
264                                         return;
265                                 }
266 #endif
267                                 messages.send(Message(Message::startChannel, chan));
268                                 // -> gotMessage -> changedService
269                         }
270                 }
271         }
272 }
273
274 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
275 {
276         channelMapIterator it =
277                 m_knownChannels.find(chan);
278         if ( it != m_knownChannels.end() )
279         {
280                 int state=0;
281                 chan->getState(state);
282                 if ( it->second->prevChannelState != state )
283                 {
284                         switch (state)
285                         {
286                                 case iDVBChannel::state_ok:
287                                 {
288                                         eDebug("[eEPGCache] channel %p running", chan);
289                                         DVBChannelRunning(chan);
290                                         break;
291                                 }
292                                 case iDVBChannel::state_release:
293                                 {
294                                         eDebug("[eEPGCache] remove channel %p", chan);
295                                         messages.send(Message(Message::leaveChannel, chan));
296                                         pthread_mutex_lock(&it->second->channel_active);
297                                         singleLock s(channel_map_lock);
298                                         m_knownChannels.erase(it);
299                                         pthread_mutex_unlock(&it->second->channel_active);
300                                         delete it->second;
301                                         it->second=0;
302                                         // -> gotMessage -> abortEPG
303                                         break;
304                                 }
305                                 default: // ignore all other events
306                                         return;
307                         }
308                         if (it->second)
309                                 it->second->prevChannelState = state;
310                 }
311         }
312 }
313
314 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
315 {
316         timeMap::iterator tmp = tm_it;
317         while ((tmp->first+tmp->second->getDuration()-300) > TM)
318         {
319                 if(tmp->first != TM && tmp->second->type != PRIVATE)
320                 {
321                         __u16 event_id = tmp->second->getEventID();
322                         servicemap.first.erase(event_id);
323 #ifdef EPG_DEBUG
324                         Event evt((uint8_t*)tmp->second->get());
325                         eServiceEvent event;
326                         event.parseFrom(&evt, service.sid<<16|service.onid);
327                         eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
328                                 service.sid, event_id,
329                                 event.getBeginTimeString().c_str(),
330                                 event.getEventName().c_str(),
331                                 event.getExtendedDescription().c_str());
332 #endif
333                         delete tmp->second;
334                         if (tmp == servicemap.second.begin())
335                         {
336                                 servicemap.second.erase(tmp);
337                                 break;
338                         }
339                         else
340                                 servicemap.second.erase(tmp--);
341                 }
342                 else
343                 {
344                         if (tmp == servicemap.second.begin())
345                                 break;
346                         --tmp;
347                 }
348         }
349
350         tmp = tm_it;
351         while(tmp->first < (TM+duration-300))
352         {
353                 if (tmp->first != TM && tmp->second->type != PRIVATE)
354                 {
355                         __u16 event_id = tmp->second->getEventID();
356                         servicemap.first.erase(event_id);
357 #ifdef EPG_DEBUG  
358                         Event evt((uint8_t*)tmp->second->get());
359                         eServiceEvent event;
360                         event.parseFrom(&evt, service.sid<<16|service.onid);
361                         eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
362                                 service.sid, event_id,
363                                 event.getBeginTimeString().c_str(),
364                                 event.getEventName().c_str(),
365                                 event.getExtendedDescription().c_str());
366 #endif
367                         delete tmp->second;
368                         servicemap.second.erase(tmp++);
369                 }
370                 else
371                         ++tmp;
372                 if (tmp == servicemap.second.end())
373                         break;
374         }
375 }
376
377 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
378 {
379         eit_t *eit = (eit_t*) data;
380
381         int len=HILO(eit->section_length)-1;//+3-4;
382         int ptr=EIT_SIZE;
383         if ( ptr >= len )
384                 return;
385
386         // This fixed the EPG on the Multichoice irdeto systems
387         // the EIT packet is non-compliant.. their EIT packet stinks
388         if ( data[ptr-1] < 0x40 )
389                 --ptr;
390
391         uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
392         eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
393         int eit_event_size;
394         int duration;
395
396         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);
397         time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
398
399         if ( TM != 3599 && TM > -1)
400                 channel->haveData |= source;
401
402         singleLock s(cache_lock);
403         // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
404         // oder eine durch [] erzeugte
405         std::pair<eventMap,timeMap> &servicemap = eventDB[service];
406         eventMap::iterator prevEventIt = servicemap.first.end();
407         timeMap::iterator prevTimeIt = servicemap.second.end();
408
409         while (ptr<len)
410         {
411                 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
412
413                 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
414                 TM = parseDVBtime(
415                         eit_event->start_time_1,
416                         eit_event->start_time_2,
417                         eit_event->start_time_3,
418                         eit_event->start_time_4,
419                         eit_event->start_time_5);
420
421                 if ( TM == 3599 )
422                         goto next;
423
424                 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
425                         goto next;
426
427                 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ )  // old events should not be cached
428                 {
429                         __u16 event_id = HILO(eit_event->event_id);
430 //                      eDebug("event_id is %d sid is %04x", event_id, service.sid);
431
432                         eventData *evt = 0;
433                         int ev_erase_count = 0;
434                         int tm_erase_count = 0;
435
436                         // search in eventmap
437                         eventMap::iterator ev_it =
438                                 servicemap.first.find(event_id);
439
440                         // entry with this event_id is already exist ?
441                         if ( ev_it != servicemap.first.end() )
442                         {
443                                 if ( source > ev_it->second->type )  // update needed ?
444                                         goto next; // when not.. then skip this entry
445
446                                 // search this event in timemap
447                                 timeMap::iterator tm_it_tmp =
448                                         servicemap.second.find(ev_it->second->getStartTime());
449
450                                 if ( tm_it_tmp != servicemap.second.end() )
451                                 {
452                                         if ( tm_it_tmp->first == TM ) // just update eventdata
453                                         {
454                                                 // exempt memory
455                                                 delete ev_it->second;
456                                                 ev_it->second = tm_it_tmp->second =
457                                                         new eventData(eit_event, eit_event_size, source);
458                                                 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
459                                                 goto next;
460                                         }
461                                         else  // event has new event begin time
462                                         {
463                                                 tm_erase_count++;
464                                                 // delete the found record from timemap
465                                                 servicemap.second.erase(tm_it_tmp);
466                                                 prevTimeIt=servicemap.second.end();
467                                         }
468                                 }
469                         }
470
471                         // search in timemap, for check of a case if new time has coincided with time of other event
472                         // or event was is not found in eventmap
473                         timeMap::iterator tm_it =
474                                 servicemap.second.find(TM);
475
476                         if ( tm_it != servicemap.second.end() )
477                         {
478                                 // event with same start time but another event_id...
479                                 if ( source > tm_it->second->type &&
480                                         ev_it == servicemap.first.end() )
481                                         goto next; // when not.. then skip this entry
482
483                                 // search this time in eventmap
484                                 eventMap::iterator ev_it_tmp =
485                                         servicemap.first.find(tm_it->second->getEventID());
486
487                                 if ( ev_it_tmp != servicemap.first.end() )
488                                 {
489                                         ev_erase_count++;
490                                         // delete the found record from eventmap
491                                         servicemap.first.erase(ev_it_tmp);
492                                         prevEventIt=servicemap.first.end();
493                                 }
494                         }
495
496                         evt = new eventData(eit_event, eit_event_size, source);
497 #ifdef EPG_DEBUG
498                         bool consistencyCheck=true;
499 #endif
500                         if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
501                         {
502                                 // exempt memory
503                                 delete ev_it->second;
504                                 delete tm_it->second;
505                                 ev_it->second=evt;
506                                 tm_it->second=evt;
507                         }
508                         else if (ev_erase_count == 0 && tm_erase_count > 0)
509                         {
510                                 // exempt memory
511                                 delete ev_it->second;
512                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
513                                 ev_it->second=evt;
514                         }
515                         else if (ev_erase_count > 0 && tm_erase_count == 0)
516                         {
517                                 // exempt memory
518                                 delete tm_it->second;
519                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
520                                 tm_it->second=evt;
521                         }
522                         else // added new eventData
523                         {
524 #ifdef EPG_DEBUG
525                                 consistencyCheck=false;
526 #endif
527                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
528                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
529                         }
530
531                         FixOverlapping(servicemap, TM, duration, tm_it, service);
532
533 #ifdef EPG_DEBUG
534                         if ( consistencyCheck )
535                         {
536                                 if ( tm_it->second != evt || ev_it->second != evt )
537                                         eFatal("tm_it->second != ev_it->second");
538                                 else if ( tm_it->second->getStartTime() != tm_it->first )
539                                         eFatal("event start_time(%d) non equal timemap key(%d)",
540                                                 tm_it->second->getStartTime(), tm_it->first );
541                                 else if ( tm_it->first != TM )
542                                         eFatal("timemap key(%d) non equal TM(%d)",
543                                                 tm_it->first, TM);
544                                 else if ( ev_it->second->getEventID() != ev_it->first )
545                                         eFatal("event_id (%d) non equal event_map key(%d)",
546                                                 ev_it->second->getEventID(), ev_it->first);
547                                 else if ( ev_it->first != event_id )
548                                         eFatal("eventmap key(%d) non equal event_id(%d)",
549                                                 ev_it->first, event_id );
550                         }
551 #endif
552                 }
553 next:
554 #ifdef EPG_DEBUG
555                 if ( servicemap.first.size() != servicemap.second.size() )
556                 {
557                         FILE *f = fopen("/hdd/event_map.txt", "w+");
558                         int i=0;
559                         for (eventMap::iterator it(servicemap.first.begin())
560                                 ; it != servicemap.first.end(); ++it )
561                                 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
562                                         i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
563                         fclose(f);
564                         f = fopen("/hdd/time_map.txt", "w+");
565                         i=0;
566                         for (timeMap::iterator it(servicemap.second.begin())
567                                 ; it != servicemap.second.end(); ++it )
568                                         fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
569                                                 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
570                         fclose(f);
571
572                         eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d", 
573                                 service.sid, service.tsid, service.onid, 
574                                 servicemap.first.size(), servicemap.second.size() );
575                 }
576 #endif
577                 ptr += eit_event_size;
578                 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
579         }
580 }
581
582 void eEPGCache::flushEPG(const uniqueEPGKey & s)
583 {
584         eDebug("[EPGC] flushEPG %d", (int)(bool)s);
585         singleLock l(cache_lock);
586         if (s)  // clear only this service
587         {
588                 eventCache::iterator it = eventDB.find(s);
589                 if ( it != eventDB.end() )
590                 {
591                         eventMap &evMap = it->second.first;
592                         timeMap &tmMap = it->second.second;
593                         tmMap.clear();
594                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
595                                 delete i->second;
596                         evMap.clear();
597                         eventDB.erase(it);
598
599                         // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
600 #ifdef ENABLE_PRIVATE_EPG
601                         contentMaps::iterator it =
602                                 content_time_tables.find(s);
603                         if ( it != content_time_tables.end() )
604                         {
605                                 it->second.clear();
606                                 content_time_tables.erase(it);
607                         }
608 #endif
609                 }
610         }
611         else // clear complete EPG Cache
612         {
613                 for (eventCache::iterator it(eventDB.begin());
614                         it != eventDB.end(); ++it)
615                 {
616                         eventMap &evMap = it->second.first;
617                         timeMap &tmMap = it->second.second;
618                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
619                                 delete i->second;
620                         evMap.clear();
621                         tmMap.clear();
622                 }
623                 eventDB.clear();
624 #ifdef ENABLE_PRIVATE_EPG
625                 content_time_tables.clear();
626 #endif
627                 channelLastUpdated.clear();
628                 singleLock m(channel_map_lock);
629                 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
630                         it->second->startEPG();
631         }
632         eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
633 }
634
635 void eEPGCache::cleanLoop()
636 {
637         singleLock s(cache_lock);
638         if (!eventDB.empty())
639         {
640                 eDebug("[EPGC] start cleanloop");
641
642                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
643
644                 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
645                 {
646                         bool updated = false;
647                         for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
648                         {
649                                 if ( now > (It->first+It->second->getDuration()) )  // outdated normal entry (nvod references to)
650                                 {
651                                         // remove entry from eventMap
652                                         eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
653                                         if ( b != DBIt->second.first.end() )
654                                         {
655                                                 // release Heap Memory for this entry   (new ....)
656 //                                              eDebug("[EPGC] delete old event (evmap)");
657                                                 DBIt->second.first.erase(b);
658                                         }
659
660                                         // remove entry from timeMap
661 //                                      eDebug("[EPGC] release heap mem");
662                                         delete It->second;
663                                         DBIt->second.second.erase(It++);
664 //                                      eDebug("[EPGC] delete old event (timeMap)");
665                                         updated = true;
666                                 }
667                                 else
668                                         ++It;
669                         }
670 #ifdef ENABLE_PRIVATE_EPG
671                         if ( updated )
672                         {
673                                 contentMaps::iterator x =
674                                         content_time_tables.find( DBIt->first );
675                                 if ( x != content_time_tables.end() )
676                                 {
677                                         timeMap &tmMap = eventDB[DBIt->first].second;
678                                         for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
679                                         {
680                                                 for ( contentTimeMap::iterator it(i->second.begin());
681                                                         it != i->second.end(); )
682                                                 {
683                                                         if ( tmMap.find(it->second.first) == tmMap.end() )
684                                                                 i->second.erase(it++);
685                                                         else
686                                                                 ++it;
687                                                 }
688                                                 if ( i->second.size() )
689                                                         ++i;
690                                                 else
691                                                         x->second.erase(i++);
692                                         }
693                                 }
694                         }
695 #endif
696                 }
697                 eDebug("[EPGC] stop cleanloop");
698                 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
699         }
700         cleanTimer.start(CLEAN_INTERVAL,true);
701 }
702
703 eEPGCache::~eEPGCache()
704 {
705         messages.send(Message::quit);
706         kill(); // waiting for thread shutdown
707         singleLock s(cache_lock);
708         for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
709                 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
710                         delete It->second;
711 }
712
713 void eEPGCache::gotMessage( const Message &msg )
714 {
715         switch (msg.type)
716         {
717                 case Message::flush:
718                         flushEPG(msg.service);
719                         break;
720                 case Message::startChannel:
721                 {
722                         singleLock s(channel_map_lock);
723                         channelMapIterator channel =
724                                 m_knownChannels.find(msg.channel);
725                         if ( channel != m_knownChannels.end() )
726                                 channel->second->startChannel();
727                         break;
728                 }
729                 case Message::leaveChannel:
730                 {
731                         singleLock s(channel_map_lock);
732                         channelMapIterator channel =
733                                 m_knownChannels.find(msg.channel);
734                         if ( channel != m_knownChannels.end() )
735                                 channel->second->abortEPG();
736                         break;
737                 }
738                 case Message::quit:
739                         quit(0);
740                         break;
741 #ifdef ENABLE_PRIVATE_EPG
742                 case Message::got_private_pid:
743                 {
744                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
745                         {
746                                 eDVBChannel *channel = (eDVBChannel*) it->first;
747                                 channel_data *data = it->second;
748                                 eDVBChannelID chid = channel->getChannelID();
749                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
750                                         chid.original_network_id.get() == msg.service.onid &&
751                                         data->m_PrivatePid == -1 )
752                                 {
753                                         data->m_PrevVersion = -1;
754                                         data->m_PrivatePid = msg.pid;
755                                         data->m_PrivateService = msg.service;
756                                         updateMap::iterator It = channelLastUpdated.find( channel->getChannelID() );
757                                         int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
758                                         if (update < ZAP_DELAY)
759                                                 update = ZAP_DELAY;
760                                         data->startPrivateTimer.start(update, 1);
761                                         if (update >= 60000)
762                                                 eDebug("[EPGC] next private update in %i min", update/60000);
763                                         else if (update >= 1000)
764                                                 eDebug("[EPGC] next private update in %i sec", update/1000);
765                                         break;
766                                 }
767                         }
768                         break;
769                 }
770 #endif
771                 case Message::timeChanged:
772                         cleanLoop();
773                         break;
774                 default:
775                         eDebug("unhandled EPGCache Message!!");
776                         break;
777         }
778 }
779
780 void eEPGCache::thread()
781 {
782         hasStarted();
783         nice(4);
784         load();
785         cleanLoop();
786         runLoop();
787         save();
788 }
789
790 void eEPGCache::load()
791 {
792         singleLock s(cache_lock);
793         FILE *f = fopen("/hdd/epg.dat", "r");
794         if (f)
795         {
796                 int size=0;
797                 int cnt=0;
798 #if 0
799                 unsigned char md5_saved[16];
800                 unsigned char md5[16];
801                 bool md5ok=false;
802
803                 if (!md5_file("/hdd/epg.dat", 1, md5))
804                 {
805                         FILE *f = fopen("/hdd/epg.dat.md5", "r");
806                         if (f)
807                         {
808                                 fread( md5_saved, 16, 1, f);
809                                 fclose(f);
810                                 if ( !memcmp(md5_saved, md5, 16) )
811                                         md5ok=true;
812                         }
813                 }
814                 if ( md5ok )
815 #endif
816                 {
817                         unsigned int magic=0;
818                         fread( &magic, sizeof(int), 1, f);
819                         if (magic != 0x98765432)
820                         {
821                                 eDebug("epg file has incorrect byte order.. dont read it");
822                                 fclose(f);
823                                 return;
824                         }
825                         char text1[13];
826                         fread( text1, 13, 1, f);
827                         if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
828                         {
829                                 fread( &size, sizeof(int), 1, f);
830                                 while(size--)
831                                 {
832                                         uniqueEPGKey key;
833                                         eventMap evMap;
834                                         timeMap tmMap;
835                                         int size=0;
836                                         fread( &key, sizeof(uniqueEPGKey), 1, f);
837                                         fread( &size, sizeof(int), 1, f);
838                                         while(size--)
839                                         {
840                                                 __u8 len=0;
841                                                 __u8 type=0;
842                                                 eventData *event=0;
843                                                 fread( &type, sizeof(__u8), 1, f);
844                                                 fread( &len, sizeof(__u8), 1, f);
845                                                 event = new eventData(0, len, type);
846                                                 event->EITdata = new __u8[len];
847                                                 eventData::CacheSize+=len;
848                                                 fread( event->EITdata, len, 1, f);
849                                                 evMap[ event->getEventID() ]=event;
850                                                 tmMap[ event->getStartTime() ]=event;
851                                                 ++cnt;
852                                         }
853                                         eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
854                                 }
855                                 eventData::load(f);
856                                 eDebug("%d events read from /hdd/epg.dat", cnt);
857 #ifdef ENABLE_PRIVATE_EPG
858                                 char text2[11];
859                                 fread( text2, 11, 1, f);
860                                 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
861                                 {
862                                         size=0;
863                                         fread( &size, sizeof(int), 1, f);
864                                         while(size--)
865                                         {
866                                                 int size=0;
867                                                 uniqueEPGKey key;
868                                                 fread( &key, sizeof(uniqueEPGKey), 1, f);
869                                                 eventMap &evMap=eventDB[key].first;
870                                                 fread( &size, sizeof(int), 1, f);
871                                                 while(size--)
872                                                 {
873                                                         int size;
874                                                         int content_id;
875                                                         fread( &content_id, sizeof(int), 1, f);
876                                                         fread( &size, sizeof(int), 1, f);
877                                                         while(size--)
878                                                         {
879                                                                 time_t time1, time2;
880                                                                 __u16 event_id;
881                                                                 fread( &time1, sizeof(time_t), 1, f);
882                                                                 fread( &time2, sizeof(time_t), 1, f);
883                                                                 fread( &event_id, sizeof(__u16), 1, f);
884                                                                 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
885                                                                 eventMap::iterator it =
886                                                                         evMap.find(event_id);
887                                                                 if (it != evMap.end())
888                                                                         it->second->type = PRIVATE;
889                                                         }
890                                                 }
891                                         }
892                                 }
893 #endif // ENABLE_PRIVATE_EPG
894                         }
895                         else
896                                 eDebug("[EPGC] don't read old epg database");
897                         fclose(f);
898                 }
899         }
900 }
901
902 void eEPGCache::save()
903 {
904         struct statfs s;
905         off64_t tmp;
906         if (statfs("/hdd", &s)<0)
907                 tmp=0;
908         else
909         {
910                 tmp=s.f_blocks;
911                 tmp*=s.f_bsize;
912         }
913
914         // prevent writes to builtin flash
915         if ( tmp < 1024*1024*50 ) // storage size < 50MB
916                 return;
917
918         // check for enough free space on storage
919         tmp=s.f_bfree;
920         tmp*=s.f_bsize;
921         if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
922                 return;
923
924         FILE *f = fopen("/hdd/epg.dat", "w");
925         int cnt=0;
926         if ( f )
927         {
928                 unsigned int magic = 0x98765432;
929                 fwrite( &magic, sizeof(int), 1, f);
930                 const char *text = "ENIGMA_EPG_V5";
931                 fwrite( text, 13, 1, f );
932                 int size = eventDB.size();
933                 fwrite( &size, sizeof(int), 1, f );
934                 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
935                 {
936                         timeMap &timemap = service_it->second.second;
937                         fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
938                         size = timemap.size();
939                         fwrite( &size, sizeof(int), 1, f);
940                         for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
941                         {
942                                 __u8 len = time_it->second->ByteSize;
943                                 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
944                                 fwrite( &len, sizeof(__u8), 1, f);
945                                 fwrite( time_it->second->EITdata, len, 1, f);
946                                 ++cnt;
947                         }
948                 }
949                 eDebug("%d events written to /hdd/epg.dat", cnt);
950                 eventData::save(f);
951 #ifdef ENABLE_PRIVATE_EPG
952                 const char* text3 = "PRIVATE_EPG";
953                 fwrite( text3, 11, 1, f );
954                 size = content_time_tables.size();
955                 fwrite( &size, sizeof(int), 1, f);
956                 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
957                 {
958                         contentMap &content_time_table = a->second;
959                         fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
960                         int size = content_time_table.size();
961                         fwrite( &size, sizeof(int), 1, f);
962                         for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
963                         {
964                                 int size = i->second.size();
965                                 fwrite( &i->first, sizeof(int), 1, f);
966                                 fwrite( &size, sizeof(int), 1, f);
967                                 for ( contentTimeMap::iterator it(i->second.begin());
968                                         it != i->second.end(); ++it )
969                                 {
970                                         fwrite( &it->first, sizeof(time_t), 1, f);
971                                         fwrite( &it->second.first, sizeof(time_t), 1, f);
972                                         fwrite( &it->second.second, sizeof(__u16), 1, f);
973                                 }
974                         }
975                 }
976 #endif
977                 fclose(f);
978 #if 0
979                 unsigned char md5[16];
980                 if (!md5_file("/hdd/epg.dat", 1, md5))
981                 {
982                         FILE *f = fopen("/hdd/epg.dat.md5", "w");
983                         if (f)
984                         {
985                                 fwrite( md5, 16, 1, f);
986                                 fclose(f);
987                         }
988                 }
989 #endif
990         }
991 }
992
993 eEPGCache::channel_data::channel_data(eEPGCache *ml)
994         :cache(ml)
995         ,abortTimer(ml), zapTimer(ml), state(0)
996         ,isRunning(0), haveData(0)
997 #ifdef ENABLE_PRIVATE_EPG
998         ,startPrivateTimer(ml)
999 #endif
1000 #ifdef ENABLE_MHW_EPG
1001         ,m_MHWTimeoutTimer(ml)
1002 #endif
1003 {
1004 #ifdef ENABLE_MHW_EPG
1005         CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1006 #endif
1007         CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1008         CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1009 #ifdef ENABLE_PRIVATE_EPG
1010         CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1011 #endif
1012         pthread_mutex_init(&channel_active, 0);
1013 }
1014
1015 bool eEPGCache::channel_data::finishEPG()
1016 {
1017         if (!isRunning)  // epg ready
1018         {
1019                 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1020                 zapTimer.start(UPDATE_INTERVAL, 1);
1021                 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1022                 for (int i=0; i < 3; ++i)
1023                 {
1024                         seenSections[i].clear();
1025                         calcedSections[i].clear();
1026                 }
1027                 singleLock l(cache->cache_lock);
1028                 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1029 #ifdef ENABLE_MHW_EPG
1030                 cleanup();
1031 #endif
1032                 return true;
1033         }
1034         return false;
1035 }
1036
1037 void eEPGCache::channel_data::startEPG()
1038 {
1039         eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1040         state=0;
1041         haveData=0;
1042         for (int i=0; i < 3; ++i)
1043         {
1044                 seenSections[i].clear();
1045                 calcedSections[i].clear();
1046         }
1047
1048         eDVBSectionFilterMask mask;
1049         memset(&mask, 0, sizeof(mask));
1050
1051 #ifdef ENABLE_MHW_EPG
1052         mask.pid = 0xD3;
1053         mask.data[0] = 0x91;
1054         mask.mask[0] = 0xFF;
1055         m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1056         m_MHWReader->start(mask);
1057         isRunning |= MHW;
1058         memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1059 #endif
1060
1061         mask.pid = 0x12;
1062         mask.flags = eDVBSectionFilterMask::rfCRC;
1063
1064         mask.data[0] = 0x4E;
1065         mask.mask[0] = 0xFE;
1066         m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1067         m_NowNextReader->start(mask);
1068         isRunning |= NOWNEXT;
1069
1070         mask.data[0] = 0x50;
1071         mask.mask[0] = 0xF0;
1072         m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1073         m_ScheduleReader->start(mask);
1074         isRunning |= SCHEDULE;
1075
1076         mask.data[0] = 0x60;
1077         mask.mask[0] = 0xF0;
1078         m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1079         m_ScheduleOtherReader->start(mask);
1080         isRunning |= SCHEDULE_OTHER;
1081
1082         abortTimer.start(7000,true);
1083 }
1084
1085 void eEPGCache::channel_data::abortNonAvail()
1086 {
1087         if (!state)
1088         {
1089                 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1090                 {
1091                         eDebug("[EPGC] abort non avail nownext reading");
1092                         isRunning &= ~NOWNEXT;
1093                         m_NowNextReader->stop();
1094                         m_NowNextConn=0;
1095                 }
1096                 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1097                 {
1098                         eDebug("[EPGC] abort non avail schedule reading");
1099                         isRunning &= ~SCHEDULE;
1100                         m_ScheduleReader->stop();
1101                         m_ScheduleConn=0;
1102                 }
1103                 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1104                 {
1105                         eDebug("[EPGC] abort non avail schedule_other reading");
1106                         isRunning &= ~SCHEDULE_OTHER;
1107                         m_ScheduleOtherReader->stop();
1108                         m_ScheduleOtherConn=0;
1109                 }
1110 #ifdef ENABLE_MHW_EPG
1111                 if ( !(haveData&MHW) && (isRunning&MHW) )
1112                 {
1113                         eDebug("[EPGC] abort non avail mhw reading");
1114                         isRunning &= ~MHW;
1115                         m_MHWReader->stop();
1116                         m_MHWConn=0;
1117                 }
1118 #endif
1119                 if ( isRunning )
1120                         abortTimer.start(90000, true);
1121                 else
1122                 {
1123                         ++state;
1124                         for (int i=0; i < 3; ++i)
1125                         {
1126                                 seenSections[i].clear();
1127                                 calcedSections[i].clear();
1128                         }
1129                 }
1130         }
1131         ++state;
1132 }
1133
1134 void eEPGCache::channel_data::startChannel()
1135 {
1136         pthread_mutex_lock(&channel_active);
1137         updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1138
1139         int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1140
1141         if (update < ZAP_DELAY)
1142                 update = ZAP_DELAY;
1143
1144         zapTimer.start(update, 1);
1145         if (update >= 60000)
1146                 eDebug("[EPGC] next update in %i min", update/60000);
1147         else if (update >= 1000)
1148                 eDebug("[EPGC] next update in %i sec", update/1000);
1149 }
1150
1151 void eEPGCache::channel_data::abortEPG()
1152 {
1153         for (int i=0; i < 3; ++i)
1154         {
1155                 seenSections[i].clear();
1156                 calcedSections[i].clear();
1157         }
1158         abortTimer.stop();
1159         zapTimer.stop();
1160         if (isRunning)
1161         {
1162                 eDebug("[EPGC] abort caching events !!");
1163                 if (isRunning & SCHEDULE)
1164                 {
1165                         isRunning &= ~SCHEDULE;
1166                         m_ScheduleReader->stop();
1167                         m_ScheduleConn=0;
1168                 }
1169                 if (isRunning & NOWNEXT)
1170                 {
1171                         isRunning &= ~NOWNEXT;
1172                         m_NowNextReader->stop();
1173                         m_NowNextConn=0;
1174                 }
1175                 if (isRunning & SCHEDULE_OTHER)
1176                 {
1177                         isRunning &= ~SCHEDULE_OTHER;
1178                         m_ScheduleOtherReader->stop();
1179                         m_ScheduleOtherConn=0;
1180                 }
1181 #ifdef ENABLE_MHW_EPG
1182                 if (isRunning & MHW)
1183                 {
1184                         isRunning &= ~MHW;
1185                         m_MHWReader->stop();
1186                         m_MHWConn=0;
1187                 }
1188 #endif
1189         }
1190 #ifdef ENABLE_PRIVATE_EPG
1191         if (m_PrivateReader)
1192                 m_PrivateReader->stop();
1193         if (m_PrivateConn)
1194                 m_PrivateConn=0;
1195 #endif
1196         pthread_mutex_unlock(&channel_active);
1197 }
1198
1199 void eEPGCache::channel_data::readData( const __u8 *data)
1200 {
1201         if (!data)
1202                 eDebug("get Null pointer from section reader !!");
1203         else
1204         {
1205                 int source;
1206                 int map;
1207                 iDVBSectionReader *reader=NULL;
1208                 switch(data[0])
1209                 {
1210                         case 0x4E ... 0x4F:
1211                                 reader=m_NowNextReader;
1212                                 source=NOWNEXT;
1213                                 map=0;
1214                                 break;
1215                         case 0x50 ... 0x5F:
1216                                 reader=m_ScheduleReader;
1217                                 source=SCHEDULE;
1218                                 map=1;
1219                                 break;
1220                         case 0x60 ... 0x6F:
1221                                 reader=m_ScheduleOtherReader;
1222                                 source=SCHEDULE_OTHER;
1223                                 map=2;
1224                                 break;
1225                         default:
1226                                 eDebug("[EPGC] unknown table_id !!!");
1227                                 return;
1228                 }
1229                 tidMap &seenSections = this->seenSections[map];
1230                 tidMap &calcedSections = this->calcedSections[map];
1231                 if ( state == 1 && calcedSections == seenSections || state > 1 )
1232                 {
1233                         eDebugNoNewLine("[EPGC] ");
1234                         switch (source)
1235                         {
1236                                 case NOWNEXT:
1237                                         m_NowNextConn=0;
1238                                         eDebugNoNewLine("nownext");
1239                                         break;
1240                                 case SCHEDULE:
1241                                         m_ScheduleConn=0;
1242                                         eDebugNoNewLine("schedule");
1243                                         break;
1244                                 case SCHEDULE_OTHER:
1245                                         m_ScheduleOtherConn=0;
1246                                         eDebugNoNewLine("schedule other");
1247                                         break;
1248                                 default: eDebugNoNewLine("unknown");break;
1249                         }
1250                         eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1251                         if ( reader )
1252                                 reader->stop();
1253                         isRunning &= ~source;
1254                         if (!isRunning)
1255                                 finishEPG();
1256                 }
1257                 else
1258                 {
1259                         eit_t *eit = (eit_t*) data;
1260                         __u32 sectionNo = data[0] << 24;
1261                         sectionNo |= data[3] << 16;
1262                         sectionNo |= data[4] << 8;
1263                         sectionNo |= eit->section_number;
1264
1265                         tidMap::iterator it =
1266                                 seenSections.find(sectionNo);
1267
1268                         if ( it == seenSections.end() )
1269                         {
1270                                 seenSections.insert(sectionNo);
1271                                 calcedSections.insert(sectionNo);
1272                                 __u32 tmpval = sectionNo & 0xFFFFFF00;
1273                                 __u8 incr = source == NOWNEXT ? 1 : 8;
1274                                 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1275                                 {
1276                                         if ( i == eit->section_number )
1277                                         {
1278                                                 for (int x=i; x <= eit->segment_last_section_number; ++x)
1279                                                         calcedSections.insert(tmpval|(x&0xFF));
1280                                         }
1281                                         else
1282                                                 calcedSections.insert(tmpval|(i&0xFF));
1283                                 }
1284                                 cache->sectionRead(data, source, this);
1285                         }
1286                 }
1287         }
1288 }
1289
1290 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1291 // if t == -1 we search the current event...
1292 {
1293         singleLock s(cache_lock);
1294         uniqueEPGKey key(service);
1295
1296         // check if EPG for this service is ready...
1297         eventCache::iterator It = eventDB.find( key );
1298         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1299         {
1300                 if (t==-1)
1301                         t = eDVBLocalTimeHandler::getInstance()->nowTime();
1302                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1303                         It->second.second.upper_bound(t); // just >
1304                 if ( i != It->second.second.end() )
1305                 {
1306                         if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1307                         {
1308                                 timeMap::iterator x = i;
1309                                 --x;
1310                                 if ( x != It->second.second.end() )
1311                                 {
1312                                         time_t start_time = x->second->getStartTime();
1313                                         if (direction >= 0)
1314                                         {
1315                                                 if (t < start_time)
1316                                                         return -1;
1317                                                 if (t > (start_time+x->second->getDuration()))
1318                                                         return -1;
1319                                         }
1320                                         i = x;
1321                                 }
1322                                 else
1323                                         return -1;
1324                         }
1325                         result = i->second;
1326                         return 0;
1327                 }
1328         }
1329         return -1;
1330 }
1331
1332 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1333 {
1334         singleLock s(cache_lock);
1335         const eventData *data=0;
1336         RESULT ret = lookupEventTime(service, t, data, direction);
1337         if ( !ret && data )
1338                 result = data->get();
1339         return ret;
1340 }
1341
1342 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1343 {
1344         singleLock s(cache_lock);
1345         const eventData *data=0;
1346         RESULT ret = lookupEventTime(service, t, data, direction);
1347         if ( !ret && data )
1348                 result = new Event((uint8_t*)data->get());
1349         return ret;
1350 }
1351
1352 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1353 {
1354         singleLock s(cache_lock);
1355         const eventData *data=0;
1356         RESULT ret = lookupEventTime(service, t, data, direction);
1357         if ( !ret && data )
1358         {
1359                 Event ev((uint8_t*)data->get());
1360                 result = new eServiceEvent();
1361                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1362                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1363         }
1364         return ret;
1365 }
1366
1367 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1368 {
1369         singleLock s(cache_lock);
1370         uniqueEPGKey key( service );
1371
1372         eventCache::iterator It = eventDB.find( key );
1373         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1374         {
1375                 eventMap::iterator i( It->second.first.find( event_id ));
1376                 if ( i != It->second.first.end() )
1377                 {
1378                         result = i->second;
1379                         return 0;
1380                 }
1381                 else
1382                 {
1383                         result = 0;
1384                         eDebug("event %04x not found in epgcache", event_id);
1385                 }
1386         }
1387         return -1;
1388 }
1389
1390 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1391 {
1392         singleLock s(cache_lock);
1393         const eventData *data=0;
1394         RESULT ret = lookupEventId(service, event_id, data);
1395         if ( !ret && data )
1396                 result = data->get();
1397         return ret;
1398 }
1399
1400 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1401 {
1402         singleLock s(cache_lock);
1403         const eventData *data=0;
1404         RESULT ret = lookupEventId(service, event_id, data);
1405         if ( !ret && data )
1406                 result = new Event((uint8_t*)data->get());
1407         return ret;
1408 }
1409
1410 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1411 {
1412         singleLock s(cache_lock);
1413         const eventData *data=0;
1414         RESULT ret = lookupEventId(service, event_id, data);
1415         if ( !ret && data )
1416         {
1417                 Event ev((uint8_t*)data->get());
1418                 result = new eServiceEvent();
1419                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1420                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1421         }
1422         return ret;
1423 }
1424
1425 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1426 {
1427         eventCache::iterator It = eventDB.find( service );
1428         if ( It != eventDB.end() && It->second.second.size() )
1429         {
1430                 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1431                 if ( begin != -1 )
1432                 {
1433                         m_timemap_cursor = It->second.second.lower_bound(begin);
1434                         if ( m_timemap_cursor != It->second.second.end() )
1435                         {
1436                                 if ( m_timemap_cursor->second->getStartTime() != begin )
1437                                 {
1438                                         timeMap::iterator x = m_timemap_cursor;
1439                                         --x;
1440                                         if ( x != It->second.second.end() )
1441                                         {
1442                                                 time_t start_time = x->second->getStartTime();
1443                                                 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1444                                                         m_timemap_cursor = x;
1445                                         }
1446                                 }
1447                         }
1448                 }
1449                 else
1450                         m_timemap_cursor = It->second.second.begin();
1451                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1452                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1453                 return 0;
1454         }
1455         return -1;
1456 }
1457
1458 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1459 {
1460         if ( m_timemap_cursor != m_timemap_end )
1461         {
1462                 result = m_timemap_cursor++->second;
1463                 return 0;
1464         }
1465         return -1;
1466 }
1467
1468 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1469 {
1470         if ( m_timemap_cursor != m_timemap_end )
1471         {
1472                 result = m_timemap_cursor++->second->get();
1473                 return 0;
1474         }
1475         return -1;
1476 }
1477
1478 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1479 {
1480         if ( m_timemap_cursor != m_timemap_end )
1481         {
1482                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1483                 return 0;
1484         }
1485         return -1;
1486 }
1487
1488 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1489 {
1490         if ( m_timemap_cursor != m_timemap_end )
1491         {
1492                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1493                 result = new eServiceEvent();
1494                 return result->parseFrom(&ev, currentQueryTsidOnid);
1495         }
1496         return -1;
1497 }
1498
1499 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1500 {
1501         PyObject *tmp=NULL;
1502         int pos=0;
1503         while(pos < argcount)
1504         {
1505                 bool inc_refcount=false;
1506                 switch(argstring[pos])
1507                 {
1508                         case '0': // PyLong 0
1509                                 tmp = PyLong_FromLong(0);
1510                                 break;
1511                         case 'I': // Event Id
1512                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1513                                 break;
1514                         case 'B': // Event Begin Time
1515                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1516                                 break;
1517                         case 'D': // Event Duration
1518                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1519                                 break;
1520                         case 'T': // Event Title
1521                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1522                                 break;
1523                         case 'S': // Event Short Description
1524                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1525                                 break;
1526                         case 'E': // Event Extended Description
1527                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1528                                 break;
1529                         case 'C': // Current Time
1530                                 tmp = nowTime;
1531                                 inc_refcount = true;
1532                                 break;
1533                         case 'R': // service reference string
1534                                 tmp = service;
1535                                 inc_refcount = true;
1536                                 break;
1537                         case 'N': // service name
1538                                 tmp = service_name;
1539                                 inc_refcount = true;
1540                 }
1541                 if (!tmp)
1542                 {
1543                         tmp = Py_None;
1544                         inc_refcount = true;
1545                 }
1546                 if (inc_refcount)
1547                         Py_INCREF(tmp);
1548                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1549         }
1550 }
1551
1552 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1553 {
1554         if (convertFunc)
1555         {
1556                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1557                 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1558                 if (result == NULL)
1559                 {
1560                         if (service_name)
1561                                 Py_DECREF(service_name);
1562                         if (nowTime)
1563                                 Py_DECREF(nowTime);
1564                         Py_DECREF(convertFuncArgs);
1565                         Py_DECREF(dest_list);
1566                         return result;
1567                 }
1568                 PyList_Append(dest_list, result);
1569                 Py_DECREF(result);
1570         }
1571         else
1572         {
1573                 PyObject *tuple = PyTuple_New(argcount);
1574                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1575                 PyList_Append(dest_list, tuple);
1576                 Py_DECREF(tuple);
1577         }
1578         return 0;
1579 }
1580
1581 // here we get a python list
1582 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1583 //   0 = PyLong(0)
1584 //   I = Event Id
1585 //   B = Event Begin Time
1586 //   D = Event Duration
1587 //   T = Event Title
1588 //   S = Event Short Description
1589 //   E = Event Extended Description
1590 //   C = Current Time
1591 //   R = Service Reference
1592 //   N = Service Name
1593 // then for each service follows a tuple
1594 //   first tuple entry is the servicereference (as string... use the ref.toString() function)
1595 //   the second is the type of query
1596 //     2 = event_id
1597 //    -1 = event before given start_time
1598 //     0 = event intersects given start_time
1599 //    +1 = event after given start_time
1600 //   the third
1601 //      when type is eventid it is the event_id
1602 //      when type is time then it is the start_time ( 0 for now_time )
1603 //   the fourth is the end_time .. ( optional .. for query all events in time range)
1604
1605 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1606 {
1607         PyObject *convertFuncArgs=NULL;
1608         int argcount=0;
1609         char *argstring=NULL;
1610         if (!PyList_Check(list))
1611         {
1612                 PyErr_SetString(PyExc_StandardError,
1613                         "type error");
1614                 eDebug("no list");
1615                 return NULL;
1616         }
1617         int listIt=0;
1618         int listSize=PyList_Size(list);
1619         if (!listSize)
1620         {
1621                 PyErr_SetString(PyExc_StandardError,
1622                         "not params given");
1623                 eDebug("not params given");
1624                 return NULL;
1625         }
1626         else 
1627         {
1628                 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1629                 if (PyString_Check(argv))
1630                 {
1631                         argstring = PyString_AS_STRING(argv);
1632                         ++listIt;
1633                 }
1634                 else
1635                         argstring = "I"; // just event id as default
1636                 argcount = strlen(argstring);
1637 //              eDebug("have %d args('%s')", argcount, argstring);
1638         }
1639         if (convertFunc)
1640         {
1641                 if (!PyCallable_Check(convertFunc))
1642                 {
1643                         PyErr_SetString(PyExc_StandardError,
1644                                 "convertFunc must be callable");
1645                         eDebug("convertFunc is not callable");
1646                         return NULL;
1647                 }
1648                 convertFuncArgs = PyTuple_New(argcount);
1649         }
1650
1651         PyObject *nowTime = strchr(argstring, 'C') ?
1652                 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1653                 NULL;
1654
1655         bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1656
1657         // create dest list
1658         PyObject *dest_list=PyList_New(0);
1659         while(listSize > listIt)
1660         {
1661                 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1662                 if (PyTuple_Check(item))
1663                 {
1664                         bool service_changed=false;
1665                         int type=0;
1666                         long event_id=-1;
1667                         time_t stime=-1;
1668                         int minutes=0;
1669                         int tupleSize=PyTuple_Size(item);
1670                         int tupleIt=0;
1671                         PyObject *service=NULL;
1672                         while(tupleSize > tupleIt)  // parse query args
1673                         {
1674                                 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1675                                 switch(tupleIt++)
1676                                 {
1677                                         case 0:
1678                                         {
1679                                                 if (!PyString_Check(entry))
1680                                                 {
1681                                                         eDebug("tuple entry 0 is no a string");
1682                                                         goto skip_entry;
1683                                                 }
1684                                                 service = entry;
1685                                                 break;
1686                                         }
1687                                         case 1:
1688                                                 type=PyInt_AsLong(entry);
1689                                                 if (type < -1 || type > 2)
1690                                                 {
1691                                                         eDebug("unknown type %d", type);
1692                                                         goto skip_entry;
1693                                                 }
1694                                                 break;
1695                                         case 2:
1696                                                 event_id=stime=PyInt_AsLong(entry);
1697                                                 break;
1698                                         case 3:
1699                                                 minutes=PyInt_AsLong(entry);
1700                                                 break;
1701                                         default:
1702                                                 eDebug("unneeded extra argument");
1703                                                 break;
1704                                 }
1705                         }
1706                         eServiceReference ref(PyString_AS_STRING(service));
1707                         if (ref.type != eServiceReference::idDVB)
1708                         {
1709                                 eDebug("service reference for epg query is not valid");
1710                                 continue;
1711                         }
1712
1713                         // redirect subservice querys to parent service
1714                         eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1715                         if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1716                         {
1717                                 eServiceCenterPtr service_center;
1718                                 if (!eServiceCenter::getPrivInstance(service_center))
1719                                 {
1720                                         dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1721                                         dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1722                                         dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1723                                         dvb_ref.setParentServiceID(eServiceID(0));
1724                                         dvb_ref.name="";
1725                                         service = PyString_FromString(dvb_ref.toString().c_str());
1726                                         service_changed = true;
1727                                 }
1728                         }
1729
1730                         PyObject *service_name=NULL;
1731                         if (must_get_service_name)
1732                         {
1733                                 ePtr<iStaticServiceInformation> sptr;
1734                                 eServiceCenterPtr service_center;
1735                                 eServiceCenter::getPrivInstance(service_center);
1736                                 if (service_center)
1737                                 {
1738                                         service_center->info(ref, sptr);
1739                                         if (sptr)
1740                                         {
1741                                                 std::string name;
1742                                                 sptr->getName(ref, name);
1743                                                 if (name.length())
1744                                                         service_name = PyString_FromString(name.c_str());
1745                                         }
1746                                 }
1747                                 if (!service_name)
1748                                         service_name = PyString_FromString("<n/a>");
1749                         }
1750                         if (minutes)
1751                         {
1752                                 Lock();
1753                                 if (!startTimeQuery(ref, stime, minutes))
1754                                 {
1755                                         ePtr<eServiceEvent> ptr;
1756                                         while (!getNextTimeEntry(ptr))
1757                                         {
1758                                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1759                                                 if (ret)
1760                                                         return ret;
1761                                         }
1762                                 }
1763                                 Unlock();
1764                         }
1765                         else
1766                         {
1767                                 ePtr<eServiceEvent> ptr;
1768                                 if (stime)
1769                                 {
1770                                         if (type == 2)
1771                                                 lookupEventId(ref, event_id, ptr);
1772                                         else
1773                                                 lookupEventTime(ref, stime, ptr, type);
1774                                 }
1775                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1776                                 if (ret)
1777                                         return ret;
1778                         }
1779                         if (service_changed)
1780                                 Py_DECREF(service);
1781                         if (service_name)
1782                                 Py_DECREF(service_name);
1783                 }
1784 skip_entry:
1785                 ;
1786         }
1787         if (convertFuncArgs)
1788                 Py_DECREF(convertFuncArgs);
1789         if (nowTime)
1790                 Py_DECREF(nowTime);
1791         return dest_list;
1792 }
1793
1794 void fillTuple2(PyObject *tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, PyObject *service_name, PyObject *service_reference)
1795 {
1796         PyObject *tmp=NULL;
1797         int pos=0;
1798         while(pos < argcount)
1799         {
1800                 bool inc_refcount=false;
1801                 switch(argstring[pos])
1802                 {
1803                         case '0': // PyLong 0
1804                                 tmp = PyLong_FromLong(0);
1805                                 break;
1806                         case 'I': // Event Id
1807                                 tmp = PyLong_FromLong(evData->getEventID());
1808                                 break;
1809                         case 'B': // Event Begin Time
1810                                 if (ptr)
1811                                         tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1812                                 else
1813                                         tmp = PyLong_FromLong(evData->getStartTime());
1814                                 break;
1815                         case 'D': // Event Duration
1816                                 if (ptr)
1817                                         tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1818                                 else
1819                                         tmp = PyLong_FromLong(evData->getDuration());
1820                                 break;
1821                         case 'T': // Event Title
1822                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1823                                 break;
1824                         case 'S': // Event Short Description
1825                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1826                                 break;
1827                         case 'E': // Event Extended Description
1828                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1829                                 break;
1830                         case 'R': // service reference string
1831                                 tmp = service_reference;
1832                                 inc_refcount = true;
1833                                 break;
1834                         case 'N': // service name
1835                                 tmp = service_name;
1836                                 inc_refcount = true;
1837                                 break;
1838                 }
1839                 if (!tmp)
1840                 {
1841                         tmp = Py_None;
1842                         inc_refcount = true;
1843                 }
1844                 if (inc_refcount)
1845                         Py_INCREF(tmp);
1846                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1847         }
1848 }
1849
1850 // here we get a python tuple
1851 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1852 //   I = Event Id
1853 //   B = Event Begin Time
1854 //   D = Event Duration
1855 //   T = Event Title
1856 //   S = Event Short Description
1857 //   E = Event Extended Description
1858 //   R = Service Reference
1859 //   N = Service Name
1860 //  the second tuple entry is the MAX matches value
1861 //  the third tuple entry is the type of query
1862 //     0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1863 //     1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1864 //     2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1865 //  when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1866 //   the fourth is the servicereference string
1867 //   the fifth is the eventid
1868 //  when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1869 //   the fourth is the search text
1870 //   the fifth is
1871 //     0 = case sensitive (CASE_CHECK)
1872 //     1 = case insensitive (NO_CASECHECK)
1873
1874 PyObject *eEPGCache::search(PyObject *arg)
1875 {
1876         PyObject *ret = 0;
1877         int descridx = -1;
1878         __u32 descr[512];
1879         int eventid = -1;
1880         const char *argstring=0;
1881         char *refstr=0;
1882         int argcount=0;
1883         int querytype=-1;
1884         bool needServiceEvent=false;
1885         int maxmatches=0;
1886
1887         if (PyTuple_Check(arg))
1888         {
1889                 int tuplesize=PyTuple_Size(arg);
1890                 if (tuplesize > 0)
1891                 {
1892                         PyObject *obj = PyTuple_GET_ITEM(arg,0);
1893                         if (PyString_Check(obj))
1894                         {
1895                                 argcount = PyString_GET_SIZE(obj);
1896                                 argstring = PyString_AS_STRING(obj);
1897                                 for (int i=0; i < argcount; ++i)
1898                                         switch(argstring[i])
1899                                         {
1900                                         case 'S':
1901                                         case 'E':
1902                                         case 'T':
1903                                                 needServiceEvent=true;
1904                                         default:
1905                                                 break;
1906                                         }
1907                         }
1908                         else
1909                         {
1910                                 PyErr_SetString(PyExc_StandardError,
1911                                         "type error");
1912                                 eDebug("tuple arg 0 is not a string");
1913                                 return NULL;
1914                         }
1915                 }
1916                 if (tuplesize > 1)
1917                         maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1918                 if (tuplesize > 2)
1919                 {
1920                         querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1921                         if (tuplesize > 4 && querytype == 0)
1922                         {
1923                                 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1924                                 if (PyString_Check(obj))
1925                                 {
1926                                         refstr = PyString_AS_STRING(obj);
1927                                         eServiceReferenceDVB ref(refstr);
1928                                         if (ref.valid())
1929                                         {
1930                                                 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1931                                                 singleLock s(cache_lock);
1932                                                 const eventData *evData = 0;
1933                                                 lookupEventId(ref, eventid, evData);
1934                                                 if (evData)
1935                                                 {
1936                                                         __u8 *data = evData->EITdata;
1937                                                         int tmp = evData->ByteSize-12;
1938                                                         __u32 *p = (__u32*)(data+12);
1939                                                                 // search short and extended event descriptors
1940                                                         while(tmp>0)
1941                                                         {
1942                                                                 __u32 crc = *p++;
1943                                                                 descriptorMap::iterator it =
1944                                                                         eventData::descriptors.find(crc);
1945                                                                 if (it != eventData::descriptors.end())
1946                                                                 {
1947                                                                         __u8 *descr_data = it->second.second;
1948                                                                         switch(descr_data[0])
1949                                                                         {
1950                                                                         case 0x4D ... 0x4E:
1951                                                                                 descr[++descridx]=crc;
1952                                                                         default:
1953                                                                                 break;
1954                                                                         }
1955                                                                 }
1956                                                                 tmp-=4;
1957                                                         }
1958                                                 }
1959                                                 if (descridx<0)
1960                                                         eDebug("event not found");
1961                                         }
1962                                         else
1963                                         {
1964                                                 PyErr_SetString(PyExc_StandardError,
1965                                                         "type error");
1966                                                 eDebug("tuple arg 4 is not a valid service reference string");
1967                                                 return NULL;
1968                                         }
1969                                 }
1970                                 else
1971                                 {
1972                                         PyErr_SetString(PyExc_StandardError,
1973                                         "type error");
1974                                         eDebug("tuple arg 4 is not a string");
1975                                         return NULL;
1976                                 }
1977                         }
1978                         else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
1979                         {
1980                                 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1981                                 if (PyString_Check(obj))
1982                                 {
1983                                         int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1984                                         const char *str = PyString_AS_STRING(obj);
1985                                         int textlen = PyString_GET_SIZE(obj);
1986                                         if (querytype == 1)
1987                                                 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
1988                                         else
1989                                                 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
1990                                         singleLock s(cache_lock);
1991                                         for (descriptorMap::iterator it(eventData::descriptors.begin());
1992                                                 it != eventData::descriptors.end() && descridx < 511; ++it)
1993                                         {
1994                                                 __u8 *data = it->second.second;
1995                                                 if ( data[0] == 0x4D ) // short event descriptor
1996                                                 {
1997                                                         int title_len = data[5];
1998                                                         if ( querytype == 1 )
1999                                                         {
2000                                                                 if (title_len > textlen)
2001                                                                         continue;
2002                                                                 else if (title_len < textlen)
2003                                                                         continue;
2004                                                                 if ( casetype )
2005                                                                 {
2006                                                                         if ( !strncasecmp((const char*)data+6, str, title_len) )
2007                                                                         {
2008 //                                                                              std::string s((const char*)data+6, title_len);
2009 //                                                                              eDebug("match1 %s %s", str, s.c_str() );
2010                                                                                 descr[++descridx] = it->first;
2011                                                                         }
2012                                                                 }
2013                                                                 else if ( !strncmp((const char*)data+6, str, title_len) )
2014                                                                 {
2015 //                                                                      std::string s((const char*)data+6, title_len);
2016 //                                                                      eDebug("match2 %s %s", str, s.c_str() );
2017                                                                         descr[++descridx] = it->first;
2018                                                                 }
2019                                                         }
2020                                                         else
2021                                                         {
2022                                                                 int idx=0;
2023                                                                 while((title_len-idx) >= textlen)
2024                                                                 {
2025                                                                         if (casetype)
2026                                                                         {
2027                                                                                 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2028                                                                                 {
2029                                                                                         descr[++descridx] = it->first;
2030 //                                                                                      std::string s((const char*)data+6, title_len);
2031 //                                                                                      eDebug("match 3 %s %s", str, s.c_str() );
2032                                                                                         break;
2033                                                                                 }
2034                                                                                 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2035                                                                                 {
2036                                                                                         descr[++descridx] = it->first;
2037 //                                                                                      std::string s((const char*)data+6, title_len);
2038 //                                                                                      eDebug("match 4 %s %s", str, s.c_str() );
2039                                                                                         break;
2040                                                                                 }
2041                                                                         }
2042                                                                         ++idx;
2043                                                                 }
2044                                                         }
2045                                                 }
2046                                         }
2047                                 }
2048                                 else
2049                                 {
2050                                         PyErr_SetString(PyExc_StandardError,
2051                                                 "type error");
2052                                         eDebug("tuple arg 4 is not a string");
2053                                         return NULL;
2054                                 }
2055                         }
2056                         else
2057                         {
2058                                 PyErr_SetString(PyExc_StandardError,
2059                                         "type error");
2060                                 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2061                                 return NULL;
2062                         }
2063                 }
2064                 else
2065                 {
2066                         PyErr_SetString(PyExc_StandardError,
2067                                 "type error");
2068                         eDebug("not enough args in tuple");
2069                         return NULL;
2070                 }
2071         }
2072         else
2073         {
2074                 PyErr_SetString(PyExc_StandardError,
2075                         "type error");
2076                 eDebug("arg 0 is not a tuple");
2077                 return NULL;
2078         }
2079
2080         if (descridx > -1)
2081         {
2082                 int maxcount=maxmatches;
2083                 eServiceReferenceDVB ref(refstr?refstr:"");
2084                 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2085                 // in this case we start searching with the base service
2086                 bool first = ref.valid() ? true : false;
2087                 singleLock s(cache_lock);
2088                 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2089                 while(cit != eventDB.end() && maxcount)
2090                 {
2091                         if ( ref.valid() && !first && cit->first == ref )
2092                         {
2093                                 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2094                                 ++cit;
2095                                 continue;
2096                         }
2097                         PyObject *service_name=0;
2098                         PyObject *service_reference=0;
2099                         timeMap &evmap = cit->second.second;
2100                         // check all events
2101                         for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2102                         {
2103                                 if (evit->second->getEventID() == eventid)
2104                                         continue;
2105                                 __u8 *data = evit->second->EITdata;
2106                                 int tmp = evit->second->ByteSize-12;
2107                                 __u32 *p = (__u32*)(data+12);
2108                                 // check if any of our descriptor used by this event
2109                                 int cnt=-1;
2110                                 while(tmp>0)
2111                                 {
2112                                         __u32 crc32 = *p++;
2113                                         for ( int i=0; i <= descridx; ++i)
2114                                         {
2115                                                 if (descr[i] == crc32)  // found...
2116                                                         ++cnt;
2117                                         }
2118                                         tmp-=4;
2119                                 }
2120                                 if ( (querytype == 0 && cnt == descridx) ||
2121                                          ((querytype == 1 || querytype == 2) && cnt != -1) )
2122                                 {
2123                                         const uniqueEPGKey &service = cit->first;
2124                                         eServiceReference ref =
2125                                                 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2126                                         if (ref.valid())
2127                                         {
2128                                         // create servive event
2129                                                 ePtr<eServiceEvent> ptr;
2130                                                 if (needServiceEvent)
2131                                                 {
2132                                                         lookupEventId(ref, evit->first, ptr);
2133                                                         if (!ptr)
2134                                                                 eDebug("event not found !!!!!!!!!!!");
2135                                                 }
2136                                         // create service name
2137                                                 if (!service_name && strchr(argstring,'N'))
2138                                                 {
2139                                                         ePtr<iStaticServiceInformation> sptr;
2140                                                         eServiceCenterPtr service_center;
2141                                                         eServiceCenter::getPrivInstance(service_center);
2142                                                         if (service_center)
2143                                                         {
2144                                                                 service_center->info(ref, sptr);
2145                                                                 if (sptr)
2146                                                                 {
2147                                                                         std::string name;
2148                                                                         sptr->getName(ref, name);
2149                                                                         if (name.length())
2150                                                                                 service_name = PyString_FromString(name.c_str());
2151                                                                 }
2152                                                         }
2153                                                         if (!service_name)
2154                                                                 service_name = PyString_FromString("<n/a>");
2155                                                 }
2156                                         // create servicereference string
2157                                                 if (!service_reference && strchr(argstring,'R'))
2158                                                         service_reference = PyString_FromString(ref.toString().c_str());
2159                                         // create list
2160                                                 if (!ret)
2161                                                         ret = PyList_New(0);
2162                                         // create tuple
2163                                                 PyObject *tuple = PyTuple_New(argcount);
2164                                         // fill tuple
2165                                                 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2166                                                 PyList_Append(ret, tuple);
2167                                                 Py_DECREF(tuple);
2168                                                 --maxcount;
2169                                         }
2170                                 }
2171                         }
2172                         if (service_name)
2173                                 Py_DECREF(service_name);
2174                         if (service_reference)
2175                                 Py_DECREF(service_reference);
2176                         if (first)
2177                         {
2178                                 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2179                                 first=false;
2180                                 cit=eventDB.begin();
2181                         }
2182                         else
2183                                 ++cit;
2184                 }
2185         }
2186
2187         if (!ret)
2188         {
2189                 Py_INCREF(Py_None);
2190                 ret=Py_None;
2191         }
2192
2193         return ret;
2194 }
2195
2196 #ifdef ENABLE_PRIVATE_EPG
2197 #include <dvbsi++/descriptor_tag.h>
2198 #include <dvbsi++/unknown_descriptor.h>
2199 #include <dvbsi++/private_data_specifier_descriptor.h>
2200
2201 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2202 {
2203         ePtr<eTable<ProgramMapSection> > ptr;
2204         if (!pmthandler->getPMT(ptr) && ptr)
2205         {
2206                 std::vector<ProgramMapSection*>::const_iterator i;
2207                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2208                 {
2209                         const ProgramMapSection &pmt = **i;
2210
2211                         ElementaryStreamInfoConstIterator es;
2212                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2213                         {
2214                                 int tmp=0;
2215                                 switch ((*es)->getType())
2216                                 {
2217                                 case 0x05: // private
2218                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2219                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2220                                         {
2221                                                 switch ((*desc)->getTag())
2222                                                 {
2223                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2224                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2225                                                                         tmp |= 1;
2226                                                                 break;
2227                                                         case 0x90:
2228                                                         {
2229                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2230                                                                 int descr_len = descr->getLength();
2231                                                                 if (descr_len == 4)
2232                                                                 {
2233                                                                         uint8_t data[descr_len+2];
2234                                                                         descr->writeToBuffer(data);
2235                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2236                                                                                 tmp |= 2;
2237                                                                 }
2238                                                                 break;
2239                                                         }
2240                                                         default:
2241                                                                 break;
2242                                                 }
2243                                         }
2244                                 default:
2245                                         break;
2246                                 }
2247                                 if (tmp==3)
2248                                 {
2249                                         eServiceReferenceDVB ref;
2250                                         if (!pmthandler->getServiceReference(ref))
2251                                         {
2252                                                 int pid = (*es)->getPid();
2253                                                 messages.send(Message(Message::got_private_pid, ref, pid));
2254                                                 return;
2255                                         }
2256                                 }
2257                         }
2258                 }
2259         }
2260         else
2261                 eDebug("PMTready but no pmt!!");
2262 }
2263
2264 struct date_time
2265 {
2266         __u8 data[5];
2267         time_t tm;
2268         date_time( const date_time &a )
2269         {
2270                 memcpy(data, a.data, 5);
2271                 tm = a.tm;
2272         }
2273         date_time( const __u8 data[5])
2274         {
2275                 memcpy(this->data, data, 5);
2276                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2277         }
2278         date_time()
2279         {
2280         }
2281         const __u8& operator[](int pos) const
2282         {
2283                 return data[pos];
2284         }
2285 };
2286
2287 struct less_datetime
2288 {
2289         bool operator()( const date_time &a, const date_time &b ) const
2290         {
2291                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2292         }
2293 };
2294
2295 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
2296 {
2297         contentMap &content_time_table = content_time_tables[current_service];
2298         singleLock s(cache_lock);
2299         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2300         eventMap &evMap = eventDB[current_service].first;
2301         timeMap &tmMap = eventDB[current_service].second;
2302         int ptr=8;
2303         int content_id = data[ptr++] << 24;
2304         content_id |= data[ptr++] << 16;
2305         content_id |= data[ptr++] << 8;
2306         content_id |= data[ptr++];
2307
2308         contentTimeMap &time_event_map =
2309                 content_time_table[content_id];
2310         for ( contentTimeMap::iterator it( time_event_map.begin() );
2311                 it != time_event_map.end(); ++it )
2312         {
2313                 eventMap::iterator evIt( evMap.find(it->second.second) );
2314                 if ( evIt != evMap.end() )
2315                 {
2316                         delete evIt->second;
2317                         evMap.erase(evIt);
2318                 }
2319                 tmMap.erase(it->second.first);
2320         }
2321         time_event_map.clear();
2322
2323         __u8 duration[3];
2324         memcpy(duration, data+ptr, 3);
2325         ptr+=3;
2326         int duration_sec =
2327                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2328
2329         const __u8 *descriptors[65];
2330         const __u8 **pdescr = descriptors;
2331
2332         int descriptors_length = (data[ptr++]&0x0F) << 8;
2333         descriptors_length |= data[ptr++];
2334         while ( descriptors_length > 0 )
2335         {
2336                 int descr_type = data[ptr];
2337                 int descr_len = data[ptr+1];
2338                 descriptors_length -= (descr_len+2);
2339                 if ( descr_type == 0xf2 )
2340                 {
2341                         ptr+=2;
2342                         int tsid = data[ptr++] << 8;
2343                         tsid |= data[ptr++];
2344                         int onid = data[ptr++] << 8;
2345                         onid |= data[ptr++];
2346                         int sid = data[ptr++] << 8;
2347                         sid |= data[ptr++];
2348
2349 // WORKAROUND for wrong transmitted epg data
2350                         if ( onid == 0x85 && tsid == 0x11 && sid == 0xd3 )  // premiere sends wrong tsid here
2351                                 tsid = 0x1;
2352                         else if ( onid == 0x85 && tsid == 0x3 && sid == 0xf5 ) // premiere sends wrong sid here
2353                                 sid = 0xdc;
2354 ////////////////////////////////////////////
2355                                 
2356                         uniqueEPGKey service( sid, onid, tsid );
2357                         descr_len -= 6;
2358                         while( descr_len > 0 )
2359                         {
2360                                 __u8 datetime[5];
2361                                 datetime[0] = data[ptr++];
2362                                 datetime[1] = data[ptr++];
2363                                 int tmp_len = data[ptr++];
2364                                 descr_len -= 3;
2365                                 while( tmp_len > 0 )
2366                                 {
2367                                         memcpy(datetime+2, data+ptr, 3);
2368                                         ptr+=3;
2369                                         descr_len -= 3;
2370                                         tmp_len -= 3;
2371                                         start_times[datetime].push_back(service);
2372                                 }
2373                         }
2374                 }
2375                 else
2376                 {
2377                         *pdescr++=data+ptr;
2378                         ptr += 2;
2379                         ptr += descr_len;
2380                 }
2381         }
2382         __u8 event[4098];
2383         eit_event_struct *ev_struct = (eit_event_struct*) event;
2384         ev_struct->running_status = 0;
2385         ev_struct->free_CA_mode = 1;
2386         memcpy(event+7, duration, 3);
2387         ptr = 12;
2388         const __u8 **d=descriptors;
2389         while ( d < pdescr )
2390         {
2391                 memcpy(event+ptr, *d, ((*d)[1])+2);
2392                 ptr+=(*d++)[1];
2393                 ptr+=2;
2394         }
2395         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2396         {
2397                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2398                 if ( (it->first.tm + duration_sec) < now )
2399                         continue;
2400                 memcpy(event+2, it->first.data, 5);
2401                 int bptr = ptr;
2402                 int cnt=0;
2403                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2404                 {
2405                         event[bptr++] = 0x4A;
2406                         __u8 *len = event+(bptr++);
2407                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
2408                         event[bptr++] = (i->tsid & 0xFF);
2409                         event[bptr++] = (i->onid & 0xFF00) >> 8;
2410                         event[bptr++] = (i->onid & 0xFF);
2411                         event[bptr++] = (i->sid & 0xFF00) >> 8;
2412                         event[bptr++] = (i->sid & 0xFF);
2413                         event[bptr++] = 0xB0;
2414                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2415                         *len = ((event+bptr) - len)-1;
2416                 }
2417                 int llen = bptr - 12;
2418                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2419                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2420
2421                 time_t stime = it->first.tm;
2422                 while( tmMap.find(stime) != tmMap.end() )
2423                         ++stime;
2424                 event[6] += (stime - it->first.tm);
2425                 __u16 event_id = 0;
2426                 while( evMap.find(event_id) != evMap.end() )
2427                         ++event_id;
2428                 event[0] = (event_id & 0xFF00) >> 8;
2429                 event[1] = (event_id & 0xFF);
2430                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2431                 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2432                 evMap[event_id] = d;
2433                 tmMap[stime] = d;
2434         }
2435 }
2436
2437 void eEPGCache::channel_data::startPrivateReader()
2438 {
2439         eDVBSectionFilterMask mask;
2440         memset(&mask, 0, sizeof(mask));
2441         mask.pid = m_PrivatePid;
2442         mask.flags = eDVBSectionFilterMask::rfCRC;
2443         mask.data[0] = 0xA0;
2444         mask.mask[0] = 0xFF;
2445         eDebug("start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2446         if (m_PrevVersion != -1)
2447         {
2448                 mask.data[3] = m_PrevVersion << 1;
2449                 mask.mask[3] = 0x3E;
2450                 mask.mode[3] = 0x3E;
2451         }
2452         seenPrivateSections.clear();
2453         if (!m_PrivateConn)
2454                 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2455         m_PrivateReader->start(mask);
2456 }
2457
2458 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2459 {
2460         if (!data)
2461                 eDebug("get Null pointer from section reader !!");
2462         else
2463         {
2464                 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2465                 {
2466                         cache->privateSectionRead(m_PrivateService, data);
2467                         seenPrivateSections.insert(data[6]);
2468                 }
2469                 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2470                 {
2471                         eDebug("[EPGC] private finished");
2472                         m_PrevVersion = (data[5] & 0x3E) >> 1;
2473                         startPrivateReader();
2474                 }
2475         }
2476 }
2477
2478 #endif // ENABLE_PRIVATE_EPG
2479
2480 #ifdef ENABLE_MHW_EPG
2481 void eEPGCache::channel_data::cleanup()
2482 {
2483         m_channels.clear();
2484         m_themes.clear();
2485         m_titles.clear();
2486         m_program_ids.clear();
2487 }
2488
2489 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2490 {
2491         // Names in mhw structs are not strings as they are not '\0' terminated.
2492         // This function converts the mhw name into a string.
2493         // Constraint: "length of out" = "length of in" + 1.
2494         int i;
2495         for ( i=0; i < len_in; i++ )
2496                 out[i] = in[i];
2497
2498         i = len_in - 1;
2499         while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2500                 i--;
2501
2502         out[i+1] = 0;
2503         return out;
2504 }
2505
2506 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2507 // For time of day
2508 {
2509         return_time[0] = toBCD( hours );
2510         return_time[1] = toBCD( minutes );
2511         return_time[2] = 0;
2512 }
2513
2514 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2515 {
2516         timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2517 }
2518
2519 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2520 // For date plus time of day
2521 {
2522         // Remove offset in mhw time.
2523         __u8 local_hours = hours;
2524         if ( hours >= 16 )
2525                 local_hours -= 4;
2526         else if ( hours >= 8 )
2527                 local_hours -= 2;
2528
2529         // As far as we know all mhw time data is sent in central Europe time zone.
2530         // So, temporarily set timezone to western europe
2531         time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2532
2533         char *old_tz = getenv( "TZ" );
2534         putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2535         tzset();
2536
2537         tm *localnow = localtime( &dt );
2538
2539         if (day == 7)
2540                 day = 0;
2541         if ( day + 1 < localnow->tm_wday )              // day + 1 to prevent old events to show for next week.
2542                 day += 7;
2543         if (local_hours <= 5)
2544                 day++;
2545
2546         dt += 3600*24*(day - localnow->tm_wday);        // Shift dt to the recording date (local time zone).
2547         dt += 3600*(local_hours - localnow->tm_hour);  // Shift dt to the recording hour.
2548
2549         tm *recdate = gmtime( &dt );   // This will also take care of DST.
2550
2551         if ( old_tz == NULL )
2552                 unsetenv( "TZ" );
2553         else
2554                 putenv( old_tz );
2555         tzset();
2556
2557         // Calculate MJD according to annex in ETSI EN 300 468
2558         int l=0;
2559         if ( recdate->tm_mon <= 1 )     // Jan or Feb
2560                 l=1;
2561         int mjd = 14956 + recdate->tm_mday + int( (recdate->tm_year - l) * 365.25) +
2562                 int( (recdate->tm_mon + 2 + l * 12) * 30.6001);
2563
2564         return_time[0] = (mjd & 0xFF00)>>8;
2565         return_time[1] = mjd & 0xFF;
2566
2567         timeMHW2DVB( recdate->tm_hour, minutes, return_time+2 );
2568 }
2569
2570 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2571 // data is borrowed from calling proc to save memory space.
2572 {
2573         // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2574         __u8 name[24];
2575
2576         eit_t *packet = (eit_t *) data;
2577         packet->table_id = 0x50;
2578         packet->section_syntax_indicator = 1;
2579         packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2580         packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2581         packet->version_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2582         packet->current_next_indicator = 0;
2583         packet->section_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2584         packet->last_section_number = 0;        // eEPGCache::sectionRead() will dig this for the moment
2585         packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2586         packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2587         packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2588         packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2589         packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2590         packet->segment_last_table_id = 0x50;
2591
2592         std::string prog_title = (char *) delimitName( itTitle->second.title, name, 23 );
2593         int prog_title_length = prog_title.length();
2594
2595         int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2596                 prog_title_length + 1;
2597
2598         eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2599         event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2600         event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2601
2602         timeMHW2DVB( itTitle->second.day, itTitle->second.hours, itTitle->second.minutes,
2603                 (u_char *) event_data + 2 );
2604         timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2605
2606         event_data->running_status = 0;
2607         event_data->free_CA_mode = 0;
2608         int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2609
2610         eit_short_event_descriptor_struct *short_event_descriptor =
2611                 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2612         short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2613         short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2614                 prog_title_length - 1;
2615         short_event_descriptor->language_code_1 = 'e';
2616         short_event_descriptor->language_code_2 = 'n';
2617         short_event_descriptor->language_code_3 = 'g';
2618         short_event_descriptor->event_name_length = prog_title_length;
2619         delimitName( itTitle->second.title, name, 23 );
2620         u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2621         memcpy(event_name, name, prog_title_length);
2622
2623         // Set text length
2624         event_name[prog_title_length] = 0;
2625
2626         if ( sumText.length() > 0 )
2627         // There is summary info
2628         {
2629                 unsigned int sum_length = sumText.length();
2630                 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2631                 // Store summary in short event descriptor
2632                 {
2633                         // Increase all relevant lengths
2634                         event_name[prog_title_length] = sum_length;
2635                         short_event_descriptor->descriptor_length += sum_length;
2636                         packet_length += sum_length;
2637                         descr_ll += sum_length;
2638                         sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2639                 }
2640                 else
2641                 // Store summary in extended event descriptors
2642                 {
2643                         int remaining_sum_length = sumText.length();
2644                         int nbr_descr = int(remaining_sum_length/247) + 1;
2645                         for ( int i=0; i < nbr_descr; i++)
2646                         // Loop once per extended event descriptor
2647                         {
2648                                 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2649                                 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2650                                 remaining_sum_length -= sum_length;
2651                                 packet_length += 8 + sum_length;
2652                                 descr_ll += 8 + sum_length;
2653
2654                                 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2655                                 ext_event_descriptor->descriptor_length = sum_length + 6;
2656                                 ext_event_descriptor->descriptor_number = i;
2657                                 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2658                                 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2659                                 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2660                                 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2661                                 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2662                                 the_text[-2] = 0;
2663                                 the_text[-1] = sum_length;
2664                                 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2665                         }
2666                 }
2667         }
2668         // Add content descriptor
2669         u_char *descriptor = (u_char *) data + packet_length;
2670         packet_length += 4;
2671         descr_ll += 4;
2672
2673         int content_id = 0;
2674         std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2675         if ( content_descr.find( "FILM" ) != std::string::npos )
2676                 content_id = 0x10;
2677         else if ( content_descr.find( "SPORT" ) != std::string::npos )
2678                 content_id = 0x40;
2679
2680         descriptor[0] = 0x54;
2681         descriptor[1] = 2;
2682         descriptor[2] = content_id;
2683         descriptor[3] = 0;
2684
2685         event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2686         event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2687
2688         packet->section_length_hi =  ((packet_length - 3)&0xf00)>>8;
2689         packet->section_length_lo =  (packet_length - 3)&0xff;
2690
2691         // Feed the data to eEPGCache::sectionRead()
2692         cache->sectionRead( data, MHW, this );
2693 }
2694
2695 void eEPGCache::channel_data::startTimeout(int msec)
2696 {
2697         m_MHWTimeoutTimer.start(msec,true);
2698         m_MHWTimeoutet=false;
2699 }
2700
2701 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2702 {
2703         m_MHWFilterMask.pid = pid;
2704         m_MHWFilterMask.data[0] = tid;
2705         m_MHWReader->start(m_MHWFilterMask);
2706 //      eDebug("start 0x%02x 0x%02x", pid, tid);
2707 }
2708
2709 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2710 {
2711         if ( state > 1 || // aborted
2712                 // have si data.. so we dont read mhw data
2713                 (haveData & (SCHEDULE|SCHEDULE_OTHER)) ) 
2714         {
2715                 eDebug("[EPGC] mhw aborted %d", state);
2716         }
2717         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2718         // Channels table
2719         {
2720                 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2721                 int record_size = sizeof( mhw_channel_name_t );
2722                 int nbr_records = int (len/record_size);
2723
2724                 for ( int i = 0; i < nbr_records; i++ )
2725                 {
2726                         mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2727                         m_channels.push_back( *channel );
2728                 }
2729                 haveData |= MHW;
2730
2731                 eDebug("channels finished %d found", m_channels.size());
2732
2733                 // Channels table has been read, start reading the themes table.
2734                 startMHWReader(0xD3, 0x92);
2735                 return;
2736         }
2737         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2738         // Themes table
2739         {
2740                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2741                 int record_size = sizeof( mhw_theme_name_t );
2742                 int nbr_records = int (len/record_size);
2743                 int idx_ptr = 0;
2744                 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2745                 __u8 idx = 0;
2746                 __u8 sub_idx = 0;
2747                 for ( int i = 0; i < nbr_records; i++ )
2748                 {
2749                         mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2750                         if ( i >= next_idx )
2751                         {
2752                                 idx = (idx_ptr<<4);
2753                                 idx_ptr++;
2754                                 next_idx = (__u8) *(data + 3 + idx_ptr);
2755                                 sub_idx = 0;
2756                         }
2757                         else
2758                                 sub_idx++;
2759
2760                         m_themes[idx+sub_idx] = *theme;
2761                 }
2762                 eDebug("themes finished %d found", m_themes.size());
2763                 // Themes table has been read, start reading the titles table.
2764                 startMHWReader(0xD2, 0x90);
2765                 startTimeout(4000);
2766                 return;
2767         }
2768         else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2769         // Titles table
2770         {
2771                 mhw_title_t *title = (mhw_title_t*) data;
2772
2773                 if ( title->channel_id == 0xFF )        // Separator
2774                         return; // Continue reading of the current table.
2775                 else
2776                 {
2777                         // Create unique key per title
2778                         __u32 title_id = ((title->channel_id)<<16)|((title->day)<<13)|((title->hours)<<8)|
2779                                 (title->minutes);
2780                         __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2781                                 ((title->program_id_ml)<<8)|(title->program_id_lo);
2782
2783                         if ( m_titles.find( title_id ) == m_titles.end() )
2784                         {
2785                                 startTimeout(4000);
2786                                 m_titles[ title_id ] = *title;
2787                                 if ( (title->summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2788                                         // program_ids will be used to gather summaries.
2789                                         m_program_ids[ program_id ] = title_id;
2790                                 return; // Continue reading of the current table.
2791                         }
2792                         else if (!checkTimeout())
2793                                 return;
2794                 }
2795                 if ( !m_program_ids.empty())
2796                 {
2797                         // Titles table has been read, there are summaries to read.
2798                         // Start reading summaries, store corresponding titles on the fly.
2799                         startMHWReader(0xD3, 0x90);
2800                         eDebug("titles finished %d titles, %d with summary",
2801                                 m_titles.size(),
2802                                 m_program_ids.size());
2803                         startTimeout(4000);
2804                         return;
2805                 }
2806         }
2807         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2808         // Summaries table
2809         {
2810                 mhw_summary_t *summary = (mhw_summary_t*) data;
2811
2812                 // Create unique key per record
2813                 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2814                         ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2815                 int len = ((data[1]&0xf)<<8) + data[2];
2816
2817                 // ugly workaround to convert const __u8* to char*
2818                 char *tmp=0;
2819                 memcpy(&tmp, &data, sizeof(void*));
2820                 tmp[len+3] = 0; // Terminate as a string.
2821
2822                 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2823                 if ( itProgid == m_program_ids.end() )
2824                 { /*    This part is to prevent to looping forever if some summaries are not received yet.
2825                         There is a timeout of 4 sec. after the last successfully read summary. */
2826                         if (!m_program_ids.empty() && !checkTimeout())
2827                                 return; // Continue reading of the current table.
2828                 }
2829                 else
2830                 {
2831                         std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2832
2833                         unsigned int pos=0;
2834                         while((pos = the_text.find("\r\n")) != std::string::npos)
2835                                 the_text.replace(pos, 2, " ");
2836
2837                         // Find corresponding title, store title and summary in epgcache.
2838                         std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2839                         if ( itTitle != m_titles.end() )
2840                         {
2841                                 startTimeout(4000);
2842                                 storeTitle( itTitle, the_text, data );
2843                                 m_titles.erase( itTitle );
2844                         }
2845                         m_program_ids.erase( itProgid );
2846                         if ( !m_program_ids.empty() )
2847                                 return; // Continue reading of the current table.
2848                 }
2849         }
2850         // Summaries have been read, titles that have summaries have been stored.
2851         // Now store titles that do not have summaries.
2852         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
2853                 storeTitle( itTitle, "", data );
2854         eDebug("[EPGC] mhw finished(%ld) %d summaries left",
2855                 eDVBLocalTimeHandler::getInstance()->nowTime(),
2856                 m_program_ids.size());
2857         isRunning &= ~MHW;
2858         m_MHWConn=0;
2859         if ( m_MHWReader )
2860                 m_MHWReader->stop();
2861         if (haveData)
2862                 finishEPG();
2863 }
2864
2865 #endif