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