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