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