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