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