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