Merge branch 'bug_537_vobsub' into experimental
[vuplus_dvbapp] / lib / dvb / epgcache.cpp
1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
3
4 #undef EPG_DEBUG  
5
6 #ifdef EPG_DEBUG
7 #include <lib/service/event.h>
8 #endif
9
10 #include <time.h>
11 #include <unistd.h>  // for usleep
12 #include <sys/vfs.h> // for statfs
13 // #include <libmd5sum.h>
14 #include <lib/base/eerror.h>
15 #include <lib/base/estring.h>
16 #include <lib/dvb/pmt.h>
17 #include <lib/dvb/db.h>
18 #include <lib/python/python.h>
19 #include <dvbsi++/descriptor_tag.h>
20
21 int eventData::CacheSize=0;
22 descriptorMap eventData::descriptors;
23 __u8 eventData::data[4108];
24 extern const uint32_t crc32_table[256];
25
26 const eServiceReference &handleGroup(const eServiceReference &ref)
27 {
28         if (ref.flags & eServiceReference::isGroup)
29         {
30                 ePtr<eDVBResourceManager> res;
31                 if (!eDVBResourceManager::getInstance(res))
32                 {
33                         ePtr<iDVBChannelList> db;
34                         if (!res->getChannelList(db))
35                         {
36                                 eBouquet *bouquet=0;
37                                 if (!db->getBouquet(ref, bouquet))
38                                 {
39                                         std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
40                                         if (it != bouquet->m_services.end())
41                                                 return *it;
42                                 }
43                         }
44                 }
45         }
46         return ref;
47 }
48
49 eventData::eventData(const eit_event_struct* e, int size, int type)
50         :ByteSize(size&0xFF), type(type&0xFF)
51 {
52         if (!e)
53                 return;
54
55         __u32 descr[65];
56         __u32 *pdescr=descr;
57
58         __u8 *data = (__u8*)e;
59         int ptr=12;
60         size -= 12;
61
62         while(size > 1)
63         {
64                 __u8 *descr = data+ptr;
65                 int descr_len = descr[1];
66                 descr_len += 2;
67                 if (size >= descr_len)
68                 {
69                         switch (descr[0])
70                         {
71                                 case EXTENDED_EVENT_DESCRIPTOR:
72                                 case SHORT_EVENT_DESCRIPTOR:
73                                 case LINKAGE_DESCRIPTOR:
74                                 case COMPONENT_DESCRIPTOR:
75                                 {
76                                         __u32 crc = 0;
77                                         int cnt=0;
78                                         while(cnt++ < descr_len)
79                                                 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
80         
81                                         descriptorMap::iterator it =
82                                                 descriptors.find(crc);
83                                         if ( it == descriptors.end() )
84                                         {
85                                                 CacheSize+=descr_len;
86                                                 __u8 *d = new __u8[descr_len];
87                                                 memcpy(d, descr, descr_len);
88                                                 descriptors[crc] = descriptorPair(1, d);
89                                         }
90                                         else
91                                                 ++it->second.first;
92                                         *pdescr++=crc;
93                                         break;
94                                 }
95                                 default: // do not cache all other descriptors
96                                         ptr += descr_len;
97                                         break;
98                         }
99                         size -= descr_len;
100                 }
101                 else
102                         break;
103         }
104         ASSERT(pdescr <= &descr[65]);
105         ByteSize = 10+((pdescr-descr)*4);
106         EITdata = new __u8[ByteSize];
107         CacheSize+=ByteSize;
108         memcpy(EITdata, (__u8*) e, 10);
109         memcpy(EITdata+10, descr, ByteSize-10);
110 }
111
112 const eit_event_struct* eventData::get() const
113 {
114         int pos = 12;
115         int tmp = ByteSize-10;
116         memcpy(data, EITdata, 10);
117         int descriptors_length=0;
118         __u32 *p = (__u32*)(EITdata+10);
119         while(tmp>3)
120         {
121                 descriptorMap::iterator it =
122                         descriptors.find(*p++);
123                 if ( it != descriptors.end() )
124                 {
125                         int b = it->second.second[1]+2;
126                         memcpy(data+pos, it->second.second, b );
127                         pos += b;
128                         descriptors_length += b;
129                 }
130                 else
131                         eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(p-1));
132                 tmp-=4;
133         }
134         ASSERT(pos <= 4108);
135         data[10] = (descriptors_length >> 8) & 0x0F;
136         data[11] = descriptors_length & 0xFF;
137         return (eit_event_struct*)data;
138 }
139
140 eventData::~eventData()
141 {
142         if ( ByteSize )
143         {
144                 CacheSize -= ByteSize;
145                 __u32 *d = (__u32*)(EITdata+10);
146                 ByteSize -= 10;
147                 while(ByteSize>3)
148                 {
149                         descriptorMap::iterator it =
150                                 descriptors.find(*d++);
151                         if ( it != descriptors.end() )
152                         {
153                                 descriptorPair &p = it->second;
154                                 if (!--p.first) // no more used descriptor
155                                 {
156                                         CacheSize -= it->second.second[1];
157                                         delete [] it->second.second;    // free descriptor memory
158                                         descriptors.erase(it);  // remove entry from descriptor map
159                                 }
160                         }
161                         else
162                                 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(d-1));
163                         ByteSize -= 4;
164                 }
165                 delete [] EITdata;
166         }
167 }
168
169 void eventData::load(FILE *f)
170 {
171         int size=0;
172         int id=0;
173         __u8 header[2];
174         descriptorPair p;
175         fread(&size, sizeof(int), 1, f);
176         while(size)
177         {
178                 fread(&id, sizeof(__u32), 1, f);
179                 fread(&p.first, sizeof(int), 1, f);
180                 fread(header, 2, 1, f);
181                 int bytes = header[1]+2;
182                 p.second = new __u8[bytes];
183                 p.second[0] = header[0];
184                 p.second[1] = header[1];
185                 fread(p.second+2, bytes-2, 1, f);
186                 descriptors[id]=p;
187                 --size;
188                 CacheSize+=bytes;
189         }
190 }
191
192 void eventData::save(FILE *f)
193 {
194         int size=descriptors.size();
195         descriptorMap::iterator it(descriptors.begin());
196         fwrite(&size, sizeof(int), 1, f);
197         while(size)
198         {
199                 fwrite(&it->first, sizeof(__u32), 1, f);
200                 fwrite(&it->second.first, sizeof(int), 1, f);
201                 fwrite(it->second.second, it->second.second[1]+2, 1, f);
202                 ++it;
203                 --size;
204         }
205 }
206
207 eEPGCache* eEPGCache::instance;
208 pthread_mutex_t eEPGCache::cache_lock=
209         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
210 pthread_mutex_t eEPGCache::channel_map_lock=
211         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
212
213 DEFINE_REF(eEPGCache)
214
215 eEPGCache::eEPGCache()
216         :messages(this,1), cleanTimer(eTimer::create(this)), m_running(0)//, paused(0)
217 {
218         eDebug("[EPGC] Initialized EPGCache (wait for setCacheFile call now)");
219
220         CONNECT(messages.recv_msg, eEPGCache::gotMessage);
221         CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
222         CONNECT(cleanTimer->timeout, eEPGCache::cleanLoop);
223
224         ePtr<eDVBResourceManager> res_mgr;
225         eDVBResourceManager::getInstance(res_mgr);
226         if (!res_mgr)
227                 eDebug("[eEPGCache] no resource manager !!!!!!!");
228         else
229                 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
230
231         instance=this;
232         memset(m_filename, 0, sizeof(m_filename));
233 }
234
235 void eEPGCache::setCacheFile(const char *path)
236 {
237         bool inited = !!strlen(m_filename);
238         strncpy(m_filename, path, 1024);
239         if (!inited)
240         {
241                 eDebug("[EPGC] setCacheFile read/write epg data from/to '%s'", m_filename);
242                 if (eDVBLocalTimeHandler::getInstance()->ready())
243                         timeUpdated();
244         }
245 }
246
247 void eEPGCache::timeUpdated()
248 {
249         if (strlen(m_filename))
250         {
251                 if (!sync())
252                 {
253                         eDebug("[EPGC] time updated.. start EPG Mainloop");
254                         run();
255                         singleLock s(channel_map_lock);
256                         channelMapIterator it = m_knownChannels.begin();
257                         for (; it != m_knownChannels.end(); ++it)
258                         {
259                                 if (it->second->state == -1) {
260                                         it->second->state=0;
261                                         messages.send(Message(Message::startChannel, it->second));
262                                 }
263                         }
264                 } else
265                         messages.send(Message(Message::timeChanged));
266         }
267         else
268                 eDebug("[EPGC] time updated.. but cache file not set yet.. dont start epg!!");
269 }
270
271 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
272 {
273         if ( chan )
274         {
275 //              eDebug("[eEPGCache] add channel %p", chan);
276                 channel_data *data = new channel_data(this);
277                 data->channel = chan;
278                 data->prevChannelState = -1;
279 #ifdef ENABLE_PRIVATE_EPG
280                 data->m_PrivatePid = -1;
281 #endif
282 #ifdef ENABLE_MHW_EPG
283                 data->m_mhw2_channel_pid = 0x231; // defaults for astra 19.2 D+
284                 data->m_mhw2_title_pid = 0x234; // defaults for astra 19.2 D+
285                 data->m_mhw2_summary_pid = 0x236; // defaults for astra 19.2 D+
286 #endif
287                 singleLock s(channel_map_lock);
288                 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
289                 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
290         }
291 }
292
293 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
294 {
295         channelMapIterator it =
296                 m_knownChannels.find(chan);
297         if ( it == m_knownChannels.end() )
298                 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
299         else
300         {
301                 channel_data &data = *it->second;
302                 ePtr<eDVBResourceManager> res_mgr;
303                 if ( eDVBResourceManager::getInstance( res_mgr ) )
304                         eDebug("[eEPGCache] no res manager!!");
305                 else
306                 {
307                         ePtr<iDVBDemux> demux;
308                         if ( data.channel->getDemux(demux, 0) )
309                         {
310                                 eDebug("[eEPGCache] no demux!!");
311                                 return;
312                         }
313                         else
314                         {
315                                 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
316                                 if ( res )
317                                 {
318                                         eDebug("[eEPGCache] couldnt initialize nownext reader!!");
319                                         return;
320                                 }
321
322                                 res = demux->createSectionReader( this, data.m_ScheduleReader );
323                                 if ( res )
324                                 {
325                                         eDebug("[eEPGCache] couldnt initialize schedule reader!!");
326                                         return;
327                                 }
328
329                                 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
330                                 if ( res )
331                                 {
332                                         eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
333                                         return;
334                                 }
335
336                                 res = demux->createSectionReader( this, data.m_ViasatReader );
337                                 if ( res )
338                                 {
339                                         eDebug("[eEPGCache] couldnt initialize viasat reader!!");
340                                         return;
341                                 }
342 #ifdef ENABLE_PRIVATE_EPG
343                                 res = demux->createSectionReader( this, data.m_PrivateReader );
344                                 if ( res )
345                                 {
346                                         eDebug("[eEPGCache] couldnt initialize private reader!!");
347                                         return;
348                                 }
349 #endif
350 #ifdef ENABLE_MHW_EPG
351                                 res = demux->createSectionReader( this, data.m_MHWReader );
352                                 if ( res )
353                                 {
354                                         eDebug("[eEPGCache] couldnt initialize mhw reader!!");
355                                         return;
356                                 }
357                                 res = demux->createSectionReader( this, data.m_MHWReader2 );
358                                 if ( res )
359                                 {
360                                         eDebug("[eEPGCache] couldnt initialize mhw reader!!");
361                                         return;
362                                 }
363 #endif
364                                 if (m_running) {
365                                         data.state=0;
366                                         messages.send(Message(Message::startChannel, chan));
367                                         // -> gotMessage -> changedService
368                                 }
369                         }
370                 }
371         }
372 }
373
374 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
375 {
376         channelMapIterator it =
377                 m_knownChannels.find(chan);
378         if ( it != m_knownChannels.end() )
379         {
380                 int state=0;
381                 chan->getState(state);
382                 if ( it->second->prevChannelState != state )
383                 {
384                         switch (state)
385                         {
386                                 case iDVBChannel::state_ok:
387                                 {
388                                         eDebug("[eEPGCache] channel %p running", chan);
389                                         DVBChannelRunning(chan);
390                                         break;
391                                 }
392                                 case iDVBChannel::state_release:
393                                 {
394                                         eDebug("[eEPGCache] remove channel %p", chan);
395                                         if (it->second->state >= 0)
396                                                 messages.send(Message(Message::leaveChannel, chan));
397                                         pthread_mutex_lock(&it->second->channel_active);
398                                         singleLock s(channel_map_lock);
399                                         m_knownChannels.erase(it);
400                                         pthread_mutex_unlock(&it->second->channel_active);
401                                         delete it->second;
402                                         it->second=0;
403                                         // -> gotMessage -> abortEPG
404                                         break;
405                                 }
406                                 default: // ignore all other events
407                                         return;
408                         }
409                         if (it->second)
410                                 it->second->prevChannelState = state;
411                 }
412         }
413 }
414
415 bool eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
416 {
417         bool ret = false;
418         timeMap::iterator tmp = tm_it;
419         while ((tmp->first+tmp->second->getDuration()-300) > TM)
420         {
421                 if(tmp->first != TM 
422 #ifdef ENABLE_PRIVATE_EPG
423                         && tmp->second->type != PRIVATE 
424 #endif
425 #ifdef ENABLE_MHW
426                         && tmp->second->type != MHW
427 #endif
428                         )
429                 {
430                         __u16 event_id = tmp->second->getEventID();
431                         servicemap.first.erase(event_id);
432 #ifdef EPG_DEBUG
433                         Event evt((uint8_t*)tmp->second->get());
434                         eServiceEvent event;
435                         event.parseFrom(&evt, service.sid<<16|service.onid);
436                         eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
437                                 service.sid, event_id,
438                                 event.getBeginTimeString().c_str(),
439                                 event.getEventName().c_str(),
440                                 event.getExtendedDescription().c_str());
441 #endif
442                         delete tmp->second;
443                         if (tmp == servicemap.second.begin())
444                         {
445                                 servicemap.second.erase(tmp);
446                                 break;
447                         }
448                         else
449                                 servicemap.second.erase(tmp--);
450                         ret = true;
451                 }
452                 else
453                 {
454                         if (tmp == servicemap.second.begin())
455                                 break;
456                         --tmp;
457                 }
458         }
459
460         tmp = tm_it;
461         while(tmp->first < (TM+duration-300))
462         {
463                 if (tmp->first != TM && tmp->second->type != PRIVATE)
464                 {
465                         __u16 event_id = tmp->second->getEventID();
466                         servicemap.first.erase(event_id);
467 #ifdef EPG_DEBUG  
468                         Event evt((uint8_t*)tmp->second->get());
469                         eServiceEvent event;
470                         event.parseFrom(&evt, service.sid<<16|service.onid);
471                         eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
472                                 service.sid, event_id,
473                                 event.getBeginTimeString().c_str(),
474                                 event.getEventName().c_str(),
475                                 event.getExtendedDescription().c_str());
476 #endif
477                         delete tmp->second;
478                         servicemap.second.erase(tmp++);
479                         ret = true;
480                 }
481                 else
482                         ++tmp;
483                 if (tmp == servicemap.second.end())
484                         break;
485         }
486         return ret;
487 }
488
489 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
490 {
491         eit_t *eit = (eit_t*) data;
492
493         int len=HILO(eit->section_length)-1;//+3-4;
494         int ptr=EIT_SIZE;
495         if ( ptr >= len )
496                 return;
497
498         // This fixed the EPG on the Multichoice irdeto systems
499         // the EIT packet is non-compliant.. their EIT packet stinks
500         if ( data[ptr-1] < 0x40 )
501                 --ptr;
502
503         // Cablecom HACK .. tsid / onid in eit data are incorrect.. so we use
504         // it from running channel (just for current transport stream eit data)
505         bool use_transponder_chid = source == SCHEDULE || (source == NOWNEXT && data[0] == 0x4E);
506         eDVBChannelID chid = channel->channel->getChannelID();
507         uniqueEPGKey service( HILO(eit->service_id),
508                 use_transponder_chid ? chid.original_network_id.get() : HILO(eit->original_network_id),
509                 use_transponder_chid ? chid.transport_stream_id.get() : HILO(eit->transport_stream_id));
510
511         eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
512         int eit_event_size;
513         int duration;
514
515         time_t TM = parseDVBtime(
516                         eit_event->start_time_1,
517                         eit_event->start_time_2,
518                         eit_event->start_time_3,
519                         eit_event->start_time_4,
520                         eit_event->start_time_5);
521         time_t now = ::time(0);
522
523         if ( TM != 3599 && TM > -1)
524                 channel->haveData |= source;
525
526         singleLock s(cache_lock);
527         // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
528         // oder eine durch [] erzeugte
529         std::pair<eventMap,timeMap> &servicemap = eventDB[service];
530         eventMap::iterator prevEventIt = servicemap.first.end();
531         timeMap::iterator prevTimeIt = servicemap.second.end();
532
533         while (ptr<len)
534         {
535                 __u16 event_hash;
536                 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
537
538                 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
539                 TM = parseDVBtime(
540                         eit_event->start_time_1,
541                         eit_event->start_time_2,
542                         eit_event->start_time_3,
543                         eit_event->start_time_4,
544                         eit_event->start_time_5,
545                         &event_hash);
546
547                 if ( TM == 3599 )
548                         goto next;
549
550                 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
551                         goto next;
552
553                 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ )  // old events should not be cached
554                 {
555                         __u16 event_id = HILO(eit_event->event_id);
556                         eventData *evt = 0;
557                         int ev_erase_count = 0;
558                         int tm_erase_count = 0;
559
560                         if (event_id == 0) {
561                                 // hack for some polsat services on 13.0E..... but this also replaces other valid event_ids with value 0..
562                                 // but we dont care about it...
563                                 event_id = event_hash;
564                                 eit_event->event_id_hi = event_hash >> 8;
565                                 eit_event->event_id_lo = event_hash & 0xFF;
566                         }
567
568                         // search in eventmap
569                         eventMap::iterator ev_it =
570                                 servicemap.first.find(event_id);
571
572 //                      eDebug("event_id is %d sid is %04x", event_id, service.sid);
573
574                         // entry with this event_id is already exist ?
575                         if ( ev_it != servicemap.first.end() )
576                         {
577                                 if ( source > ev_it->second->type )  // update needed ?
578                                         goto next; // when not.. then skip this entry
579
580                                 // search this event in timemap
581                                 timeMap::iterator tm_it_tmp =
582                                         servicemap.second.find(ev_it->second->getStartTime());
583
584                                 if ( tm_it_tmp != servicemap.second.end() )
585                                 {
586                                         if ( tm_it_tmp->first == TM ) // just update eventdata
587                                         {
588                                                 // exempt memory
589                                                 eventData *tmp = ev_it->second;
590                                                 ev_it->second = tm_it_tmp->second =
591                                                         new eventData(eit_event, eit_event_size, source);
592                                                 if (FixOverlapping(servicemap, TM, duration, tm_it_tmp, service))
593                                                 {
594                                                         prevEventIt = servicemap.first.end();
595                                                         prevTimeIt = servicemap.second.end();
596                                                 }
597                                                 delete tmp;
598                                                 goto next;
599                                         }
600                                         else  // event has new event begin time
601                                         {
602                                                 tm_erase_count++;
603                                                 // delete the found record from timemap
604                                                 servicemap.second.erase(tm_it_tmp);
605                                                 prevTimeIt=servicemap.second.end();
606                                         }
607                                 }
608                         }
609
610                         // search in timemap, for check of a case if new time has coincided with time of other event
611                         // or event was is not found in eventmap
612                         timeMap::iterator tm_it =
613                                 servicemap.second.find(TM);
614
615                         if ( tm_it != servicemap.second.end() )
616                         {
617                                 // event with same start time but another event_id...
618                                 if ( source > tm_it->second->type &&
619                                         ev_it == servicemap.first.end() )
620                                         goto next; // when not.. then skip this entry
621
622                                 // search this time in eventmap
623                                 eventMap::iterator ev_it_tmp =
624                                         servicemap.first.find(tm_it->second->getEventID());
625
626                                 if ( ev_it_tmp != servicemap.first.end() )
627                                 {
628                                         ev_erase_count++;
629                                         // delete the found record from eventmap
630                                         servicemap.first.erase(ev_it_tmp);
631                                         prevEventIt=servicemap.first.end();
632                                 }
633                         }
634                         evt = new eventData(eit_event, eit_event_size, source);
635 #ifdef EPG_DEBUG
636                         bool consistencyCheck=true;
637 #endif
638                         if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
639                         {
640                                 // exempt memory
641                                 delete ev_it->second;
642                                 delete tm_it->second;
643                                 ev_it->second=evt;
644                                 tm_it->second=evt;
645                         }
646                         else if (ev_erase_count == 0 && tm_erase_count > 0)
647                         {
648                                 // exempt memory
649                                 delete ev_it->second;
650                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
651                                 ev_it->second=evt;
652                         }
653                         else if (ev_erase_count > 0 && tm_erase_count == 0)
654                         {
655                                 // exempt memory
656                                 delete tm_it->second;
657                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
658                                 tm_it->second=evt;
659                         }
660                         else // added new eventData
661                         {
662 #ifdef EPG_DEBUG
663                                 consistencyCheck=false;
664 #endif
665                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
666                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
667                         }
668
669 #ifdef EPG_DEBUG
670                         if ( consistencyCheck )
671                         {
672                                 if ( tm_it->second != evt || ev_it->second != evt )
673                                         eFatal("tm_it->second != ev_it->second");
674                                 else if ( tm_it->second->getStartTime() != tm_it->first )
675                                         eFatal("event start_time(%d) non equal timemap key(%d)",
676                                                 tm_it->second->getStartTime(), tm_it->first );
677                                 else if ( tm_it->first != TM )
678                                         eFatal("timemap key(%d) non equal TM(%d)",
679                                                 tm_it->first, TM);
680                                 else if ( ev_it->second->getEventID() != ev_it->first )
681                                         eFatal("event_id (%d) non equal event_map key(%d)",
682                                                 ev_it->second->getEventID(), ev_it->first);
683                                 else if ( ev_it->first != event_id )
684                                         eFatal("eventmap key(%d) non equal event_id(%d)",
685                                                 ev_it->first, event_id );
686                         }
687 #endif
688                         if (FixOverlapping(servicemap, TM, duration, tm_it, service))
689                         {
690                                 prevEventIt = servicemap.first.end();
691                                 prevTimeIt = servicemap.second.end();
692                         }
693                 }
694 next:
695 #ifdef EPG_DEBUG
696                 if ( servicemap.first.size() != servicemap.second.size() )
697                 {
698                         FILE *f = fopen("/hdd/event_map.txt", "w+");
699                         int i=0;
700                         for (eventMap::iterator it(servicemap.first.begin())
701                                 ; it != servicemap.first.end(); ++it )
702                                 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
703                                         i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
704                         fclose(f);
705                         f = fopen("/hdd/time_map.txt", "w+");
706                         i=0;
707                         for (timeMap::iterator it(servicemap.second.begin())
708                                 ; it != servicemap.second.end(); ++it )
709                                         fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
710                                                 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
711                         fclose(f);
712
713                         eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d", 
714                                 service.sid, service.tsid, service.onid, 
715                                 servicemap.first.size(), servicemap.second.size() );
716                 }
717 #endif
718                 ptr += eit_event_size;
719                 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
720         }
721 }
722
723 void eEPGCache::flushEPG(const uniqueEPGKey & s)
724 {
725         eDebug("[EPGC] flushEPG %d", (int)(bool)s);
726         singleLock l(cache_lock);
727         if (s)  // clear only this service
728         {
729                 eventCache::iterator it = eventDB.find(s);
730                 if ( it != eventDB.end() )
731                 {
732                         eventMap &evMap = it->second.first;
733                         timeMap &tmMap = it->second.second;
734                         tmMap.clear();
735                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
736                                 delete i->second;
737                         evMap.clear();
738                         eventDB.erase(it);
739
740                         // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
741 #ifdef ENABLE_PRIVATE_EPG
742                         contentMaps::iterator it =
743                                 content_time_tables.find(s);
744                         if ( it != content_time_tables.end() )
745                         {
746                                 it->second.clear();
747                                 content_time_tables.erase(it);
748                         }
749 #endif
750                 }
751         }
752         else // clear complete EPG Cache
753         {
754                 for (eventCache::iterator it(eventDB.begin());
755                         it != eventDB.end(); ++it)
756                 {
757                         eventMap &evMap = it->second.first;
758                         timeMap &tmMap = it->second.second;
759                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
760                                 delete i->second;
761                         evMap.clear();
762                         tmMap.clear();
763                 }
764                 eventDB.clear();
765 #ifdef ENABLE_PRIVATE_EPG
766                 content_time_tables.clear();
767 #endif
768                 channelLastUpdated.clear();
769                 singleLock m(channel_map_lock);
770                 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
771                         it->second->startEPG();
772         }
773         eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
774 }
775
776 void eEPGCache::cleanLoop()
777 {
778         singleLock s(cache_lock);
779         if (!eventDB.empty())
780         {
781                 eDebug("[EPGC] start cleanloop");
782
783                 time_t now = ::time(0);
784
785                 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
786                 {
787                         bool updated = false;
788                         for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
789                         {
790                                 if ( now > (It->first+It->second->getDuration()) )  // outdated normal entry (nvod references to)
791                                 {
792                                         // remove entry from eventMap
793                                         eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
794                                         if ( b != DBIt->second.first.end() )
795                                         {
796                                                 // release Heap Memory for this entry   (new ....)
797 //                                              eDebug("[EPGC] delete old event (evmap)");
798                                                 DBIt->second.first.erase(b);
799                                         }
800
801                                         // remove entry from timeMap
802 //                                      eDebug("[EPGC] release heap mem");
803                                         delete It->second;
804                                         DBIt->second.second.erase(It++);
805 //                                      eDebug("[EPGC] delete old event (timeMap)");
806                                         updated = true;
807                                 }
808                                 else
809                                         ++It;
810                         }
811 #ifdef ENABLE_PRIVATE_EPG
812                         if ( updated )
813                         {
814                                 contentMaps::iterator x =
815                                         content_time_tables.find( DBIt->first );
816                                 if ( x != content_time_tables.end() )
817                                 {
818                                         timeMap &tmMap = DBIt->second.second;
819                                         for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
820                                         {
821                                                 for ( contentTimeMap::iterator it(i->second.begin());
822                                                         it != i->second.end(); )
823                                                 {
824                                                         if ( tmMap.find(it->second.first) == tmMap.end() )
825                                                                 i->second.erase(it++);
826                                                         else
827                                                                 ++it;
828                                                 }
829                                                 if ( i->second.size() )
830                                                         ++i;
831                                                 else
832                                                         x->second.erase(i++);
833                                         }
834                                 }
835                         }
836 #endif
837                 }
838                 eDebug("[EPGC] stop cleanloop");
839                 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
840         }
841         cleanTimer->start(CLEAN_INTERVAL,true);
842 }
843
844 eEPGCache::~eEPGCache()
845 {
846         messages.send(Message::quit);
847         kill(); // waiting for thread shutdown
848         singleLock s(cache_lock);
849         for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
850                 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
851                         delete It->second;
852 }
853
854 void eEPGCache::gotMessage( const Message &msg )
855 {
856         switch (msg.type)
857         {
858                 case Message::flush:
859                         flushEPG(msg.service);
860                         break;
861                 case Message::startChannel:
862                 {
863                         singleLock s(channel_map_lock);
864                         channelMapIterator channel =
865                                 m_knownChannels.find(msg.channel);
866                         if ( channel != m_knownChannels.end() )
867                                 channel->second->startChannel();
868                         break;
869                 }
870                 case Message::leaveChannel:
871                 {
872                         singleLock s(channel_map_lock);
873                         channelMapIterator channel =
874                                 m_knownChannels.find(msg.channel);
875                         if ( channel != m_knownChannels.end() )
876                                 channel->second->abortEPG();
877                         break;
878                 }
879                 case Message::quit:
880                         quit(0);
881                         break;
882 #ifdef ENABLE_PRIVATE_EPG
883                 case Message::got_private_pid:
884                 {
885                         singleLock s(channel_map_lock);
886                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
887                         {
888                                 eDVBChannel *channel = (eDVBChannel*) it->first;
889                                 channel_data *data = it->second;
890                                 eDVBChannelID chid = channel->getChannelID();
891                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
892                                         chid.original_network_id.get() == msg.service.onid &&
893                                         data->m_PrivatePid == -1 )
894                                 {
895                                         data->m_PrevVersion = -1;
896                                         data->m_PrivatePid = msg.pid;
897                                         data->m_PrivateService = msg.service;
898                                         int onid = chid.original_network_id.get();
899                                         onid |= 0x80000000;  // we use highest bit as private epg indicator
900                                         chid.original_network_id = onid;
901                                         updateMap::iterator It = channelLastUpdated.find( chid );
902                                         int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
903                                         if (update < ZAP_DELAY)
904                                                 update = ZAP_DELAY;
905                                         data->startPrivateTimer->start(update, 1);
906                                         if (update >= 60000)
907                                                 eDebug("[EPGC] next private update in %i min", update/60000);
908                                         else if (update >= 1000)
909                                                 eDebug("[EPGC] next private update in %i sec", update/1000);
910                                         break;
911                                 }
912                         }
913                         break;
914                 }
915 #endif
916 #ifdef ENABLE_MHW_EPG
917                 case Message::got_mhw2_channel_pid:
918                 {
919                         singleLock s(channel_map_lock);
920                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
921                         {
922                                 eDVBChannel *channel = (eDVBChannel*) it->first;
923                                 channel_data *data = it->second;
924                                 eDVBChannelID chid = channel->getChannelID();
925                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
926                                         chid.original_network_id.get() == msg.service.onid )
927                                 {
928                                         data->m_mhw2_channel_pid = msg.pid;
929                                         eDebug("[EPGC] got mhw2 channel pid %04x", msg.pid);
930                                         break;
931                                 }
932                         }
933                         break;
934                 }
935                 case Message::got_mhw2_title_pid:
936                 {
937                         singleLock s(channel_map_lock);
938                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
939                         {
940                                 eDVBChannel *channel = (eDVBChannel*) it->first;
941                                 channel_data *data = it->second;
942                                 eDVBChannelID chid = channel->getChannelID();
943                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
944                                         chid.original_network_id.get() == msg.service.onid )
945                                 {
946                                         data->m_mhw2_title_pid = msg.pid;
947                                         eDebug("[EPGC] got mhw2 title pid %04x", msg.pid);
948                                         break;
949                                 }
950                         }
951                         break;
952                 }
953                 case Message::got_mhw2_summary_pid:
954                 {
955                         singleLock s(channel_map_lock);
956                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
957                         {
958                                 eDVBChannel *channel = (eDVBChannel*) it->first;
959                                 channel_data *data = it->second;
960                                 eDVBChannelID chid = channel->getChannelID();
961                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
962                                         chid.original_network_id.get() == msg.service.onid )
963                                 {
964                                         data->m_mhw2_summary_pid = msg.pid;
965                                         eDebug("[EPGC] got mhw2 summary pid %04x", msg.pid);
966                                         break;
967                                 }
968                         }
969                         break;
970                 }
971 #endif
972                 case Message::timeChanged:
973                         cleanLoop();
974                         break;
975                 default:
976                         eDebug("unhandled EPGCache Message!!");
977                         break;
978         }
979 }
980
981 void eEPGCache::thread()
982 {
983         hasStarted();
984         m_running=1;
985         nice(4);
986         load();
987         cleanLoop();
988         runLoop();
989         save();
990         m_running=0;
991 }
992
993 void eEPGCache::load()
994 {
995         FILE *f = fopen(m_filename, "r");
996         if (f)
997         {
998                 unlink(m_filename);
999                 int size=0;
1000                 int cnt=0;
1001
1002                 {
1003                         unsigned int magic=0;
1004                         fread( &magic, sizeof(int), 1, f);
1005                         if (magic != 0x98765432)
1006                         {
1007                                 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
1008                                 fclose(f);
1009                                 return;
1010                         }
1011                         char text1[13];
1012                         fread( text1, 13, 1, f);
1013                         if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
1014                         {
1015                                 singleLock s(cache_lock);
1016                                 fread( &size, sizeof(int), 1, f);
1017                                 while(size--)
1018                                 {
1019                                         uniqueEPGKey key;
1020                                         eventMap evMap;
1021                                         timeMap tmMap;
1022                                         int size=0;
1023                                         fread( &key, sizeof(uniqueEPGKey), 1, f);
1024                                         fread( &size, sizeof(int), 1, f);
1025                                         while(size--)
1026                                         {
1027                                                 __u8 len=0;
1028                                                 __u8 type=0;
1029                                                 eventData *event=0;
1030                                                 fread( &type, sizeof(__u8), 1, f);
1031                                                 fread( &len, sizeof(__u8), 1, f);
1032                                                 event = new eventData(0, len, type);
1033                                                 event->EITdata = new __u8[len];
1034                                                 eventData::CacheSize+=len;
1035                                                 fread( event->EITdata, len, 1, f);
1036                                                 evMap[ event->getEventID() ]=event;
1037                                                 tmMap[ event->getStartTime() ]=event;
1038                                                 ++cnt;
1039                                         }
1040                                         eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
1041                                 }
1042                                 eventData::load(f);
1043                                 eDebug("[EPGC] %d events read from %s", cnt, m_filename);
1044 #ifdef ENABLE_PRIVATE_EPG
1045                                 char text2[11];
1046                                 fread( text2, 11, 1, f);
1047                                 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
1048                                 {
1049                                         size=0;
1050                                         fread( &size, sizeof(int), 1, f);
1051                                         while(size--)
1052                                         {
1053                                                 int size=0;
1054                                                 uniqueEPGKey key;
1055                                                 fread( &key, sizeof(uniqueEPGKey), 1, f);
1056                                                 eventMap &evMap=eventDB[key].first;
1057                                                 fread( &size, sizeof(int), 1, f);
1058                                                 while(size--)
1059                                                 {
1060                                                         int size;
1061                                                         int content_id;
1062                                                         fread( &content_id, sizeof(int), 1, f);
1063                                                         fread( &size, sizeof(int), 1, f);
1064                                                         while(size--)
1065                                                         {
1066                                                                 time_t time1, time2;
1067                                                                 __u16 event_id;
1068                                                                 fread( &time1, sizeof(time_t), 1, f);
1069                                                                 fread( &time2, sizeof(time_t), 1, f);
1070                                                                 fread( &event_id, sizeof(__u16), 1, f);
1071                                                                 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
1072                                                                 eventMap::iterator it =
1073                                                                         evMap.find(event_id);
1074                                                                 if (it != evMap.end())
1075                                                                         it->second->type = PRIVATE;
1076                                                         }
1077                                                 }
1078                                         }
1079                                 }
1080 #endif // ENABLE_PRIVATE_EPG
1081                         }
1082                         else
1083                                 eDebug("[EPGC] don't read old epg database");
1084                         fclose(f);
1085                 }
1086         }
1087 }
1088
1089 void eEPGCache::save()
1090 {
1091         /* create empty file */
1092         FILE *f = fopen(m_filename, "w");
1093
1094         if (!f)
1095         {
1096                 eDebug("[EPGC] couldn't save epg data to '%s'(%m)", m_filename);
1097                 return;
1098         }
1099
1100         char *buf = realpath(m_filename, NULL);
1101         if (!buf)
1102         {
1103                 eDebug("[EPGC] realpath to '%s' failed in save (%m)", m_filename);
1104                 fclose(f);
1105                 return;
1106         }
1107
1108         eDebug("[EPGC] store epg to realpath '%s'", buf);
1109
1110         struct statfs s;
1111         off64_t tmp;
1112         if (statfs(buf, &s) < 0) {
1113                 eDebug("[EPGC] statfs '%s' failed in save (%m)", buf);
1114                 fclose(f);
1115                 return;
1116         }
1117
1118         free(buf);
1119
1120         // check for enough free space on storage
1121         tmp=s.f_bfree;
1122         tmp*=s.f_bsize;
1123         if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
1124         {
1125                 eDebug("[EPGC] not enough free space at path '%s' %lld bytes availd but %d needed", buf, tmp, (eventData::CacheSize*12)/10);
1126                 fclose(f);
1127                 return;
1128         }
1129
1130         int cnt=0;
1131         unsigned int magic = 0x98765432;
1132         fwrite( &magic, sizeof(int), 1, f);
1133         const char *text = "UNFINISHED_V7";
1134         fwrite( text, 13, 1, f );
1135         int size = eventDB.size();
1136         fwrite( &size, sizeof(int), 1, f );
1137         for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1138         {
1139                 timeMap &timemap = service_it->second.second;
1140                 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1141                 size = timemap.size();
1142                 fwrite( &size, sizeof(int), 1, f);
1143                 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1144                 {
1145                         __u8 len = time_it->second->ByteSize;
1146                         fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1147                         fwrite( &len, sizeof(__u8), 1, f);
1148                         fwrite( time_it->second->EITdata, len, 1, f);
1149                         ++cnt;
1150                 }
1151         }
1152         eDebug("[EPGC] %d events written to %s", cnt, m_filename);
1153         eventData::save(f);
1154 #ifdef ENABLE_PRIVATE_EPG
1155         const char* text3 = "PRIVATE_EPG";
1156         fwrite( text3, 11, 1, f );
1157         size = content_time_tables.size();
1158         fwrite( &size, sizeof(int), 1, f);
1159         for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1160         {
1161                 contentMap &content_time_table = a->second;
1162                 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1163                 int size = content_time_table.size();
1164                 fwrite( &size, sizeof(int), 1, f);
1165                 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1166                 {
1167                         int size = i->second.size();
1168                         fwrite( &i->first, sizeof(int), 1, f);
1169                         fwrite( &size, sizeof(int), 1, f);
1170                         for ( contentTimeMap::iterator it(i->second.begin());
1171                                 it != i->second.end(); ++it )
1172                         {
1173                                 fwrite( &it->first, sizeof(time_t), 1, f);
1174                                 fwrite( &it->second.first, sizeof(time_t), 1, f);
1175                                 fwrite( &it->second.second, sizeof(__u16), 1, f);
1176                         }
1177                 }
1178         }
1179 #endif
1180         // write version string after binary data
1181         // has been written to disk.
1182         fsync(fileno(f));
1183         fseek(f, sizeof(int), SEEK_SET);
1184         fwrite("ENIGMA_EPG_V7", 13, 1, f);
1185         fclose(f);
1186 }
1187
1188 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1189         :cache(ml)
1190         ,abortTimer(eTimer::create(ml)), zapTimer(eTimer::create(ml)), state(-1)
1191         ,isRunning(0), haveData(0)
1192 #ifdef ENABLE_PRIVATE_EPG
1193         ,startPrivateTimer(eTimer::create(ml))
1194 #endif
1195 #ifdef ENABLE_MHW_EPG
1196         ,m_MHWTimeoutTimer(eTimer::create(ml))
1197 #endif
1198 {
1199 #ifdef ENABLE_MHW_EPG
1200         CONNECT(m_MHWTimeoutTimer->timeout, eEPGCache::channel_data::MHWTimeout);
1201 #endif
1202         CONNECT(zapTimer->timeout, eEPGCache::channel_data::startEPG);
1203         CONNECT(abortTimer->timeout, eEPGCache::channel_data::abortNonAvail);
1204 #ifdef ENABLE_PRIVATE_EPG
1205         CONNECT(startPrivateTimer->timeout, eEPGCache::channel_data::startPrivateReader);
1206 #endif
1207         pthread_mutex_init(&channel_active, 0);
1208 }
1209
1210 bool eEPGCache::channel_data::finishEPG()
1211 {
1212         if (!isRunning)  // epg ready
1213         {
1214                 eDebug("[EPGC] stop caching events(%ld)", ::time(0));
1215                 zapTimer->start(UPDATE_INTERVAL, 1);
1216                 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1217                 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1218                 {
1219                         seenSections[i].clear();
1220                         calcedSections[i].clear();
1221                 }
1222                 singleLock l(cache->cache_lock);
1223                 cache->channelLastUpdated[channel->getChannelID()] = ::time(0);
1224 #ifdef ENABLE_MHW_EPG
1225                 cleanup();
1226 #endif
1227                 return true;
1228         }
1229         return false;
1230 }
1231
1232 void eEPGCache::channel_data::startEPG()
1233 {
1234         eDebug("[EPGC] start caching events(%ld)", ::time(0));
1235         state=0;
1236         haveData=0;
1237         for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1238         {
1239                 seenSections[i].clear();
1240                 calcedSections[i].clear();
1241         }
1242
1243         eDVBSectionFilterMask mask;
1244         memset(&mask, 0, sizeof(mask));
1245
1246 #ifdef ENABLE_MHW_EPG
1247         mask.pid = 0xD3;
1248         mask.data[0] = 0x91;
1249         mask.mask[0] = 0xFF;
1250         m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1251         m_MHWReader->start(mask);
1252         isRunning |= MHW;
1253         memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1254
1255         mask.pid = m_mhw2_channel_pid;
1256         mask.data[0] = 0xC8;
1257         mask.mask[0] = 0xFF;
1258         mask.data[1] = 0;
1259         mask.mask[1] = 0xFF;
1260         m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1261         m_MHWReader2->start(mask);
1262         isRunning |= MHW;
1263         memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1264         mask.data[1] = 0;
1265         mask.mask[1] = 0;
1266         m_MHWTimeoutet=false;
1267 #endif
1268
1269         mask.pid = 0x12;
1270         mask.flags = eDVBSectionFilterMask::rfCRC;
1271
1272         mask.data[0] = 0x4E;
1273         mask.mask[0] = 0xFE;
1274         m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1275         m_NowNextReader->start(mask);
1276         isRunning |= NOWNEXT;
1277
1278         mask.data[0] = 0x50;
1279         mask.mask[0] = 0xF0;
1280         m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1281         m_ScheduleReader->start(mask);
1282         isRunning |= SCHEDULE;
1283
1284         mask.data[0] = 0x60;
1285         m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1286         m_ScheduleOtherReader->start(mask);
1287         isRunning |= SCHEDULE_OTHER;
1288
1289         mask.pid = 0x39;
1290
1291         mask.data[0] = 0x40;
1292         mask.mask[0] = 0x40;
1293         m_ViasatReader->connectRead(slot(*this, &eEPGCache::channel_data::readDataViasat), m_ViasatConn);
1294         m_ViasatReader->start(mask);
1295         isRunning |= VIASAT;
1296
1297         abortTimer->start(7000,true);
1298 }
1299
1300 void eEPGCache::channel_data::abortNonAvail()
1301 {
1302         if (!state)
1303         {
1304                 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1305                 {
1306                         eDebug("[EPGC] abort non avail nownext reading");
1307                         isRunning &= ~NOWNEXT;
1308                         m_NowNextReader->stop();
1309                         m_NowNextConn=0;
1310                 }
1311                 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1312                 {
1313                         eDebug("[EPGC] abort non avail schedule reading");
1314                         isRunning &= ~SCHEDULE;
1315                         m_ScheduleReader->stop();
1316                         m_ScheduleConn=0;
1317                 }
1318                 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1319                 {
1320                         eDebug("[EPGC] abort non avail schedule other reading");
1321                         isRunning &= ~SCHEDULE_OTHER;
1322                         m_ScheduleOtherReader->stop();
1323                         m_ScheduleOtherConn=0;
1324                 }
1325                 if ( !(haveData&VIASAT) && (isRunning&VIASAT) )
1326                 {
1327                         eDebug("[EPGC] abort non avail viasat reading");
1328                         isRunning &= ~VIASAT;
1329                         m_ViasatReader->stop();
1330                         m_ViasatConn=0;
1331                 }
1332 #ifdef ENABLE_MHW_EPG
1333                 if ( !(haveData&MHW) && (isRunning&MHW) )
1334                 {
1335                         eDebug("[EPGC] abort non avail mhw reading");
1336                         isRunning &= ~MHW;
1337                         m_MHWReader->stop();
1338                         m_MHWConn=0;
1339                         m_MHWReader2->stop();
1340                         m_MHWConn2=0;
1341                 }
1342 #endif
1343                 if ( isRunning & VIASAT )
1344                         abortTimer->start(300000, true);
1345                 else if ( isRunning )
1346                         abortTimer->start(90000, true);
1347                 else
1348                 {
1349                         ++state;
1350                         for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1351                         {
1352                                 seenSections[i].clear();
1353                                 calcedSections[i].clear();
1354                         }
1355                 }
1356         }
1357         ++state;
1358 }
1359
1360 void eEPGCache::channel_data::startChannel()
1361 {
1362         pthread_mutex_lock(&channel_active);
1363         updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1364
1365         int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
1366
1367         if (update < ZAP_DELAY)
1368                 update = ZAP_DELAY;
1369
1370         zapTimer->start(update, 1);
1371         if (update >= 60000)
1372                 eDebug("[EPGC] next update in %i min", update/60000);
1373         else if (update >= 1000)
1374                 eDebug("[EPGC] next update in %i sec", update/1000);
1375 }
1376
1377 void eEPGCache::channel_data::abortEPG()
1378 {
1379         for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1380         {
1381                 seenSections[i].clear();
1382                 calcedSections[i].clear();
1383         }
1384         abortTimer->stop();
1385         zapTimer->stop();
1386         if (isRunning)
1387         {
1388                 eDebug("[EPGC] abort caching events !!");
1389                 if (isRunning & SCHEDULE)
1390                 {
1391                         isRunning &= ~SCHEDULE;
1392                         m_ScheduleReader->stop();
1393                         m_ScheduleConn=0;
1394                 }
1395                 if (isRunning & NOWNEXT)
1396                 {
1397                         isRunning &= ~NOWNEXT;
1398                         m_NowNextReader->stop();
1399                         m_NowNextConn=0;
1400                 }
1401                 if (isRunning & SCHEDULE_OTHER)
1402                 {
1403                         isRunning &= ~SCHEDULE_OTHER;
1404                         m_ScheduleOtherReader->stop();
1405                         m_ScheduleOtherConn=0;
1406                 }
1407                 if (isRunning & VIASAT)
1408                 {
1409                         isRunning &= ~VIASAT;
1410                         m_ViasatReader->stop();
1411                         m_ViasatConn=0;
1412                 }
1413 #ifdef ENABLE_MHW_EPG
1414                 if (isRunning & MHW)
1415                 {
1416                         isRunning &= ~MHW;
1417                         m_MHWReader->stop();
1418                         m_MHWConn=0;
1419                         m_MHWReader2->stop();
1420                         m_MHWConn2=0;
1421                 }
1422 #endif
1423         }
1424 #ifdef ENABLE_PRIVATE_EPG
1425         if (m_PrivateReader)
1426                 m_PrivateReader->stop();
1427         if (m_PrivateConn)
1428                 m_PrivateConn=0;
1429 #endif
1430         pthread_mutex_unlock(&channel_active);
1431 }
1432
1433
1434 void eEPGCache::channel_data::readDataViasat( const __u8 *data)
1435 {
1436         __u8 *d=0;
1437         memcpy(&d, &data, sizeof(__u8*));
1438         d[0] |= 0x80;
1439         readData(data);
1440 }
1441
1442 void eEPGCache::channel_data::readData( const __u8 *data)
1443 {
1444         int source;
1445         int map;
1446         iDVBSectionReader *reader=NULL;
1447         switch(data[0])
1448         {
1449                 case 0x4E ... 0x4F:
1450                         reader=m_NowNextReader;
1451                         source=NOWNEXT;
1452                         map=0;
1453                         break;
1454                 case 0x50 ... 0x5F:
1455                         reader=m_ScheduleReader;
1456                         source=SCHEDULE;
1457                         map=1;
1458                         break;
1459                 case 0x60 ... 0x6F:
1460                         reader=m_ScheduleOtherReader;
1461                         source=SCHEDULE_OTHER;
1462                         map=2;
1463                         break;
1464                 case 0xD0 ... 0xDF:
1465                 case 0xE0 ... 0xEF:
1466                         reader=m_ViasatReader;
1467                         source=VIASAT;
1468                         map=3;
1469                         break;
1470                 default:
1471                         eDebug("[EPGC] unknown table_id !!!");
1472                         return;
1473         }
1474         tidMap &seenSections = this->seenSections[map];
1475         tidMap &calcedSections = this->calcedSections[map];
1476         if ( (state == 1 && calcedSections == seenSections) || state > 1 )
1477         {
1478                 eDebugNoNewLine("[EPGC] ");
1479                 switch (source)
1480                 {
1481                         case NOWNEXT:
1482                                 m_NowNextConn=0;
1483                                 eDebugNoNewLine("nownext");
1484                                 break;
1485                         case SCHEDULE:
1486                                 m_ScheduleConn=0;
1487                                 eDebugNoNewLine("schedule");
1488                                 break;
1489                         case SCHEDULE_OTHER:
1490                                 m_ScheduleOtherConn=0;
1491                                 eDebugNoNewLine("schedule other");
1492                                 break;
1493                         case VIASAT:
1494                                 m_ViasatConn=0;
1495                                 eDebugNoNewLine("viasat");
1496                                 break;
1497                         default: eDebugNoNewLine("unknown");break;
1498                 }
1499                 eDebug(" finished(%ld)", ::time(0));
1500                 if ( reader )
1501                         reader->stop();
1502                 isRunning &= ~source;
1503                 if (!isRunning)
1504                         finishEPG();
1505         }
1506         else
1507         {
1508                 eit_t *eit = (eit_t*) data;
1509                 __u32 sectionNo = data[0] << 24;
1510                 sectionNo |= data[3] << 16;
1511                 sectionNo |= data[4] << 8;
1512                 sectionNo |= eit->section_number;
1513
1514                 tidMap::iterator it =
1515                         seenSections.find(sectionNo);
1516
1517                 if ( it == seenSections.end() )
1518                 {
1519                         seenSections.insert(sectionNo);
1520                         calcedSections.insert(sectionNo);
1521                         __u32 tmpval = sectionNo & 0xFFFFFF00;
1522                         __u8 incr = source == NOWNEXT ? 1 : 8;
1523                         for ( int i = 0; i <= eit->last_section_number; i+=incr )
1524                         {
1525                                 if ( i == eit->section_number )
1526                                 {
1527                                         for (int x=i; x <= eit->segment_last_section_number; ++x)
1528                                                 calcedSections.insert(tmpval|(x&0xFF));
1529                                 }
1530                                 else
1531                                         calcedSections.insert(tmpval|(i&0xFF));
1532                         }
1533                         cache->sectionRead(data, source, this);
1534                 }
1535         }
1536 }
1537
1538 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1539 // if t == -1 we search the current event...
1540 {
1541         singleLock s(cache_lock);
1542         uniqueEPGKey key(handleGroup(service));
1543
1544         // check if EPG for this service is ready...
1545         eventCache::iterator It = eventDB.find( key );
1546         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1547         {
1548                 if (t==-1)
1549                         t = ::time(0);
1550                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1551                         It->second.second.upper_bound(t); // just >
1552                 if ( i != It->second.second.end() )
1553                 {
1554                         if ( direction < 0 || (direction == 0 && i->first > t) )
1555                         {
1556                                 timeMap::iterator x = i;
1557                                 --x;
1558                                 if ( x != It->second.second.end() )
1559                                 {
1560                                         time_t start_time = x->first;
1561                                         if (direction >= 0)
1562                                         {
1563                                                 if (t < start_time)
1564                                                         return -1;
1565                                                 if (t > (start_time+x->second->getDuration()))
1566                                                         return -1;
1567                                         }
1568                                         i = x;
1569                                 }
1570                                 else
1571                                         return -1;
1572                         }
1573                         result = i->second;
1574                         return 0;
1575                 }
1576         }
1577         return -1;
1578 }
1579
1580 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1581 {
1582         singleLock s(cache_lock);
1583         const eventData *data=0;
1584         RESULT ret = lookupEventTime(service, t, data, direction);
1585         if ( !ret && data )
1586                 result = data->get();
1587         return ret;
1588 }
1589
1590 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1591 {
1592         singleLock s(cache_lock);
1593         const eventData *data=0;
1594         RESULT ret = lookupEventTime(service, t, data, direction);
1595         if ( !ret && data )
1596                 result = new Event((uint8_t*)data->get());
1597         return ret;
1598 }
1599
1600 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1601 {
1602         singleLock s(cache_lock);
1603         const eventData *data=0;
1604         RESULT ret = lookupEventTime(service, t, data, direction);
1605         if ( !ret && data )
1606         {
1607                 Event ev((uint8_t*)data->get());
1608                 result = new eServiceEvent();
1609                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1610                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1611         }
1612         return ret;
1613 }
1614
1615 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1616 {
1617         singleLock s(cache_lock);
1618         uniqueEPGKey key(handleGroup(service));
1619
1620         eventCache::iterator It = eventDB.find( key );
1621         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1622         {
1623                 eventMap::iterator i( It->second.first.find( event_id ));
1624                 if ( i != It->second.first.end() )
1625                 {
1626                         result = i->second;
1627                         return 0;
1628                 }
1629                 else
1630                 {
1631                         result = 0;
1632                         eDebug("[EPGC] event %04x not found in epgcache", event_id);
1633                 }
1634         }
1635         return -1;
1636 }
1637
1638 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1639 {
1640         singleLock s(cache_lock);
1641         const eventData *data=0;
1642         RESULT ret = lookupEventId(service, event_id, data);
1643         if ( !ret && data )
1644                 result = data->get();
1645         return ret;
1646 }
1647
1648 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1649 {
1650         singleLock s(cache_lock);
1651         const eventData *data=0;
1652         RESULT ret = lookupEventId(service, event_id, data);
1653         if ( !ret && data )
1654                 result = new Event((uint8_t*)data->get());
1655         return ret;
1656 }
1657
1658 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1659 {
1660         singleLock s(cache_lock);
1661         const eventData *data=0;
1662         RESULT ret = lookupEventId(service, event_id, data);
1663         if ( !ret && data )
1664         {
1665                 Event ev((uint8_t*)data->get());
1666                 result = new eServiceEvent();
1667                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1668                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1669         }
1670         return ret;
1671 }
1672
1673 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1674 {
1675         singleLock s(cache_lock);
1676         const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1677         if (begin == -1)
1678                 begin = ::time(0);
1679         eventCache::iterator It = eventDB.find(ref);
1680         if ( It != eventDB.end() && It->second.second.size() )
1681         {
1682                 m_timemap_cursor = It->second.second.lower_bound(begin);
1683                 if ( m_timemap_cursor != It->second.second.end() )
1684                 {
1685                         if ( m_timemap_cursor->first != begin )
1686                         {
1687                                 timeMap::iterator x = m_timemap_cursor;
1688                                 --x;
1689                                 if ( x != It->second.second.end() )
1690                                 {
1691                                         time_t start_time = x->first;
1692                                         if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1693                                                 m_timemap_cursor = x;
1694                                 }
1695                         }
1696                 }
1697
1698                 if (minutes != -1)
1699                         m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1700                 else
1701                         m_timemap_end = It->second.second.end();
1702
1703                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1704                 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1705         }
1706         return -1;
1707 }
1708
1709 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1710 {
1711         if ( m_timemap_cursor != m_timemap_end )
1712         {
1713                 result = m_timemap_cursor++->second;
1714                 return 0;
1715         }
1716         return -1;
1717 }
1718
1719 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1720 {
1721         if ( m_timemap_cursor != m_timemap_end )
1722         {
1723                 result = m_timemap_cursor++->second->get();
1724                 return 0;
1725         }
1726         return -1;
1727 }
1728
1729 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1730 {
1731         if ( m_timemap_cursor != m_timemap_end )
1732         {
1733                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1734                 return 0;
1735         }
1736         return -1;
1737 }
1738
1739 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1740 {
1741         if ( m_timemap_cursor != m_timemap_end )
1742         {
1743                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1744                 result = new eServiceEvent();
1745                 return result->parseFrom(&ev, currentQueryTsidOnid);
1746         }
1747         return -1;
1748 }
1749
1750 void fillTuple(ePyObject tuple, const char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1751 {
1752         ePyObject tmp;
1753         int spos=0, tpos=0;
1754         char c;
1755         while(spos < argcount)
1756         {
1757                 bool inc_refcount=false;
1758                 switch((c=argstring[spos++]))
1759                 {
1760                         case '0': // PyLong 0
1761                                 tmp = PyLong_FromLong(0);
1762                                 break;
1763                         case 'I': // Event Id
1764                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1765                                 break;
1766                         case 'B': // Event Begin Time
1767                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1768                                 break;
1769                         case 'D': // Event Duration
1770                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1771                                 break;
1772                         case 'T': // Event Title
1773                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1774                                 break;
1775                         case 'S': // Event Short Description
1776                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1777                                 break;
1778                         case 'E': // Event Extended Description
1779                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1780                                 break;
1781                         case 'C': // Current Time
1782                                 tmp = nowTime;
1783                                 inc_refcount = true;
1784                                 break;
1785                         case 'R': // service reference string
1786                                 tmp = service;
1787                                 inc_refcount = true;
1788                                 break;
1789                         case 'n': // short service name
1790                         case 'N': // service name
1791                                 tmp = service_name;
1792                                 inc_refcount = true;
1793                                 break;
1794                         case 'X':
1795                                 ++argcount;
1796                                 continue;
1797                         default:  // ignore unknown
1798                                 tmp = ePyObject();
1799                                 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1800                 }
1801                 if (!tmp)
1802                 {
1803                         tmp = Py_None;
1804                         inc_refcount = true;
1805                 }
1806                 if (inc_refcount)
1807                         Py_INCREF(tmp);
1808                 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1809         }
1810 }
1811
1812 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1813 {
1814         if (convertFunc)
1815         {
1816                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1817                 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1818                 if (!result)
1819                 {
1820                         if (service_name)
1821                                 Py_DECREF(service_name);
1822                         if (nowTime)
1823                                 Py_DECREF(nowTime);
1824                         Py_DECREF(convertFuncArgs);
1825                         Py_DECREF(dest_list);
1826                         PyErr_SetString(PyExc_StandardError,
1827                                 "error in convertFunc execute");
1828                         eDebug("error in convertFunc execute");
1829                         return -1;
1830                 }
1831                 PyList_Append(dest_list, result);
1832                 Py_DECREF(result);
1833         }
1834         else
1835         {
1836                 ePyObject tuple = PyTuple_New(argcount);
1837                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1838                 PyList_Append(dest_list, tuple);
1839                 Py_DECREF(tuple);
1840         }
1841         return 0;
1842 }
1843
1844 // here we get a python list
1845 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1846 //   0 = PyLong(0)
1847 //   I = Event Id
1848 //   B = Event Begin Time
1849 //   D = Event Duration
1850 //   T = Event Title
1851 //   S = Event Short Description
1852 //   E = Event Extended Description
1853 //   C = Current Time
1854 //   R = Service Reference
1855 //   N = Service Name
1856 //   n = Short Service Name
1857 //   X = Return a minimum of one tuple per service in the result list... even when no event was found.
1858 //       The returned tuple is filled with all available infos... non avail is filled as None
1859 //       The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1860 // then for each service follows a tuple
1861 //   first tuple entry is the servicereference (as string... use the ref.toString() function)
1862 //   the second is the type of query
1863 //     2 = event_id
1864 //    -1 = event before given start_time
1865 //     0 = event intersects given start_time
1866 //    +1 = event after given start_time
1867 //   the third
1868 //      when type is eventid it is the event_id
1869 //      when type is time then it is the start_time ( -1 for now_time )
1870 //   the fourth is the end_time .. ( optional .. for query all events in time range)
1871
1872 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1873 {
1874         ePyObject convertFuncArgs;
1875         int argcount=0;
1876         const char *argstring=NULL;
1877         if (!PyList_Check(list))
1878         {
1879                 PyErr_SetString(PyExc_StandardError,
1880                         "type error");
1881                 eDebug("no list");
1882                 return NULL;
1883         }
1884         int listIt=0;
1885         int listSize=PyList_Size(list);
1886         if (!listSize)
1887         {
1888                 PyErr_SetString(PyExc_StandardError,
1889                         "not params given");
1890                 eDebug("not params given");
1891                 return NULL;
1892         }
1893         else 
1894         {
1895                 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1896                 if (PyString_Check(argv))
1897                 {
1898                         argstring = PyString_AS_STRING(argv);
1899                         ++listIt;
1900                 }
1901                 else
1902                         argstring = "I"; // just event id as default
1903                 argcount = strlen(argstring);
1904 //              eDebug("have %d args('%s')", argcount, argstring);
1905         }
1906
1907         bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1908         if (forceReturnOne)
1909                 --argcount;
1910
1911         if (convertFunc)
1912         {
1913                 if (!PyCallable_Check(convertFunc))
1914                 {
1915                         PyErr_SetString(PyExc_StandardError,
1916                                 "convertFunc must be callable");
1917                         eDebug("convertFunc is not callable");
1918                         return NULL;
1919                 }
1920                 convertFuncArgs = PyTuple_New(argcount);
1921         }
1922
1923         ePyObject nowTime = strchr(argstring, 'C') ?
1924                 PyLong_FromLong(::time(0)) :
1925                 ePyObject();
1926
1927         int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1928
1929         // create dest list
1930         ePyObject dest_list=PyList_New(0);
1931         while(listSize > listIt)
1932         {
1933                 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1934                 if (PyTuple_Check(item))
1935                 {
1936                         bool service_changed=false;
1937                         int type=0;
1938                         long event_id=-1;
1939                         time_t stime=-1;
1940                         int minutes=0;
1941                         int tupleSize=PyTuple_Size(item);
1942                         int tupleIt=0;
1943                         ePyObject service;
1944                         while(tupleSize > tupleIt)  // parse query args
1945                         {
1946                                 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1947                                 switch(tupleIt++)
1948                                 {
1949                                         case 0:
1950                                         {
1951                                                 if (!PyString_Check(entry))
1952                                                 {
1953                                                         eDebug("tuple entry 0 is no a string");
1954                                                         goto skip_entry;
1955                                                 }
1956                                                 service = entry;
1957                                                 break;
1958                                         }
1959                                         case 1:
1960                                                 type=PyInt_AsLong(entry);
1961                                                 if (type < -1 || type > 2)
1962                                                 {
1963                                                         eDebug("unknown type %d", type);
1964                                                         goto skip_entry;
1965                                                 }
1966                                                 break;
1967                                         case 2:
1968                                                 event_id=stime=PyInt_AsLong(entry);
1969                                                 break;
1970                                         case 3:
1971                                                 minutes=PyInt_AsLong(entry);
1972                                                 break;
1973                                         default:
1974                                                 eDebug("unneeded extra argument");
1975                                                 break;
1976                                 }
1977                         }
1978
1979                         if (minutes && stime == -1)
1980                                 stime = ::time(0);
1981
1982                         eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1983                         if (ref.type != eServiceReference::idDVB)
1984                         {
1985                                 eDebug("service reference for epg query is not valid");
1986                                 continue;
1987                         }
1988
1989                         // redirect subservice querys to parent service
1990                         eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1991                         if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1992                         {
1993                                 eServiceCenterPtr service_center;
1994                                 if (!eServiceCenter::getPrivInstance(service_center))
1995                                 {
1996                                         dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1997                                         dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1998                                         dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1999                                         dvb_ref.setParentServiceID(eServiceID(0));
2000                                         dvb_ref.name="";
2001                                         service = PyString_FromString(dvb_ref.toString().c_str());
2002                                         service_changed = true;
2003                                 }
2004                         }
2005
2006                         ePyObject service_name;
2007                         if (must_get_service_name)
2008                         {
2009                                 ePtr<iStaticServiceInformation> sptr;
2010                                 eServiceCenterPtr service_center;
2011                                 eServiceCenter::getPrivInstance(service_center);
2012                                 if (service_center)
2013                                 {
2014                                         service_center->info(ref, sptr);
2015                                         if (sptr)
2016                                         {
2017                                                 std::string name;
2018                                                 sptr->getName(ref, name);
2019
2020                                                 if (must_get_service_name == 1)
2021                                                 {
2022                                                         size_t pos;
2023                                                         // filter short name brakets
2024                                                         while((pos = name.find("\xc2\x86")) != std::string::npos)
2025                                                                 name.erase(pos,2);
2026                                                         while((pos = name.find("\xc2\x87")) != std::string::npos)
2027                                                                 name.erase(pos,2);
2028                                                 }
2029                                                 else
2030                                                         name = buildShortName(name);
2031
2032                                                 if (name.length())
2033                                                         service_name = PyString_FromString(name.c_str());
2034                                         }
2035                                 }
2036                                 if (!service_name)
2037                                         service_name = PyString_FromString("<n/a>");
2038                         }
2039                         if (minutes)
2040                         {
2041                                 singleLock s(cache_lock);
2042                                 if (!startTimeQuery(ref, stime, minutes))
2043                                 {
2044                                         while ( m_timemap_cursor != m_timemap_end )
2045                                         {
2046                                                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
2047                                                 eServiceEvent evt;
2048                                                 evt.parseFrom(&ev, currentQueryTsidOnid);
2049                                                 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2050                                                         return 0;  // error
2051                                         }
2052                                 }
2053                                 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2054                                         return 0;  // error
2055                         }
2056                         else
2057                         {
2058                                 eServiceEvent evt;
2059                                 const eventData *ev_data=0;
2060                                 if (stime)
2061                                 {
2062                                         singleLock s(cache_lock);
2063                                         if (type == 2)
2064                                                 lookupEventId(ref, event_id, ev_data);
2065                                         else
2066                                                 lookupEventTime(ref, stime, ev_data, type);
2067                                         if (ev_data)
2068                                         {
2069                                                 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2070                                                 Event ev((uint8_t*)ev_data->get());
2071                                                 evt.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2072                                         }
2073                                 }
2074                                 if (ev_data)
2075                                 {
2076                                         if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2077                                                 return 0; // error
2078                                 }
2079                                 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2080                                         return 0; // error
2081                         }
2082                         if (service_changed)
2083                                 Py_DECREF(service);
2084                         if (service_name)
2085                                 Py_DECREF(service_name);
2086                 }
2087 skip_entry:
2088                 ;
2089         }
2090         if (convertFuncArgs)
2091                 Py_DECREF(convertFuncArgs);
2092         if (nowTime)
2093                 Py_DECREF(nowTime);
2094         return dest_list;
2095 }
2096
2097 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2098 {
2099         ePyObject tmp;
2100         int pos=0;
2101         while(pos < argcount)
2102         {
2103                 bool inc_refcount=false;
2104                 switch(argstring[pos])
2105                 {
2106                         case '0': // PyLong 0
2107                                 tmp = PyLong_FromLong(0);
2108                                 break;
2109                         case 'I': // Event Id
2110                                 tmp = PyLong_FromLong(evData->getEventID());
2111                                 break;
2112                         case 'B': // Event Begin Time
2113                                 if (ptr)
2114                                         tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2115                                 else
2116                                         tmp = PyLong_FromLong(evData->getStartTime());
2117                                 break;
2118                         case 'D': // Event Duration
2119                                 if (ptr)
2120                                         tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2121                                 else
2122                                         tmp = PyLong_FromLong(evData->getDuration());
2123                                 break;
2124                         case 'T': // Event Title
2125                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2126                                 break;
2127                         case 'S': // Event Short Description
2128                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2129                                 break;
2130                         case 'E': // Event Extended Description
2131                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2132                                 break;
2133                         case 'R': // service reference string
2134                                 tmp = service_reference;
2135                                 inc_refcount = true;
2136                                 break;
2137                         case 'n': // short service name
2138                         case 'N': // service name
2139                                 tmp = service_name;
2140                                 inc_refcount = true;
2141                                 break;
2142                         default:  // ignore unknown
2143                                 tmp = ePyObject();
2144                                 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2145                 }
2146                 if (!tmp)
2147                 {
2148                         tmp = Py_None;
2149                         inc_refcount = true;
2150                 }
2151                 if (inc_refcount)
2152                         Py_INCREF(tmp);
2153                 PyTuple_SET_ITEM(tuple, pos++, tmp);
2154         }
2155 }
2156
2157 // here we get a python tuple
2158 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2159 //   I = Event Id
2160 //   B = Event Begin Time
2161 //   D = Event Duration
2162 //   T = Event Title
2163 //   S = Event Short Description
2164 //   E = Event Extended Description
2165 //   R = Service Reference
2166 //   N = Service Name
2167 //   n = Short Service Name
2168 //  the second tuple entry is the MAX matches value
2169 //  the third tuple entry is the type of query
2170 //     0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2171 //     1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2172 //     2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2173 //  when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2174 //   the fourth is the servicereference string
2175 //   the fifth is the eventid
2176 //  when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2177 //   the fourth is the search text
2178 //   the fifth is
2179 //     0 = case sensitive (CASE_CHECK)
2180 //     1 = case insensitive (NO_CASECHECK)
2181
2182 PyObject *eEPGCache::search(ePyObject arg)
2183 {
2184         ePyObject ret;
2185         int descridx = -1;
2186         __u32 descr[512];
2187         int eventid = -1;
2188         const char *argstring=0;
2189         char *refstr=0;
2190         int argcount=0;
2191         int querytype=-1;
2192         bool needServiceEvent=false;
2193         int maxmatches=0;
2194         int must_get_service_name = 0;
2195         bool must_get_service_reference = false;
2196
2197         if (PyTuple_Check(arg))
2198         {
2199                 int tuplesize=PyTuple_Size(arg);
2200                 if (tuplesize > 0)
2201                 {
2202                         ePyObject obj = PyTuple_GET_ITEM(arg,0);
2203                         if (PyString_Check(obj))
2204                         {
2205 #if PY_VERSION_HEX < 0x02060000
2206                                 argcount = PyString_GET_SIZE(obj);
2207 #else
2208                                 argcount = PyString_Size(obj);
2209 #endif
2210                                 argstring = PyString_AS_STRING(obj);
2211                                 for (int i=0; i < argcount; ++i)
2212                                         switch(argstring[i])
2213                                         {
2214                                         case 'S':
2215                                         case 'E':
2216                                         case 'T':
2217                                                 needServiceEvent=true;
2218                                                 break;
2219                                         case 'N':
2220                                                 must_get_service_name = 1;
2221                                                 break;
2222                                         case 'n':
2223                                                 must_get_service_name = 2;
2224                                                 break;
2225                                         case 'R':
2226                                                 must_get_service_reference = true;
2227                                                 break;
2228                                         default:
2229                                                 break;
2230                                         }
2231                         }
2232                         else
2233                         {
2234                                 PyErr_SetString(PyExc_StandardError,
2235                                         "type error");
2236                                 eDebug("tuple arg 0 is not a string");
2237                                 return NULL;
2238                         }
2239                 }
2240                 if (tuplesize > 1)
2241                         maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2242                 if (tuplesize > 2)
2243                 {
2244                         querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2245                         if (tuplesize > 4 && querytype == 0)
2246                         {
2247                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2248                                 if (PyString_Check(obj))
2249                                 {
2250                                         refstr = PyString_AS_STRING(obj);
2251                                         eServiceReferenceDVB ref(refstr);
2252                                         if (ref.valid())
2253                                         {
2254                                                 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2255                                                 singleLock s(cache_lock);
2256                                                 const eventData *evData = 0;
2257                                                 lookupEventId(ref, eventid, evData);
2258                                                 if (evData)
2259                                                 {
2260                                                         __u8 *data = evData->EITdata;
2261                                                         int tmp = evData->ByteSize-10;
2262                                                         __u32 *p = (__u32*)(data+10);
2263                                                                 // search short and extended event descriptors
2264                                                         while(tmp>3)
2265                                                         {
2266                                                                 __u32 crc = *p++;
2267                                                                 descriptorMap::iterator it =
2268                                                                         eventData::descriptors.find(crc);
2269                                                                 if (it != eventData::descriptors.end())
2270                                                                 {
2271                                                                         __u8 *descr_data = it->second.second;
2272                                                                         switch(descr_data[0])
2273                                                                         {
2274                                                                         case 0x4D ... 0x4E:
2275                                                                                 descr[++descridx]=crc;
2276                                                                         default:
2277                                                                                 break;
2278                                                                         }
2279                                                                 }
2280                                                                 tmp-=4;
2281                                                         }
2282                                                 }
2283                                                 if (descridx<0)
2284                                                         eDebug("event not found");
2285                                         }
2286                                         else
2287                                         {
2288                                                 PyErr_SetString(PyExc_StandardError, "type error");
2289                                                 eDebug("tuple arg 4 is not a valid service reference string");
2290                                                 return NULL;
2291                                         }
2292                                 }
2293                                 else
2294                                 {
2295                                         PyErr_SetString(PyExc_StandardError, "type error");
2296                                         eDebug("tuple arg 4 is not a string");
2297                                         return NULL;
2298                                 }
2299                         }
2300                         else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2301                         {
2302                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2303                                 if (PyString_Check(obj))
2304                                 {
2305                                         int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2306                                         const char *str = PyString_AS_STRING(obj);
2307 #if PY_VERSION_HEX < 0x02060000
2308                                         int textlen = PyString_GET_SIZE(obj);
2309 #else
2310                                         int textlen = PyString_Size(obj);
2311 #endif
2312                                         if (querytype == 1)
2313                                                 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2314                                         else
2315                                                 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2316                                         singleLock s(cache_lock);
2317                                         for (descriptorMap::iterator it(eventData::descriptors.begin());
2318                                                 it != eventData::descriptors.end() && descridx < 511; ++it)
2319                                         {
2320                                                 __u8 *data = it->second.second;
2321                                                 if ( data[0] == 0x4D ) // short event descriptor
2322                                                 {
2323                                                         int title_len = data[5];
2324                                                         if ( querytype == 1 )
2325                                                         {
2326                                                                 int offs = 6;
2327                                                                 // skip DVB-Text Encoding!
2328                                                                 if (data[6] == 0x10)
2329                                                                 {
2330                                                                         offs+=3;
2331                                                                         title_len-=3;
2332                                                                 }
2333                                                                 else if(data[6] > 0 && data[6] < 0x20)
2334                                                                 {
2335                                                                         offs+=1;
2336                                                                         title_len-=1;
2337                                                                 }
2338                                                                 if (title_len != textlen)
2339                                                                         continue;
2340                                                                 if ( casetype )
2341                                                                 {
2342                                                                         if ( !strncasecmp((const char*)data+offs, str, title_len) )
2343                                                                         {
2344 //                                                                              std::string s((const char*)data+offs, title_len);
2345 //                                                                              eDebug("match1 %s %s", str, s.c_str() );
2346                                                                                 descr[++descridx] = it->first;
2347                                                                         }
2348                                                                 }
2349                                                                 else if ( !strncmp((const char*)data+offs, str, title_len) )
2350                                                                 {
2351 //                                                                      std::string s((const char*)data+offs, title_len);
2352 //                                                                      eDebug("match2 %s %s", str, s.c_str() );
2353                                                                         descr[++descridx] = it->first;
2354                                                                 }
2355                                                         }
2356                                                         else
2357                                                         {
2358                                                                 int idx=0;
2359                                                                 while((title_len-idx) >= textlen)
2360                                                                 {
2361                                                                         if (casetype)
2362                                                                         {
2363                                                                                 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2364                                                                                 {
2365                                                                                         descr[++descridx] = it->first;
2366 //                                                                                      std::string s((const char*)data+6, title_len);
2367 //                                                                                      eDebug("match 3 %s %s", str, s.c_str() );
2368                                                                                         break;
2369                                                                                 }
2370                                                                         }
2371                                                                         else if (!strncmp((const char*)data+6+idx, str, textlen) )
2372                                                                         {
2373                                                                                 descr[++descridx] = it->first;
2374 //                                                                              std::string s((const char*)data+6, title_len);
2375 //                                                                              eDebug("match 4 %s %s", str, s.c_str() );
2376                                                                                 break;
2377                                                                         }
2378                                                                         ++idx;
2379                                                                 }
2380                                                         }
2381                                                 }
2382                                         }
2383                                 }
2384                                 else
2385                                 {
2386                                         PyErr_SetString(PyExc_StandardError,
2387                                                 "type error");
2388                                         eDebug("tuple arg 4 is not a string");
2389                                         return NULL;
2390                                 }
2391                         }
2392                         else
2393                         {
2394                                 PyErr_SetString(PyExc_StandardError,
2395                                         "type error");
2396                                 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2397                                 return NULL;
2398                         }
2399                 }
2400                 else
2401                 {
2402                         PyErr_SetString(PyExc_StandardError,
2403                                 "type error");
2404                         eDebug("not enough args in tuple");
2405                         return NULL;
2406                 }
2407         }
2408         else
2409         {
2410                 PyErr_SetString(PyExc_StandardError,
2411                         "type error");
2412                 eDebug("arg 0 is not a tuple");
2413                 return NULL;
2414         }
2415
2416         if (descridx > -1)
2417         {
2418                 int maxcount=maxmatches;
2419                 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2420                 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2421                 // in this case we start searching with the base service
2422                 bool first = ref.valid() ? true : false;
2423                 singleLock s(cache_lock);
2424                 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2425                 while(cit != eventDB.end() && maxcount)
2426                 {
2427                         if ( ref.valid() && !first && cit->first == ref )
2428                         {
2429                                 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2430                                 ++cit;
2431                                 continue;
2432                         }
2433                         ePyObject service_name;
2434                         ePyObject service_reference;
2435                         timeMap &evmap = cit->second.second;
2436                         // check all events
2437                         for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2438                         {
2439                                 int evid = evit->second->getEventID();
2440                                 if ( evid == eventid)
2441                                         continue;
2442                                 __u8 *data = evit->second->EITdata;
2443                                 int tmp = evit->second->ByteSize-10;
2444                                 __u32 *p = (__u32*)(data+10);
2445                                 // check if any of our descriptor used by this event
2446                                 int cnt=-1;
2447                                 while(tmp>3)
2448                                 {
2449                                         __u32 crc32 = *p++;
2450                                         for ( int i=0; i <= descridx; ++i)
2451                                         {
2452                                                 if (descr[i] == crc32)  // found...
2453                                                         ++cnt;
2454                                         }
2455                                         tmp-=4;
2456                                 }
2457                                 if ( (querytype == 0 && cnt == descridx) ||
2458                                          ((querytype == 1 || querytype == 2) && cnt != -1) )
2459                                 {
2460                                         const uniqueEPGKey &service = cit->first;
2461                                         eServiceReference ref =
2462                                                 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2463                                         if (ref.valid())
2464                                         {
2465                                         // create servive event
2466                                                 eServiceEvent ptr;
2467                                                 const eventData *ev_data=0;
2468                                                 if (needServiceEvent)
2469                                                 {
2470                                                         if (lookupEventId(ref, evid, ev_data))
2471                                                                 eDebug("event not found !!!!!!!!!!!");
2472                                                         else
2473                                                         {
2474                                                                 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2475                                                                 Event ev((uint8_t*)ev_data->get());
2476                                                                 ptr.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2477                                                         }
2478                                                 }
2479                                         // create service name
2480                                                 if (must_get_service_name && !service_name)
2481                                                 {
2482                                                         ePtr<iStaticServiceInformation> sptr;
2483                                                         eServiceCenterPtr service_center;
2484                                                         eServiceCenter::getPrivInstance(service_center);
2485                                                         if (service_center)
2486                                                         {
2487                                                                 service_center->info(ref, sptr);
2488                                                                 if (sptr)
2489                                                                 {
2490                                                                         std::string name;
2491                                                                         sptr->getName(ref, name);
2492
2493                                                                         if (must_get_service_name == 1)
2494                                                                         {
2495                                                                                 size_t pos;
2496                                                                                 // filter short name brakets
2497                                                                                 while((pos = name.find("\xc2\x86")) != std::string::npos)
2498                                                                                         name.erase(pos,2);
2499                                                                                 while((pos = name.find("\xc2\x87")) != std::string::npos)
2500                                                                                         name.erase(pos,2);
2501                                                                         }
2502                                                                         else
2503                                                                                 name = buildShortName(name);
2504
2505                                                                         if (name.length())
2506                                                                                 service_name = PyString_FromString(name.c_str());
2507                                                                 }
2508                                                         }
2509                                                         if (!service_name)
2510                                                                 service_name = PyString_FromString("<n/a>");
2511                                                 }
2512                                         // create servicereference string
2513                                                 if (must_get_service_reference && !service_reference)
2514                                                         service_reference = PyString_FromString(ref.toString().c_str());
2515                                         // create list
2516                                                 if (!ret)
2517                                                         ret = PyList_New(0);
2518                                         // create tuple
2519                                                 ePyObject tuple = PyTuple_New(argcount);
2520                                         // fill tuple
2521                                                 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2522                                                 PyList_Append(ret, tuple);
2523                                                 Py_DECREF(tuple);
2524                                                 --maxcount;
2525                                         }
2526                                 }
2527                         }
2528                         if (service_name)
2529                                 Py_DECREF(service_name);
2530                         if (service_reference)
2531                                 Py_DECREF(service_reference);
2532                         if (first)
2533                         {
2534                                 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2535                                 first=false;
2536                                 cit=eventDB.begin();
2537                         }
2538                         else
2539                                 ++cit;
2540                 }
2541         }
2542
2543         if (!ret)
2544                 Py_RETURN_NONE;
2545
2546         return ret;
2547 }
2548
2549 #ifdef ENABLE_PRIVATE_EPG
2550 #include <dvbsi++/descriptor_tag.h>
2551 #include <dvbsi++/unknown_descriptor.h>
2552 #include <dvbsi++/private_data_specifier_descriptor.h>
2553
2554 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2555 {
2556         ePtr<eTable<ProgramMapSection> > ptr;
2557         if (!pmthandler->getPMT(ptr) && ptr)
2558         {
2559                 std::vector<ProgramMapSection*>::const_iterator i;
2560                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2561                 {
2562                         const ProgramMapSection &pmt = **i;
2563
2564                         ElementaryStreamInfoConstIterator es;
2565                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2566                         {
2567                                 int tmp=0;
2568                                 switch ((*es)->getType())
2569                                 {
2570                                 case 0xC1: // user private
2571                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2572                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2573                                         {
2574                                                 switch ((*desc)->getTag())
2575                                                 {
2576                                                         case 0xC2: // user defined
2577                                                                 if ((*desc)->getLength() == 8) 
2578                                                                 {
2579                                                                         __u8 buffer[10];
2580                                                                         (*desc)->writeToBuffer(buffer);
2581                                                                         if (!strncmp((const char *)buffer+2, "EPGDATA", 7))
2582                                                                         {
2583                                                                                 eServiceReferenceDVB ref;
2584                                                                                 if (!pmthandler->getServiceReference(ref))
2585                                                                                 {
2586                                                                                         int pid = (*es)->getPid();
2587                                                                                         messages.send(Message(Message::got_mhw2_channel_pid, ref, pid));
2588                                                                                 }
2589                                                                         }
2590                                                                         else if(!strncmp((const char *)buffer+2, "FICHAS", 6))
2591                                                                         {
2592                                                                                 eServiceReferenceDVB ref;
2593                                                                                 if (!pmthandler->getServiceReference(ref))
2594                                                                                 {
2595                                                                                         int pid = (*es)->getPid();
2596                                                                                         messages.send(Message(Message::got_mhw2_summary_pid, ref, pid));
2597                                                                                 }
2598                                                                         }
2599                                                                         else if(!strncmp((const char *)buffer+2, "GENEROS", 7))
2600                                                                         {
2601                                                                                 eServiceReferenceDVB ref;
2602                                                                                 if (!pmthandler->getServiceReference(ref))
2603                                                                                 {
2604                                                                                         int pid = (*es)->getPid();
2605                                                                                         messages.send(Message(Message::got_mhw2_title_pid, ref, pid));
2606                                                                                 }
2607                                                                         }
2608                                                                 }
2609                                                                 break;
2610                                                         default:
2611                                                                 break;
2612                                                 }
2613                                         }
2614                                 case 0x05: // private
2615                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2616                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2617                                         {
2618                                                 switch ((*desc)->getTag())
2619                                                 {
2620                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2621                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2622                                                                         tmp |= 1;
2623                                                                 break;
2624                                                         case 0x90:
2625                                                         {
2626                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2627                                                                 int descr_len = descr->getLength();
2628                                                                 if (descr_len == 4)
2629                                                                 {
2630                                                                         uint8_t data[descr_len+2];
2631                                                                         descr->writeToBuffer(data);
2632                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2633                                                                                 tmp |= 2;
2634                                                                 }
2635                                                                 break;
2636                                                         }
2637                                                         default:
2638                                                                 break;
2639                                                 }
2640                                         }
2641                                 default:
2642                                         break;
2643                                 }
2644                                 if (tmp==3)
2645                                 {
2646                                         eServiceReferenceDVB ref;
2647                                         if (!pmthandler->getServiceReference(ref))
2648                                         {
2649                                                 int pid = (*es)->getPid();
2650                                                 messages.send(Message(Message::got_private_pid, ref, pid));
2651                                                 return;
2652                                         }
2653                                 }
2654                         }
2655                 }
2656         }
2657         else
2658                 eDebug("PMTready but no pmt!!");
2659 }
2660
2661 struct date_time
2662 {
2663         __u8 data[5];
2664         time_t tm;