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