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