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