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