9abd554e0b716b2de90e662eaa28a60c9f0f27f3
[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                                 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1721                 }
1722                 if (!tmp)
1723                 {
1724                         tmp = Py_None;
1725                         inc_refcount = true;
1726                 }
1727                 if (inc_refcount)
1728                         Py_INCREF(tmp);
1729                 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1730         }
1731 }
1732
1733 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1734 {
1735         if (convertFunc)
1736         {
1737                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1738                 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1739                 if (!result)
1740                 {
1741                         if (service_name)
1742                                 Py_DECREF(service_name);
1743                         if (nowTime)
1744                                 Py_DECREF(nowTime);
1745                         Py_DECREF(convertFuncArgs);
1746                         Py_DECREF(dest_list);
1747                         PyErr_SetString(PyExc_StandardError,
1748                                 "error in convertFunc execute");
1749                         eDebug("error in convertFunc execute");
1750                         return -1;
1751                 }
1752                 PyList_Append(dest_list, result);
1753                 Py_DECREF(result);
1754         }
1755         else
1756         {
1757                 ePyObject tuple = PyTuple_New(argcount);
1758                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1759                 PyList_Append(dest_list, tuple);
1760                 Py_DECREF(tuple);
1761         }
1762         return 0;
1763 }
1764
1765 // here we get a python list
1766 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1767 //   0 = PyLong(0)
1768 //   I = Event Id
1769 //   B = Event Begin Time
1770 //   D = Event Duration
1771 //   T = Event Title
1772 //   S = Event Short Description
1773 //   E = Event Extended Description
1774 //   C = Current Time
1775 //   R = Service Reference
1776 //   N = Service Name
1777 //   n = Short Service Name
1778 //   X = Return a minimum of one tuple per service in the result list... even when no event was found.
1779 //       The returned tuple is filled with all available infos... non avail is filled as None
1780 //       The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1781 // then for each service follows a tuple
1782 //   first tuple entry is the servicereference (as string... use the ref.toString() function)
1783 //   the second is the type of query
1784 //     2 = event_id
1785 //    -1 = event before given start_time
1786 //     0 = event intersects given start_time
1787 //    +1 = event after given start_time
1788 //   the third
1789 //      when type is eventid it is the event_id
1790 //      when type is time then it is the start_time ( -1 for now_time )
1791 //   the fourth is the end_time .. ( optional .. for query all events in time range)
1792
1793 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1794 {
1795         ePyObject convertFuncArgs;
1796         int argcount=0;
1797         const char *argstring=NULL;
1798         if (!PyList_Check(list))
1799         {
1800                 PyErr_SetString(PyExc_StandardError,
1801                         "type error");
1802                 eDebug("no list");
1803                 return NULL;
1804         }
1805         int listIt=0;
1806         int listSize=PyList_Size(list);
1807         if (!listSize)
1808         {
1809                 PyErr_SetString(PyExc_StandardError,
1810                         "not params given");
1811                 eDebug("not params given");
1812                 return NULL;
1813         }
1814         else 
1815         {
1816                 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1817                 if (PyString_Check(argv))
1818                 {
1819                         argstring = PyString_AS_STRING(argv);
1820                         ++listIt;
1821                 }
1822                 else
1823                         argstring = "I"; // just event id as default
1824                 argcount = strlen(argstring);
1825 //              eDebug("have %d args('%s')", argcount, argstring);
1826         }
1827
1828         bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1829         if (forceReturnOne)
1830                 --argcount;
1831
1832         if (convertFunc)
1833         {
1834                 if (!PyCallable_Check(convertFunc))
1835                 {
1836                         PyErr_SetString(PyExc_StandardError,
1837                                 "convertFunc must be callable");
1838                         eDebug("convertFunc is not callable");
1839                         return NULL;
1840                 }
1841                 convertFuncArgs = PyTuple_New(argcount);
1842         }
1843
1844         ePyObject nowTime = strchr(argstring, 'C') ?
1845                 PyLong_FromLong(::time(0)) :
1846                 ePyObject();
1847
1848         int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1849
1850         // create dest list
1851         ePyObject dest_list=PyList_New(0);
1852         while(listSize > listIt)
1853         {
1854                 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1855                 if (PyTuple_Check(item))
1856                 {
1857                         bool service_changed=false;
1858                         int type=0;
1859                         long event_id=-1;
1860                         time_t stime=-1;
1861                         int minutes=0;
1862                         int tupleSize=PyTuple_Size(item);
1863                         int tupleIt=0;
1864                         ePyObject service;
1865                         while(tupleSize > tupleIt)  // parse query args
1866                         {
1867                                 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1868                                 switch(tupleIt++)
1869                                 {
1870                                         case 0:
1871                                         {
1872                                                 if (!PyString_Check(entry))
1873                                                 {
1874                                                         eDebug("tuple entry 0 is no a string");
1875                                                         goto skip_entry;
1876                                                 }
1877                                                 service = entry;
1878                                                 break;
1879                                         }
1880                                         case 1:
1881                                                 type=PyInt_AsLong(entry);
1882                                                 if (type < -1 || type > 2)
1883                                                 {
1884                                                         eDebug("unknown type %d", type);
1885                                                         goto skip_entry;
1886                                                 }
1887                                                 break;
1888                                         case 2:
1889                                                 event_id=stime=PyInt_AsLong(entry);
1890                                                 break;
1891                                         case 3:
1892                                                 minutes=PyInt_AsLong(entry);
1893                                                 break;
1894                                         default:
1895                                                 eDebug("unneeded extra argument");
1896                                                 break;
1897                                 }
1898                         }
1899
1900                         if (minutes && stime == -1)
1901                                 stime = ::time(0);
1902
1903                         eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1904                         if (ref.type != eServiceReference::idDVB)
1905                         {
1906                                 eDebug("service reference for epg query is not valid");
1907                                 continue;
1908                         }
1909
1910                         // redirect subservice querys to parent service
1911                         eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1912                         if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1913                         {
1914                                 eServiceCenterPtr service_center;
1915                                 if (!eServiceCenter::getPrivInstance(service_center))
1916                                 {
1917                                         dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1918                                         dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1919                                         dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1920                                         dvb_ref.setParentServiceID(eServiceID(0));
1921                                         dvb_ref.name="";
1922                                         service = PyString_FromString(dvb_ref.toString().c_str());
1923                                         service_changed = true;
1924                                 }
1925                         }
1926
1927                         ePyObject service_name;
1928                         if (must_get_service_name)
1929                         {
1930                                 ePtr<iStaticServiceInformation> sptr;
1931                                 eServiceCenterPtr service_center;
1932                                 eServiceCenter::getPrivInstance(service_center);
1933                                 if (service_center)
1934                                 {
1935                                         service_center->info(ref, sptr);
1936                                         if (sptr)
1937                                         {
1938                                                 std::string name;
1939                                                 sptr->getName(ref, name);
1940
1941                                                 if (must_get_service_name == 1)
1942                                                 {
1943                                                         size_t pos;
1944                                                         // filter short name brakets
1945                                                         while((pos = name.find("\xc2\x86")) != std::string::npos)
1946                                                                 name.erase(pos,2);
1947                                                         while((pos = name.find("\xc2\x87")) != std::string::npos)
1948                                                                 name.erase(pos,2);
1949                                                 }
1950                                                 else
1951                                                         name = buildShortName(name);
1952
1953                                                 if (name.length())
1954                                                         service_name = PyString_FromString(name.c_str());
1955                                         }
1956                                 }
1957                                 if (!service_name)
1958                                         service_name = PyString_FromString("<n/a>");
1959                         }
1960                         if (minutes)
1961                         {
1962                                 singleLock s(cache_lock);
1963                                 if (!startTimeQuery(ref, stime, minutes))
1964                                 {
1965                                         while ( m_timemap_cursor != m_timemap_end )
1966                                         {
1967                                                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1968                                                 eServiceEvent evt;
1969                                                 evt.parseFrom(&ev, currentQueryTsidOnid);
1970                                                 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1971                                                         return 0;  // error
1972                                         }
1973                                 }
1974                                 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1975                                         return 0;  // error
1976                         }
1977                         else
1978                         {
1979                                 eServiceEvent evt;
1980                                 const eventData *ev_data=0;
1981                                 if (stime)
1982                                 {
1983                                         singleLock s(cache_lock);
1984                                         if (type == 2)
1985                                                 lookupEventId(ref, event_id, ev_data);
1986                                         else
1987                                                 lookupEventTime(ref, stime, ev_data, type);
1988                                         if (ev_data)
1989                                         {
1990                                                 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
1991                                                 Event ev((uint8_t*)ev_data->get());
1992                                                 evt.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
1993                                         }
1994                                 }
1995                                 if (ev_data)
1996                                 {
1997                                         if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1998                                                 return 0; // error
1999                                 }
2000                                 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2001                                         return 0; // error
2002                         }
2003                         if (service_changed)
2004                                 Py_DECREF(service);
2005                         if (service_name)
2006                                 Py_DECREF(service_name);
2007                 }
2008 skip_entry:
2009                 ;
2010         }
2011         if (convertFuncArgs)
2012                 Py_DECREF(convertFuncArgs);
2013         if (nowTime)
2014                 Py_DECREF(nowTime);
2015         return dest_list;
2016 }
2017
2018 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2019 {
2020         ePyObject tmp;
2021         int pos=0;
2022         while(pos < argcount)
2023         {
2024                 bool inc_refcount=false;
2025                 switch(argstring[pos])
2026                 {
2027                         case '0': // PyLong 0
2028                                 tmp = PyLong_FromLong(0);
2029                                 break;
2030                         case 'I': // Event Id
2031                                 tmp = PyLong_FromLong(evData->getEventID());
2032                                 break;
2033                         case 'B': // Event Begin Time
2034                                 if (ptr)
2035                                         tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2036                                 else
2037                                         tmp = PyLong_FromLong(evData->getStartTime());
2038                                 break;
2039                         case 'D': // Event Duration
2040                                 if (ptr)
2041                                         tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2042                                 else
2043                                         tmp = PyLong_FromLong(evData->getDuration());
2044                                 break;
2045                         case 'T': // Event Title
2046                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2047                                 break;
2048                         case 'S': // Event Short Description
2049                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2050                                 break;
2051                         case 'E': // Event Extended Description
2052                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2053                                 break;
2054                         case 'R': // service reference string
2055                                 tmp = service_reference;
2056                                 inc_refcount = true;
2057                                 break;
2058                         case 'n': // short service name
2059                         case 'N': // service name
2060                                 tmp = service_name;
2061                                 inc_refcount = true;
2062                                 break;
2063                         default:  // ignore unknown
2064                                 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2065                 }
2066                 if (!tmp)
2067                 {
2068                         tmp = Py_None;
2069                         inc_refcount = true;
2070                 }
2071                 if (inc_refcount)
2072                         Py_INCREF(tmp);
2073                 PyTuple_SET_ITEM(tuple, pos++, tmp);
2074         }
2075 }
2076
2077 // here we get a python tuple
2078 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2079 //   I = Event Id
2080 //   B = Event Begin Time
2081 //   D = Event Duration
2082 //   T = Event Title
2083 //   S = Event Short Description
2084 //   E = Event Extended Description
2085 //   R = Service Reference
2086 //   N = Service Name
2087 //   n = Short Service Name
2088 //  the second tuple entry is the MAX matches value
2089 //  the third tuple entry is the type of query
2090 //     0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2091 //     1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2092 //     2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2093 //  when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2094 //   the fourth is the servicereference string
2095 //   the fifth is the eventid
2096 //  when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2097 //   the fourth is the search text
2098 //   the fifth is
2099 //     0 = case sensitive (CASE_CHECK)
2100 //     1 = case insensitive (NO_CASECHECK)
2101
2102 PyObject *eEPGCache::search(ePyObject arg)
2103 {
2104         ePyObject ret;
2105         int descridx = -1;
2106         __u32 descr[512];
2107         int eventid = -1;
2108         const char *argstring=0;
2109         char *refstr=0;
2110         int argcount=0;
2111         int querytype=-1;
2112         bool needServiceEvent=false;
2113         int maxmatches=0;
2114         int must_get_service_name = 0;
2115         bool must_get_service_reference = false;
2116
2117         if (PyTuple_Check(arg))
2118         {
2119                 int tuplesize=PyTuple_Size(arg);
2120                 if (tuplesize > 0)
2121                 {
2122                         ePyObject obj = PyTuple_GET_ITEM(arg,0);
2123                         if (PyString_Check(obj))
2124                         {
2125 #if PY_VERSION_HEX < 0x02060000
2126                                 argcount = PyString_GET_SIZE(obj);
2127 #else
2128                                 argcount = PyString_Size(obj);
2129 #endif
2130                                 argstring = PyString_AS_STRING(obj);
2131                                 for (int i=0; i < argcount; ++i)
2132                                         switch(argstring[i])
2133                                         {
2134                                         case 'S':
2135                                         case 'E':
2136                                         case 'T':
2137                                                 needServiceEvent=true;
2138                                                 break;
2139                                         case 'N':
2140                                                 must_get_service_name = 1;
2141                                                 break;
2142                                         case 'n':
2143                                                 must_get_service_name = 2;
2144                                                 break;
2145                                         case 'R':
2146                                                 must_get_service_reference = true;
2147                                                 break;
2148                                         default:
2149                                                 break;
2150                                         }
2151                         }
2152                         else
2153                         {
2154                                 PyErr_SetString(PyExc_StandardError,
2155                                         "type error");
2156                                 eDebug("tuple arg 0 is not a string");
2157                                 return NULL;
2158                         }
2159                 }
2160                 if (tuplesize > 1)
2161                         maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2162                 if (tuplesize > 2)
2163                 {
2164                         querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2165                         if (tuplesize > 4 && querytype == 0)
2166                         {
2167                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2168                                 if (PyString_Check(obj))
2169                                 {
2170                                         refstr = PyString_AS_STRING(obj);
2171                                         eServiceReferenceDVB ref(refstr);
2172                                         if (ref.valid())
2173                                         {
2174                                                 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2175                                                 singleLock s(cache_lock);
2176                                                 const eventData *evData = 0;
2177                                                 lookupEventId(ref, eventid, evData);
2178                                                 if (evData)
2179                                                 {
2180                                                         __u8 *data = evData->EITdata;
2181                                                         int tmp = evData->ByteSize-10;
2182                                                         __u32 *p = (__u32*)(data+10);
2183                                                                 // search short and extended event descriptors
2184                                                         while(tmp>3)
2185                                                         {
2186                                                                 __u32 crc = *p++;
2187                                                                 descriptorMap::iterator it =
2188                                                                         eventData::descriptors.find(crc);
2189                                                                 if (it != eventData::descriptors.end())
2190                                                                 {
2191                                                                         __u8 *descr_data = it->second.second;
2192                                                                         switch(descr_data[0])
2193                                                                         {
2194                                                                         case 0x4D ... 0x4E:
2195                                                                                 descr[++descridx]=crc;
2196                                                                         default:
2197                                                                                 break;
2198                                                                         }
2199                                                                 }
2200                                                                 tmp-=4;
2201                                                         }
2202                                                 }
2203                                                 if (descridx<0)
2204                                                         eDebug("event not found");
2205                                         }
2206                                         else
2207                                         {
2208                                                 PyErr_SetString(PyExc_StandardError, "type error");
2209                                                 eDebug("tuple arg 4 is not a valid service reference string");
2210                                                 return NULL;
2211                                         }
2212                                 }
2213                                 else
2214                                 {
2215                                         PyErr_SetString(PyExc_StandardError, "type error");
2216                                         eDebug("tuple arg 4 is not a string");
2217                                         return NULL;
2218                                 }
2219                         }
2220                         else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2221                         {
2222                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2223                                 if (PyString_Check(obj))
2224                                 {
2225                                         int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2226                                         const char *str = PyString_AS_STRING(obj);
2227 #if PY_VERSION_HEX < 0x02060000
2228                                         int textlen = PyString_GET_SIZE(obj);
2229 #else
2230                                         int textlen = PyString_Size(obj);
2231 #endif
2232                                         if (querytype == 1)
2233                                                 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2234                                         else
2235                                                 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2236                                         singleLock s(cache_lock);
2237                                         for (descriptorMap::iterator it(eventData::descriptors.begin());
2238                                                 it != eventData::descriptors.end() && descridx < 511; ++it)
2239                                         {
2240                                                 __u8 *data = it->second.second;
2241                                                 if ( data[0] == 0x4D ) // short event descriptor
2242                                                 {
2243                                                         int title_len = data[5];
2244                                                         if ( querytype == 1 )
2245                                                         {
2246                                                                 int offs = 6;
2247                                                                 // skip DVB-Text Encoding!
2248                                                                 if (data[6] == 0x10)
2249                                                                 {
2250                                                                         offs+=3;
2251                                                                         title_len-=3;
2252                                                                 }
2253                                                                 else if(data[6] > 0 && data[6] < 0x20)
2254                                                                 {
2255                                                                         offs+=1;
2256                                                                         title_len-=1;
2257                                                                 }
2258                                                                 if (title_len != textlen)
2259                                                                         continue;
2260                                                                 if ( casetype )
2261                                                                 {
2262                                                                         if ( !strncasecmp((const char*)data+offs, str, title_len) )
2263                                                                         {
2264 //                                                                              std::string s((const char*)data+offs, title_len);
2265 //                                                                              eDebug("match1 %s %s", str, s.c_str() );
2266                                                                                 descr[++descridx] = it->first;
2267                                                                         }
2268                                                                 }
2269                                                                 else if ( !strncmp((const char*)data+offs, str, title_len) )
2270                                                                 {
2271 //                                                                      std::string s((const char*)data+offs, title_len);
2272 //                                                                      eDebug("match2 %s %s", str, s.c_str() );
2273                                                                         descr[++descridx] = it->first;
2274                                                                 }
2275                                                         }
2276                                                         else
2277                                                         {
2278                                                                 int idx=0;
2279                                                                 while((title_len-idx) >= textlen)
2280                                                                 {
2281                                                                         if (casetype)
2282                                                                         {
2283                                                                                 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2284                                                                                 {
2285                                                                                         descr[++descridx] = it->first;
2286 //                                                                                      std::string s((const char*)data+6, title_len);
2287 //                                                                                      eDebug("match 3 %s %s", str, s.c_str() );
2288                                                                                         break;
2289                                                                                 }
2290                                                                         }
2291                                                                         else if (!strncmp((const char*)data+6+idx, str, textlen) )
2292                                                                         {
2293                                                                                 descr[++descridx] = it->first;
2294 //                                                                              std::string s((const char*)data+6, title_len);
2295 //                                                                              eDebug("match 4 %s %s", str, s.c_str() );
2296                                                                                 break;
2297                                                                         }
2298                                                                         ++idx;
2299                                                                 }
2300                                                         }
2301                                                 }
2302                                         }
2303                                 }
2304                                 else
2305                                 {
2306                                         PyErr_SetString(PyExc_StandardError,
2307                                                 "type error");
2308                                         eDebug("tuple arg 4 is not a string");
2309                                         return NULL;
2310                                 }
2311                         }
2312                         else
2313                         {
2314                                 PyErr_SetString(PyExc_StandardError,
2315                                         "type error");
2316                                 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2317                                 return NULL;
2318                         }
2319                 }
2320                 else
2321                 {
2322                         PyErr_SetString(PyExc_StandardError,
2323                                 "type error");
2324                         eDebug("not enough args in tuple");
2325                         return NULL;
2326                 }
2327         }
2328         else
2329         {
2330                 PyErr_SetString(PyExc_StandardError,
2331                         "type error");
2332                 eDebug("arg 0 is not a tuple");
2333                 return NULL;
2334         }
2335
2336         if (descridx > -1)
2337         {
2338                 int maxcount=maxmatches;
2339                 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2340                 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2341                 // in this case we start searching with the base service
2342                 bool first = ref.valid() ? true : false;
2343                 singleLock s(cache_lock);
2344                 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2345                 while(cit != eventDB.end() && maxcount)
2346                 {
2347                         if ( ref.valid() && !first && cit->first == ref )
2348                         {
2349                                 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2350                                 ++cit;
2351                                 continue;
2352                         }
2353                         ePyObject service_name;
2354                         ePyObject service_reference;
2355                         timeMap &evmap = cit->second.second;
2356                         // check all events
2357                         for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2358                         {
2359                                 int evid = evit->second->getEventID();
2360                                 if ( evid == eventid)
2361                                         continue;
2362                                 __u8 *data = evit->second->EITdata;
2363                                 int tmp = evit->second->ByteSize-10;
2364                                 __u32 *p = (__u32*)(data+10);
2365                                 // check if any of our descriptor used by this event
2366                                 int cnt=-1;
2367                                 while(tmp>3)
2368                                 {
2369                                         __u32 crc32 = *p++;
2370                                         for ( int i=0; i <= descridx; ++i)
2371                                         {
2372                                                 if (descr[i] == crc32)  // found...
2373                                                         ++cnt;
2374                                         }
2375                                         tmp-=4;
2376                                 }
2377                                 if ( (querytype == 0 && cnt == descridx) ||
2378                                          ((querytype == 1 || querytype == 2) && cnt != -1) )
2379                                 {
2380                                         const uniqueEPGKey &service = cit->first;
2381                                         eServiceReference ref =
2382                                                 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2383                                         if (ref.valid())
2384                                         {
2385                                         // create servive event
2386                                                 eServiceEvent ptr;
2387                                                 const eventData *ev_data=0;
2388                                                 if (needServiceEvent)
2389                                                 {
2390                                                         if (lookupEventId(ref, evid, ev_data))
2391                                                                 eDebug("event not found !!!!!!!!!!!");
2392                                                         else
2393                                                         {
2394                                                                 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2395                                                                 Event ev((uint8_t*)ev_data->get());
2396                                                                 ptr.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2397                                                         }
2398                                                 }
2399                                         // create service name
2400                                                 if (must_get_service_name && !service_name)
2401                                                 {
2402                                                         ePtr<iStaticServiceInformation> sptr;
2403                                                         eServiceCenterPtr service_center;
2404                                                         eServiceCenter::getPrivInstance(service_center);
2405                                                         if (service_center)
2406                                                         {
2407                                                                 service_center->info(ref, sptr);
2408                                                                 if (sptr)
2409                                                                 {
2410                                                                         std::string name;
2411                                                                         sptr->getName(ref, name);
2412
2413                                                                         if (must_get_service_name == 1)
2414                                                                         {
2415                                                                                 size_t pos;
2416                                                                                 // filter short name brakets
2417                                                                                 while((pos = name.find("\xc2\x86")) != std::string::npos)
2418                                                                                         name.erase(pos,2);
2419                                                                                 while((pos = name.find("\xc2\x87")) != std::string::npos)
2420                                                                                         name.erase(pos,2);
2421                                                                         }
2422                                                                         else
2423                                                                                 name = buildShortName(name);
2424
2425                                                                         if (name.length())
2426                                                                                 service_name = PyString_FromString(name.c_str());
2427                                                                 }
2428                                                         }
2429                                                         if (!service_name)
2430                                                                 service_name = PyString_FromString("<n/a>");
2431                                                 }
2432                                         // create servicereference string
2433                                                 if (must_get_service_reference && !service_reference)
2434                                                         service_reference = PyString_FromString(ref.toString().c_str());
2435                                         // create list
2436                                                 if (!ret)
2437                                                         ret = PyList_New(0);
2438                                         // create tuple
2439                                                 ePyObject tuple = PyTuple_New(argcount);
2440                                         // fill tuple
2441                                                 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2442                                                 PyList_Append(ret, tuple);
2443                                                 Py_DECREF(tuple);
2444                                                 --maxcount;
2445                                         }
2446                                 }
2447                         }
2448                         if (service_name)
2449                                 Py_DECREF(service_name);
2450                         if (service_reference)
2451                                 Py_DECREF(service_reference);
2452                         if (first)
2453                         {
2454                                 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2455                                 first=false;
2456                                 cit=eventDB.begin();
2457                         }
2458                         else
2459                                 ++cit;
2460                 }
2461         }
2462
2463         if (!ret)
2464                 Py_RETURN_NONE;
2465
2466         return ret;
2467 }
2468
2469 #ifdef ENABLE_PRIVATE_EPG
2470 #include <dvbsi++/descriptor_tag.h>
2471 #include <dvbsi++/unknown_descriptor.h>
2472 #include <dvbsi++/private_data_specifier_descriptor.h>
2473
2474 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2475 {
2476         ePtr<eTable<ProgramMapSection> > ptr;
2477         if (!pmthandler->getPMT(ptr) && ptr)
2478         {
2479                 std::vector<ProgramMapSection*>::const_iterator i;
2480                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2481                 {
2482                         const ProgramMapSection &pmt = **i;
2483
2484                         ElementaryStreamInfoConstIterator es;
2485                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2486                         {
2487                                 int tmp=0;
2488                                 switch ((*es)->getType())
2489                                 {
2490                                 case 0x05: // private
2491                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2492                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2493                                         {
2494                                                 switch ((*desc)->getTag())
2495                                                 {
2496                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2497                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2498                                                                         tmp |= 1;
2499                                                                 break;
2500                                                         case 0x90:
2501                                                         {
2502                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2503                                                                 int descr_len = descr->getLength();
2504                                                                 if (descr_len == 4)
2505                                                                 {
2506                                                                         uint8_t data[descr_len+2];
2507                                                                         descr->writeToBuffer(data);
2508                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2509                                                                                 tmp |= 2;
2510                                                                 }
2511                                                                 break;
2512                                                         }
2513                                                         default:
2514                                                                 break;
2515                                                 }
2516                                         }
2517                                 default:
2518                                         break;
2519                                 }
2520                                 if (tmp==3)
2521                                 {
2522                                         eServiceReferenceDVB ref;
2523                                         if (!pmthandler->getServiceReference(ref))
2524                                         {
2525                                                 int pid = (*es)->getPid();
2526                                                 messages.send(Message(Message::got_private_pid, ref, pid));
2527                                                 return;
2528                                         }
2529                                 }
2530                         }
2531                 }
2532         }
2533         else
2534                 eDebug("PMTready but no pmt!!");
2535 }
2536
2537 struct date_time
2538 {
2539         __u8 data[5];
2540         time_t tm;
2541         date_time( const date_time &a )
2542         {
2543                 memcpy(data, a.data, 5);
2544                 tm = a.tm;
2545         }
2546         date_time( const __u8 data[5])
2547         {
2548                 memcpy(this->data, data, 5);
2549                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2550         }
2551         date_time()
2552         {
2553         }
2554         const __u8& operator[](int pos) const
2555         {
2556                 return data[pos];
2557         }
2558 };
2559
2560 struct less_datetime
2561 {
2562         bool operator()( const date_time &a, const date_time &b ) const
2563         {
2564                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2565         }
2566 };
2567
2568 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
2569 {
2570         contentMap &content_time_table = content_time_tables[current_service];
2571         singleLock s(cache_lock);
2572         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2573         eventMap &evMap = eventDB[current_service].first;
2574         timeMap &tmMap = eventDB[current_service].second;
2575         int ptr=8;
2576         int content_id = data[ptr++] << 24;
2577         content_id |= data[ptr++] << 16;
2578         content_id |= data[ptr++] << 8;
2579         content_id |= data[ptr++];
2580
2581         contentTimeMap &time_event_map =
2582                 content_time_table[content_id];
2583         for ( contentTimeMap::iterator it( time_event_map.begin() );
2584                 it != time_event_map.end(); ++it )
2585         {
2586                 eventMap::iterator evIt( evMap.find(it->second.second) );
2587                 if ( evIt != evMap.end() )
2588                 {
2589                         delete evIt->second;
2590                         evMap.erase(evIt);
2591                 }
2592                 tmMap.erase(it->second.first);
2593         }
2594         time_event_map.clear();
2595
2596         __u8 duration[3];
2597         memcpy(duration, data+ptr, 3);
2598         ptr+=3;
2599         int duration_sec =
2600                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2601
2602         const __u8 *descriptors[65];
2603         const __u8 **pdescr = descriptors;
2604
2605         int descriptors_length = (data[ptr++]&0x0F) << 8;
2606         descriptors_length |= data[ptr++];
2607         while ( descriptors_length > 1 )
2608         {
2609                 int descr_type = data[ptr];
2610                 int descr_len = data[ptr+1];
2611                 descriptors_length -= 2;
2612                 if (descriptors_length >= descr_len)
2613                 {
2614                         descriptors_length -= descr_len;
2615                         if ( descr_type == 0xf2 && descr_len > 5)
2616                         {
2617                                 ptr+=2;
2618                                 int tsid = data[ptr++] << 8;
2619                                 tsid |= data[ptr++];
2620                                 int onid = data[ptr++] << 8;
2621                                 onid |= data[ptr++];
2622                                 int sid = data[ptr++] << 8;
2623                                 sid |= data[ptr++];
2624
2625 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2626                                 if ( onid == 0x85 )
2627                                 {
2628                                         switch( (tsid << 16) | sid )
2629                                         {
2630                                                 case 0x01030b: sid = 0x1b; tsid = 4; break;  // Premiere Win
2631                                                 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2632                                                 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2633                                                 case 0x0300f5: sid = 0xdc; break;
2634                                                 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2635                                                 case 0x1100d3: sid = 0xe3; break;
2636                                                 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2637                                         }
2638                                 }
2639 ////////////////////////////////////////////
2640
2641                                 uniqueEPGKey service( sid, onid, tsid );
2642                                 descr_len -= 6;
2643                                 while( descr_len > 2 )
2644                                 {
2645                                         __u8 datetime[5];
2646                                         datetime[0] = data[ptr++];
2647                                         datetime[1] = data[ptr++];
2648                                         int tmp_len = data[ptr++];
2649                                         descr_len -= 3;
2650                                         if (descr_len >= tmp_len)
2651                                         {
2652                                                 descr_len -= tmp_len;
2653                                                 while( tmp_len > 2 )
2654                                                 {
2655                                                         memcpy(datetime+2, data+ptr, 3);
2656                                                         ptr += 3;
2657                                                         tmp_len -= 3;
2658                                                         start_times[datetime].push_back(service);
2659                                                 }
2660                                         }
2661                                 }
2662                         }
2663                         else
2664                         {
2665                                 *pdescr++=data+ptr;
2666                                 ptr += 2;
2667                                 ptr += descr_len;
2668                         }
2669                 }
2670         }
2671         ASSERT(pdescr <= &descriptors[65])
2672         __u8 event[4098];
2673         eit_event_struct *ev_struct = (eit_event_struct*) event;
2674         ev_struct->running_status = 0;
2675         ev_struct->free_CA_mode = 1;
2676         memcpy(event+7, duration, 3);
2677         ptr = 12;
2678         const __u8 **d=descriptors;
2679         while ( d < pdescr )
2680         {
2681                 memcpy(event+ptr, *d, ((*d)[1])+2);
2682                 ptr+=(*d++)[1];
2683                 ptr+=2;
2684         }
2685         ASSERT(ptr <= 4098);
2686         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2687         {
2688                 time_t now = ::time(0);
2689                 if ( (it->first.tm + duration_sec) < now )
2690                         continue;
2691                 memcpy(event+2, it->first.data, 5);
2692                 int bptr = ptr;
2693                 int cnt=0;
2694                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2695                 {
2696                         event[bptr++] = 0x4A;
2697                         __u8 *len = event+(bptr++);
2698                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
2699                         event[bptr++] = (i->tsid & 0xFF);
2700                         event[bptr++] = (i->onid & 0xFF00) >> 8;
2701                         event[bptr++] = (i->onid & 0xFF);
2702                         event[bptr++] = (i->sid & 0xFF00) >> 8;
2703                         event[bptr++] = (i->sid & 0xFF);
2704                         event[bptr++] = 0xB0;
2705                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2706                         *len = ((event+bptr) - len)-1;
2707                 }
2708                 int llen = bptr - 12;
2709                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2710                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2711
2712                 time_t stime = it->first.tm;
2713                 while( tmMap.find(stime) != tmMap.end() )
2714                         ++stime;
2715                 event[6] += (stime - it->first.tm);
2716                 __u16 event_id = 0;
2717                 while( evMap.find(event_id) != evMap.end() )
2718                         ++event_id;
2719                 event[0] = (event_id & 0xFF00) >> 8;
2720                 event[1] = (event_id & 0xFF);
2721                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2722                 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2723                 evMap[event_id] = d;
2724                 tmMap[stime] = d;
2725                 ASSERT(bptr <= 4098);
2726         }
2727 }
2728
2729 void eEPGCache::channel_data::startPrivateReader()
2730 {
2731         eDVBSectionFilterMask mask;
2732         memset(&mask, 0, sizeof(mask));
2733         mask.pid = m_PrivatePid;
2734         mask.flags = eDVBSectionFilterMask::rfCRC;
2735         mask.data[0] = 0xA0;
2736         mask.mask[0] = 0xFF;
2737         eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2738         if (m_PrevVersion != -1)
2739         {
2740                 mask.data[3] = m_PrevVersion << 1;
2741                 mask.mask[3] = 0x3E;
2742                 mask.mode[3] = 0x3E;
2743         }
2744         seenPrivateSections.clear();
2745         if (!m_PrivateConn)
2746                 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2747         m_PrivateReader->start(mask);
2748 }
2749
2750 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2751 {
2752         if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2753         {
2754                 cache->privateSectionRead(m_PrivateService, data);
2755                 seenPrivateSections.insert(data[6]);
2756         }
2757         if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2758         {
2759                 eDebug("[EPGC] private finished");
2760                 eDVBChannelID chid = channel->getChannelID();
2761                 int tmp = chid.original_network_id.get();
2762                 tmp |= 0x80000000; // we use highest bit as private epg indicator
2763                 chid.original_network_id = tmp;
2764                 cache->channelLastUpdated[chid] = ::time(0);
2765                 m_PrevVersion = (data[5] & 0x3E) >> 1;
2766                 startPrivateReader();
2767         }
2768 }
2769
2770 #endif // ENABLE_PRIVATE_EPG
2771
2772 #ifdef ENABLE_MHW_EPG
2773 void eEPGCache::channel_data::cleanup()
2774 {
2775         m_channels.clear();
2776         m_themes.clear();
2777         m_titles.clear();
2778         m_program_ids.clear();
2779 }
2780
2781 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2782 {
2783         // Names in mhw structs are not strings as they are not '\0' terminated.
2784         // This function converts the mhw name into a string.
2785         // Constraint: "length of out" = "length of in" + 1.
2786         int i;
2787         for ( i=0; i < len_in; i++ )
2788                 out[i] = in[i];
2789
2790         i = len_in - 1;
2791         while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2792                 i--;
2793
2794         out[i+1] = 0;
2795         return out;
2796 }
2797
2798 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2799 // For time of day
2800 {
2801         return_time[0] = toBCD( hours );
2802         return_time[1] = toBCD( minutes );
2803         return_time[2] = 0;
2804 }
2805
2806 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2807 {
2808         timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2809 }
2810
2811 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2812 // For date plus time of day
2813 {
2814         // Remove offset in mhw time.
2815         __u8 local_hours = hours;
2816         if ( hours >= 16 )
2817                 local_hours -= 4;
2818         else if ( hours >= 8 )
2819                 local_hours -= 2;
2820
2821         // As far as we know all mhw time data is sent in central Europe time zone.
2822         // So, temporarily set timezone to western europe
2823         time_t dt = ::time(0);
2824
2825         char *old_tz = getenv( "TZ" );
2826         putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2827         tzset();
2828
2829         tm localnow;
2830         localtime_r(&dt, &localnow);
2831
2832         if (day == 7)
2833                 day = 0;
2834         if ( day + 1 < localnow.tm_wday )               // day + 1 to prevent old events to show for next week.
2835                 day += 7;
2836         if (local_hours <= 5)
2837                 day++;
2838
2839         dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2840         dt += 3600*(local_hours - localnow.tm_hour);  // Shift dt to the recording hour.
2841
2842         tm recdate;
2843         gmtime_r( &dt, &recdate );   // This will also take care of DST.
2844
2845         if ( old_tz == NULL )
2846                 unsetenv( "TZ" );
2847         else
2848                 putenv( old_tz );
2849         tzset();
2850
2851         // Calculate MJD according to annex in ETSI EN 300 468
2852         int l=0;
2853         if ( recdate.tm_mon <= 1 )      // Jan or Feb
2854                 l=1;
2855         int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2856                 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2857
2858         return_time[0] = (mjd & 0xFF00)>>8;
2859         return_time[1] = mjd & 0xFF;
2860
2861         timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2862 }
2863
2864 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2865 // data is borrowed from calling proc to save memory space.
2866 {
2867         __u8 name[34];
2868
2869         // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2870         bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2871                 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2872
2873         eit_t *packet = (eit_t *) data;
2874         packet->table_id = 0x50;
2875         packet->section_syntax_indicator = 1;
2876
2877         packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2878         packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2879         packet->version_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2880         packet->current_next_indicator = 0;
2881         packet->section_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2882         packet->last_section_number = 0;        // eEPGCache::sectionRead() will dig this for the moment
2883         packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2884         packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2885         packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2886         packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2887         packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2888         packet->segment_last_table_id = 0x50;
2889
2890         __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2891         std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2892         int prog_title_length = prog_title.length();
2893
2894         int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2895                 prog_title_length + 1;
2896
2897         eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2898         event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2899         event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2900
2901         if (isMHW2)
2902         {
2903                 u_char *data = (u_char*) event_data;
2904                 data[2] = itTitle->second.mhw2_mjd_hi;
2905                 data[3] = itTitle->second.mhw2_mjd_lo;
2906                 data[4] = itTitle->second.mhw2_hours;
2907                 data[5] = itTitle->second.mhw2_minutes;
2908                 data[6] = itTitle->second.mhw2_seconds;
2909                 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2910         }
2911         else
2912         {
2913                 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2914                 (u_char *) event_data + 2 );
2915                 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2916         }
2917
2918         event_data->running_status = 0;
2919         event_data->free_CA_mode = 0;
2920         int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2921
2922         eit_short_event_descriptor_struct *short_event_descriptor =
2923                 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2924         short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2925         short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2926                 prog_title_length - 1;
2927         short_event_descriptor->language_code_1 = 'e';
2928         short_event_descriptor->language_code_2 = 'n';
2929         short_event_descriptor->language_code_3 = 'g';
2930         short_event_descriptor->event_name_length = prog_title_length;
2931         u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2932         memcpy(event_name, prog_title.c_str(), prog_title_length);
2933
2934         // Set text length
2935         event_name[prog_title_length] = 0;
2936
2937         if ( sumText.length() > 0 )
2938         // There is summary info
2939         {
2940                 unsigned int sum_length = sumText.length();
2941                 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2942                 // Store summary in short event descriptor
2943                 {
2944                         // Increase all relevant lengths
2945                         event_name[prog_title_length] = sum_length;
2946                         short_event_descriptor->descriptor_length += sum_length;
2947                         packet_length += sum_length;
2948                         descr_ll += sum_length;
2949                         sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2950                 }
2951                 else
2952                 // Store summary in extended event descriptors
2953                 {
2954                         int remaining_sum_length = sumText.length();
2955                         int nbr_descr = int(remaining_sum_length/247) + 1;
2956                         for ( int i=0; i < nbr_descr; i++)
2957                         // Loop once per extended event descriptor
2958                         {
2959                                 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2960                                 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2961                                 remaining_sum_length -= sum_length;
2962                                 packet_length += 8 + sum_length;
2963                                 descr_ll += 8 + sum_length;
2964
2965                                 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2966                                 ext_event_descriptor->descriptor_length = sum_length + 6;
2967                                 ext_event_descriptor->descriptor_number = i;
2968                                 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2969                                 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2970                                 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2971                                 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2972                                 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2973                                 the_text[-2] = 0;
2974                                 the_text[-1] = sum_length;
2975                                 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2976                         }
2977                 }
2978         }
2979
2980         if (!isMHW2)
2981         {
2982                 // Add content descriptor
2983                 u_char *descriptor = (u_char *) data + packet_length;
2984                 packet_length += 4;
2985                 descr_ll += 4;
2986
2987                 int content_id = 0;
2988                 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2989                 if ( content_descr.find( "FILM" ) != std::string::npos )
2990                         content_id = 0x10;
2991                 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2992                         content_id = 0x40;
2993
2994                 descriptor[0] = 0x54;
2995                 descriptor[1] = 2;
2996                 descriptor[2] = content_id;
2997                 descriptor[3] = 0;
2998         }
2999
3000         event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
3001         event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
3002
3003         packet->section_length_hi =  ((packet_length - 3)&0xf00)>>8;
3004         packet->section_length_lo =  (packet_length - 3)&0xff;
3005
3006         // Feed the data to eEPGCache::sectionRead()
3007         cache->sectionRead( data, MHW, this );
3008 }
3009
3010 void eEPGCache::channel_data::startTimeout(int msec)
3011 {
3012         m_MHWTimeoutTimer->start(msec,true);
3013         m_MHWTimeoutet=false;
3014 }
3015
3016 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
3017 {
3018         m_MHWFilterMask.pid = pid;
3019         m_MHWFilterMask.data[0] = tid;
3020         m_MHWReader->start(m_MHWFilterMask);
3021 //      eDebug("start 0x%02x 0x%02x", pid, tid);
3022 }
3023
3024 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
3025 {
3026         m_MHWFilterMask2.pid = pid;
3027         m_MHWFilterMask2.data[0] = tid;
3028         if (ext != -1)
3029         {
3030                 m_MHWFilterMask2.data[1] = ext;
3031                 m_MHWFilterMask2.mask[1] = 0xFF;
3032 //              eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
3033         }
3034         else
3035         {
3036                 m_MHWFilterMask2.data[1] = 0;
3037                 m_MHWFilterMask2.mask[1] = 0;
3038 //              eDebug("start 0x%02x 0x%02x", pid, tid);
3039         }
3040         m_MHWReader2->start(m_MHWFilterMask2);
3041 }
3042
3043 void eEPGCache::channel_data::readMHWData(const __u8 *data)
3044 {
3045         if ( m_MHWReader2 )
3046                 m_MHWReader2->stop();
3047
3048         if ( state > 1 || // aborted
3049                 // have si data.. so we dont read mhw data
3050                 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3051         {
3052                 eDebug("[EPGC] mhw aborted %d", state);
3053         }
3054         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
3055         // Channels table
3056         {
3057                 int len = ((data[1]&0xf)<<8) + data[2] - 1;
3058                 int record_size = sizeof( mhw_channel_name_t );
3059                 int nbr_records = int (len/record_size);
3060
3061                 m_channels.resize(nbr_records);
3062                 for ( int i = 0; i < nbr_records; i++ )
3063                 {
3064                         mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
3065                         m_channels[i]=*channel;
3066                 }
3067                 haveData |= MHW;
3068
3069                 eDebug("[EPGC] mhw %d channels found", m_channels.size());
3070
3071                 // Channels table has been read, start reading the themes table.
3072                 startMHWReader(0xD3, 0x92);
3073                 return;
3074         }
3075         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
3076         // Themes table
3077         {
3078                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3079                 int record_size = sizeof( mhw_theme_name_t );
3080                 int nbr_records = int (len/record_size);
3081                 int idx_ptr = 0;
3082                 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
3083                 __u8 idx = 0;
3084                 __u8 sub_idx = 0;
3085                 for ( int i = 0; i < nbr_records; i++ )
3086                 {
3087                         mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
3088                         if ( i >= next_idx )
3089                         {
3090                                 idx = (idx_ptr<<4);
3091                                 idx_ptr++;
3092                                 next_idx = (__u8) *(data + 3 + idx_ptr);
3093                                 sub_idx = 0;
3094                         }
3095                         else
3096                                 sub_idx++;
3097
3098                         m_themes[idx+sub_idx] = *theme;
3099                 }
3100                 eDebug("[EPGC] mhw %d themes found", m_themes.size());
3101                 // Themes table has been read, start reading the titles table.
3102                 startMHWReader(0xD2, 0x90);
3103                 startTimeout(4000);
3104                 return;
3105         }
3106         else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3107         // Titles table
3108         {
3109                 mhw_title_t *title = (mhw_title_t*) data;
3110
3111                 if ( title->channel_id == 0xFF )        // Separator
3112                         return; // Continue reading of the current table.
3113                 else
3114                 {
3115                         // Create unique key per title
3116                         __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
3117                                 (title->ms.minutes);
3118                         __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
3119                                 ((title->program_id_ml)<<8)|(title->program_id_lo);
3120
3121                         if ( m_titles.find( title_id ) == m_titles.end() )
3122                         {
3123                                 startTimeout(4000);
3124                                 title->mhw2_mjd_hi = 0;
3125                                 title->mhw2_mjd_lo = 0;
3126                                 title->mhw2_duration_hi = 0;
3127                                 title->mhw2_duration_lo = 0;
3128                                 m_titles[ title_id ] = *title;
3129                                 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3130                                         // program_ids will be used to gather summaries.
3131                                         m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3132                                 return; // Continue reading of the current table.
3133                         }
3134                         else if (!checkTimeout())
3135                                 return;
3136                 }
3137                 if ( !m_program_ids.empty())
3138                 {
3139                         // Titles table has been read, there are summaries to read.
3140                         // Start reading summaries, store corresponding titles on the fly.
3141                         startMHWReader(0xD3, 0x90);
3142                         eDebug("[EPGC] mhw %d titles(%d with summary) found",
3143                                 m_titles.size(),
3144                                 m_program_ids.size());
3145                         startTimeout(4000);
3146                         return;
3147                 }
3148         }
3149         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3150         // Summaries table
3151         {
3152                 mhw_summary_t *summary = (mhw_summary_t*) data;
3153
3154                 // Create unique key per record
3155                 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3156                         ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3157                 int len = ((data[1]&0xf)<<8) + data[2];
3158
3159                 // ugly workaround to convert const __u8* to char*
3160                 char *tmp=0;
3161                 memcpy(&tmp, &data, sizeof(void*));
3162                 tmp[len+3] = 0; // Terminate as a string.
3163
3164                 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3165                 if ( itProgid == m_program_ids.end() )
3166                 { /*    This part is to prevent to looping forever if some summaries are not received yet.
3167                         There is a timeout of 4 sec. after the last successfully read summary. */
3168                         if (!m_program_ids.empty() && !checkTimeout())
3169                                 return; // Continue reading of the current table.
3170                 }
3171                 else
3172                 {
3173                         std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3174
3175                         unsigned int pos=0;
3176                         while((pos = the_text.find("\r\n")) != std::string::npos)
3177                                 the_text.replace(pos, 2, " ");
3178
3179                         // Find corresponding title, store title and summary in epgcache.
3180                         std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3181                         if ( itTitle != m_titles.end() )
3182                         {
3183                                 startTimeout(4000);
3184                                 storeTitle( itTitle, the_text, data );
3185                                 m_titles.erase( itTitle );
3186                         }
3187                         m_program_ids.erase( itProgid );
3188                         if ( !m_program_ids.empty() )
3189                                 return; // Continue reading of the current table.
3190                 }
3191         }
3192         eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3193                 ::time(0),
3194                 m_program_ids.size());
3195         // Summaries have been read, titles that have summaries have been stored.
3196         // Now store titles that do not have summaries.
3197         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3198                 storeTitle( itTitle, "", data );
3199         isRunning &= ~MHW;
3200         m_MHWConn=0;
3201         if ( m_MHWReader )
3202                 m_MHWReader->stop();
3203         if (haveData)
3204                 finishEPG();
3205 }
3206
3207 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3208 {
3209         int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3210
3211         if ( m_MHWReader )
3212                 m_MHWReader->stop();
3213
3214         if ( state > 1 || // aborted
3215                 // have si data.. so we dont read mhw data
3216                 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3217         {
3218                 eDebug("[EPGC] mhw2 aborted %d", state);
3219         }
3220         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3221         // Channels table
3222         {
3223                 int num_channels = data[119];
3224                 m_channels.resize(num_channels);
3225                 if(dataLen > 119)
3226                 {
3227                         int ptr = 120 + 8 * num_channels;
3228                         if( dataLen > ptr )
3229                         {
3230                                 for( int chid = 0; chid < num_channels; ++chid )
3231                                 {
3232                                         ptr += ( data[ptr] & 0x0f ) + 1;
3233                                         if( dataLen < ptr )
3234                                                 goto abort;
3235                                 }
3236                         }
3237                         else
3238                                 goto abort;
3239                 }
3240                 else
3241                         goto abort;
3242                 // data seems consistent...
3243                 const __u8 *tmp = data+120;
3244                 for (int i=0; i < num_channels; ++i)
3245                 {
3246                         mhw_channel_name_t channel;
3247                         channel.network_id_hi = *(tmp++);
3248                         channel.network_id_lo = *(tmp++);
3249                         channel.transport_stream_id_hi = *(tmp++);
3250                         channel.transport_stream_id_lo = *(tmp++);
3251                         channel.channel_id_hi = *(tmp++);
3252                         channel.channel_id_lo = *(tmp++);
3253                         m_channels[i]=channel;
3254                         tmp+=2;
3255                 }
3256                 for (int i=0; i < num_channels; ++i)
3257                 {
3258                         mhw_channel_name_t &channel = m_channels[i];
3259                         int channel_name_len=*(tmp++)&0x0f;
3260                         int x=0;
3261                         for (; x < channel_name_len; ++x)
3262                                 channel.name[x]=*(tmp++);
3263                         channel.name[x+1]=0;
3264                 }
3265                 haveData |= MHW;
3266                 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3267         }
3268         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3269         {
3270                 // Themes table
3271                 eDebug("[EPGC] mhw2 themes nyi");
3272         }
3273         else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3274         // Titles table
3275         {
3276                 int pos=18;
3277                 bool valid=true;
3278                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3279                 bool finish=false;
3280                 if(data[dataLen-1] != 0xff)
3281                         return;
3282                 while( pos < dataLen )
3283                 {
3284                         valid = false;
3285                         pos += 7;
3286                         if( pos < dataLen )
3287                         {
3288                                 pos += 3;
3289                                 if( pos < dataLen )
3290                                 {
3291                                         if( data[pos] > 0xc0 )
3292                                         {
3293                                                 pos += ( data[pos] - 0xc0 );
3294                                                 pos += 4;
3295                                                 if( pos < dataLen )
3296                                                 {
3297                                                         if( data[pos] == 0xff )
3298                                                         {
3299                                                                 ++pos;
3300                                                                 valid = true;
3301                                                         }
3302                                                 }
3303                                         }
3304                                 }
3305                         }
3306                         if( !valid )
3307                         {
3308                                 if (checkTimeout())
3309                                         goto start_summary;
3310                                 return;
3311                         }
3312                 }
3313                 // data seems consistent...
3314                 mhw_title_t title;
3315                 pos = 18;
3316                 while (pos < len)
3317                 {
3318                         title.channel_id = data[pos]+1;
3319                         title.program_id_ml = data[pos+1];
3320                         title.program_id_lo = data[pos+2];
3321                         title.mhw2_mjd_hi = data[pos+3];
3322                         title.mhw2_mjd_lo = data[pos+4];
3323                         title.mhw2_hours = data[pos+5];
3324                         title.mhw2_minutes = data[pos+6];
3325                         title.mhw2_seconds = data[pos+7];
3326                         int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3327                         title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3328                         title.mhw2_duration_lo = duration&0xFF;
3329                         __u8 slen = data[pos+10] & 0x3f;
3330                         __u8 *dest = ((__u8*)title.title)-4;
3331                         memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3332                         memset(dest+slen, 0, 33-slen);
3333                         pos += 11 + slen;
3334 //                      not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3335                         __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3336
3337                         // Create unique key per title
3338                         __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3339
3340                         pos += 4;
3341
3342                         std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3343                         if ( it == m_titles.end() )
3344                         {
3345                                 startTimeout(5000);
3346                                 m_titles[ title_id ] = title;
3347                                 if (summary_id != 0xFFFF)
3348                                 {
3349                                         bool add=true;
3350                                         std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3351                                         while (it != m_program_ids.end() && it->first == summary_id)
3352                                         {
3353                                                 if (it->second == title_id) {
3354                                                         add=false;
3355                                                         break;
3356                                                 }
3357                                                 ++it;
3358                                         }
3359                                         if (add)
3360                                                 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3361                                 }
3362                         }
3363                         else
3364                         {
3365                                 if ( !checkTimeout() )
3366                                         continue;       // Continue reading of the current table.
3367                                 finish=true;
3368                                 break;
3369                         }
3370                 }
3371 start_summary:
3372                 if (finish)
3373                 {
3374                         eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3375                         if (!m_program_ids.empty())
3376                         {
3377                                 // Titles table has been read, there are summaries to read.
3378                                 // Start reading summaries, store corresponding titles on the fly.
3379                                 startMHWReader2(0x236, 0x96);
3380                                 startTimeout(15000);
3381                                 return;
3382                         }
3383                 }
3384                 else
3385                         return;
3386         }
3387         else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3388         // Summaries table
3389         {
3390                 if (!checkTimeout())
3391                 {
3392                         int len, loop, pos, lenline;
3393                         bool valid;
3394                         valid = true;
3395                         if( dataLen > 15 )
3396                         {
3397                                 loop = data[14];
3398                                 pos = 15 + loop;
3399                                 if( dataLen > pos )
3400                                 {
3401                                         loop = data[pos] & 0x0f;
3402                                         pos += 1;
3403                                         if( dataLen > pos )
3404                                         {
3405                                                 len = 0;
3406                                                 for( ; loop > 0; --loop )
3407                                                 {
3408                                                         if( dataLen > (pos+len) )
3409                                                         {
3410                                                                 lenline = data[pos+len];
3411                                                                 len += lenline + 1;
3412                                                         }
3413                                                         else
3414                                                                 valid=false;
3415                                                 }
3416                                         }
3417                                 }
3418                         }
3419                         else
3420                                 return;  // continue reading
3421                         if (valid)
3422                         {
3423                                 // data seems consistent...
3424                                 __u32 summary_id = (data[3]<<8)|data[4];
3425
3426                                 // ugly workaround to convert const __u8* to char*
3427                                 char *tmp=0;
3428                                 memcpy(&tmp, &data, sizeof(void*));
3429
3430                                 len = 0;
3431                                 loop = data[14];
3432                                 pos = 15 + loop;
3433                                 loop = tmp[pos] & 0x0f;
3434                                 pos += 1;
3435                                 for( ; loop > 0; loop -- )
3436                                 {
3437                                         lenline = tmp[pos+len];
3438                                         tmp[pos+len] = ' ';
3439                                         len += lenline + 1;
3440                                 }
3441                                 if( len > 0 )
3442                                     tmp[pos+len] = 0;
3443                                 else
3444                                         tmp[pos+1] = 0;
3445
3446                                 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3447                                 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3448                                 { /*    This part is to prevent to looping forever if some summaries are not received yet.
3449                                         There is a timeout of 4 sec. after the last successfully read summary. */
3450                                         if ( !m_program_ids.empty() )
3451                                                 return; // Continue reading of the current table.
3452                                 }
3453                                 else
3454                                 {
3455                                         startTimeout(15000);
3456                                         std::string the_text = (char *) (data + pos + 1);
3457
3458                                         while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3459                                         {
3460                                                 // Find corresponding title, store title and summary in epgcache.
3461                                                 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3462                                                 if ( itTitle != m_titles.end() )
3463                                                 {
3464                                                         storeTitle( itTitle, the_text, data );
3465                                                         m_titles.erase( itTitle );
3466                                                 }
3467                                                 m_program_ids.erase( itProgId++ );
3468                                         }
3469                                         if ( !m_program_ids.empty() )
3470                                                 return; // Continue reading of the current table.
3471                                 }
3472                         }
3473                         else
3474                                 return;  // continue reading
3475                 }
3476         }
3477         if (isRunning & eEPGCache::MHW)
3478         {
3479                 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3480                 {
3481                         // Channels table has been read, start reading the themes table.
3482                         startMHWReader2(0x231, 0xC8, 1);
3483                         return;
3484                 }
3485                 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3486                 {
3487                         // Themes table has been read, start reading the titles table.
3488                         startMHWReader2(0x234, 0xe6);
3489                         return;
3490                 }
3491                 else
3492                 {
3493                         // Summaries have been read, titles that have summaries have been stored.
3494                         // Now store titles that do not have summaries.
3495                         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3496                                 storeTitle( itTitle, "", data );
3497                         eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3498                                 ::time(0),
3499                                 m_program_ids.size());
3500                 }
3501         }
3502 abort:
3503         isRunning &= ~MHW;
3504         m_MHWConn2=0;
3505         if ( m_MHWReader2 )
3506                 m_MHWReader2->stop();
3507         if (haveData)
3508                 finishEPG();
3509 }
3510 #endif