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