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