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