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