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