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