1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
7 #include <lib/service/event.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>
21 int eventData::CacheSize=0;
22 descriptorMap eventData::descriptors;
23 __u8 eventData::data[4108];
24 extern const uint32_t crc32_table[256];
26 const eServiceReference &handleGroup(const eServiceReference &ref)
28 if (ref.flags & eServiceReference::isGroup)
30 ePtr<eDVBResourceManager> res;
31 if (!eDVBResourceManager::getInstance(res))
33 ePtr<iDVBChannelList> db;
34 if (!res->getChannelList(db))
37 if (!db->getBouquet(ref, bouquet))
39 std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
40 if (it != bouquet->m_services.end())
49 eventData::eventData(const eit_event_struct* e, int size, int type)
50 :ByteSize(size&0xFF), type(type&0xFF)
58 __u8 *data = (__u8*)e;
64 __u8 *descr = data+ptr;
65 int descr_len = descr[1];
67 if (size >= descr_len)
71 case EXTENDED_EVENT_DESCRIPTOR:
72 case SHORT_EVENT_DESCRIPTOR:
73 case LINKAGE_DESCRIPTOR:
74 case COMPONENT_DESCRIPTOR:
78 while(cnt++ < descr_len)
79 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
81 descriptorMap::iterator it =
82 descriptors.find(crc);
83 if ( it == descriptors.end() )
86 __u8 *d = new __u8[descr_len];
87 memcpy(d, descr, descr_len);
88 descriptors[crc] = descriptorPair(1, d);
95 default: // do not cache all other descriptors
104 ASSERT(pdescr <= &descr[65]);
105 ByteSize = 10+((pdescr-descr)*4);
106 EITdata = new __u8[ByteSize];
108 memcpy(EITdata, (__u8*) e, 10);
109 memcpy(EITdata+10, descr, ByteSize-10);
112 const eit_event_struct* eventData::get() const
115 int tmp = ByteSize-10;
116 memcpy(data, EITdata, 10);
117 int descriptors_length=0;
118 __u32 *p = (__u32*)(EITdata+10);
121 descriptorMap::iterator it =
122 descriptors.find(*p++);
123 if ( it != descriptors.end() )
125 int b = it->second.second[1]+2;
126 memcpy(data+pos, it->second.second, b );
128 descriptors_length += b;
131 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(p-1));
135 data[10] = (descriptors_length >> 8) & 0x0F;
136 data[11] = descriptors_length & 0xFF;
137 return (eit_event_struct*)data;
140 eventData::~eventData()
144 CacheSize -= ByteSize;
145 __u32 *d = (__u32*)(EITdata+10);
149 descriptorMap::iterator it =
150 descriptors.find(*d++);
151 if ( it != descriptors.end() )
153 descriptorPair &p = it->second;
154 if (!--p.first) // no more used descriptor
156 CacheSize -= it->second.second[1];
157 delete [] it->second.second; // free descriptor memory
158 descriptors.erase(it); // remove entry from descriptor map
162 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(d-1));
169 void eventData::load(FILE *f)
175 fread(&size, sizeof(int), 1, f);
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);
192 void eventData::save(FILE *f)
194 int size=descriptors.size();
195 descriptorMap::iterator it(descriptors.begin());
196 fwrite(&size, sizeof(int), 1, f);
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);
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;
213 DEFINE_REF(eEPGCache)
215 eEPGCache::eEPGCache()
216 :messages(this,1), cleanTimer(eTimer::create(this))//, paused(0)
218 eDebug("[EPGC] Initialized EPGCache");
220 CONNECT(messages.recv_msg, eEPGCache::gotMessage);
221 CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
222 CONNECT(cleanTimer->timeout, eEPGCache::cleanLoop);
224 ePtr<eDVBResourceManager> res_mgr;
225 eDVBResourceManager::getInstance(res_mgr);
227 eDebug("[eEPGCache] no resource manager !!!!!!!");
230 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
231 if (eDVBLocalTimeHandler::getInstance()->ready())
236 memset(m_filename, 0, sizeof(m_filename));
238 FILE *f = fopen("/etc/enigma2/epg.dat.src", "r");
241 int rd = fread(m_filename, 1, 255, f);
245 char *p=strchr(m_filename, '\n');
247 m_filename[p-m_filename] = 0;
248 p=strchr(m_filename, '\t');
250 m_filename[p-m_filename] = 0;
255 if (!strlen(m_filename))
256 strcpy(m_filename, "/hdd/epg.dat");
258 eDebug("[EPGC] read/write epg data from/to '%s'", m_filename);
261 void eEPGCache::timeUpdated()
265 eDebug("[EPGC] time updated.. start EPG Mainloop");
268 messages.send(Message(Message::timeChanged));
271 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
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;
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+
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);
293 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
295 channelMapIterator it =
296 m_knownChannels.find(chan);
297 if ( it == m_knownChannels.end() )
298 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
301 channel_data &data = *it->second;
302 ePtr<eDVBResourceManager> res_mgr;
303 if ( eDVBResourceManager::getInstance( res_mgr ) )
304 eDebug("[eEPGCache] no res manager!!");
307 ePtr<iDVBDemux> demux;
308 if ( data.channel->getDemux(demux, 0) )
310 eDebug("[eEPGCache] no demux!!");
315 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
318 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
322 res = demux->createSectionReader( this, data.m_ScheduleReader );
325 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
329 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
332 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
336 res = demux->createSectionReader( this, data.m_ViasatReader );
339 eDebug("[eEPGCache] couldnt initialize viasat reader!!");
342 #ifdef ENABLE_PRIVATE_EPG
343 res = demux->createSectionReader( this, data.m_PrivateReader );
346 eDebug("[eEPGCache] couldnt initialize private reader!!");
350 #ifdef ENABLE_MHW_EPG
351 res = demux->createSectionReader( this, data.m_MHWReader );
354 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
357 res = demux->createSectionReader( this, data.m_MHWReader2 );
360 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
364 messages.send(Message(Message::startChannel, chan));
365 // -> gotMessage -> changedService
371 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
373 channelMapIterator it =
374 m_knownChannels.find(chan);
375 if ( it != m_knownChannels.end() )
378 chan->getState(state);
379 if ( it->second->prevChannelState != state )
383 case iDVBChannel::state_ok:
385 eDebug("[eEPGCache] channel %p running", chan);
386 DVBChannelRunning(chan);
389 case iDVBChannel::state_release:
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);
399 // -> gotMessage -> abortEPG
402 default: // ignore all other events
406 it->second->prevChannelState = state;
411 bool eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
414 timeMap::iterator tmp = tm_it;
415 while ((tmp->first+tmp->second->getDuration()-300) > TM)
418 #ifdef ENABLE_PRIVATE_EPG
419 && tmp->second->type != PRIVATE
422 && tmp->second->type != MHW
426 __u16 event_id = tmp->second->getEventID();
427 servicemap.first.erase(event_id);
429 Event evt((uint8_t*)tmp->second->get());
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());
439 if (tmp == servicemap.second.begin())
441 servicemap.second.erase(tmp);
445 servicemap.second.erase(tmp--);
450 if (tmp == servicemap.second.begin())
457 while(tmp->first < (TM+duration-300))
459 if (tmp->first != TM && tmp->second->type != PRIVATE)
461 __u16 event_id = tmp->second->getEventID();
462 servicemap.first.erase(event_id);
464 Event evt((uint8_t*)tmp->second->get());
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());
474 servicemap.second.erase(tmp++);
479 if (tmp == servicemap.second.end())
485 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
487 eit_t *eit = (eit_t*) data;
489 int len=HILO(eit->section_length)-1;//+3-4;
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 )
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));
507 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
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);
519 if ( TM != 3599 && TM > -1)
520 channel->haveData |= source;
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();
532 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
534 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
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,
546 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
549 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
551 __u16 event_id = HILO(eit_event->event_id);
553 int ev_erase_count = 0;
554 int tm_erase_count = 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;
564 // search in eventmap
565 eventMap::iterator ev_it =
566 servicemap.first.find(event_id);
568 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
570 // entry with this event_id is already exist ?
571 if ( ev_it != servicemap.first.end() )
573 if ( source > ev_it->second->type ) // update needed ?
574 goto next; // when not.. then skip this entry
576 // search this event in timemap
577 timeMap::iterator tm_it_tmp =
578 servicemap.second.find(ev_it->second->getStartTime());
580 if ( tm_it_tmp != servicemap.second.end() )
582 if ( tm_it_tmp->first == TM ) // just update eventdata
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))
590 prevEventIt = servicemap.first.end();
591 prevTimeIt = servicemap.second.end();
596 else // event has new event begin time
599 // delete the found record from timemap
600 servicemap.second.erase(tm_it_tmp);
601 prevTimeIt=servicemap.second.end();
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);
611 if ( tm_it != servicemap.second.end() )
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
618 // search this time in eventmap
619 eventMap::iterator ev_it_tmp =
620 servicemap.first.find(tm_it->second->getEventID());
622 if ( ev_it_tmp != servicemap.first.end() )
625 // delete the found record from eventmap
626 servicemap.first.erase(ev_it_tmp);
627 prevEventIt=servicemap.first.end();
630 evt = new eventData(eit_event, eit_event_size, source);
632 bool consistencyCheck=true;
634 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
637 delete ev_it->second;
638 delete tm_it->second;
642 else if (ev_erase_count == 0 && tm_erase_count > 0)
645 delete ev_it->second;
646 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
649 else if (ev_erase_count > 0 && tm_erase_count == 0)
652 delete tm_it->second;
653 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
656 else // added new eventData
659 consistencyCheck=false;
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 ) );
666 if ( consistencyCheck )
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)",
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 );
684 if (FixOverlapping(servicemap, TM, duration, tm_it, service))
686 prevEventIt = servicemap.first.end();
687 prevTimeIt = servicemap.second.end();
692 if ( servicemap.first.size() != servicemap.second.size() )
694 FILE *f = fopen("/hdd/event_map.txt", "w+");
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 );
701 f = fopen("/hdd/time_map.txt", "w+");
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 );
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() );
714 ptr += eit_event_size;
715 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
719 void eEPGCache::flushEPG(const uniqueEPGKey & s)
721 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
722 singleLock l(cache_lock);
723 if (s) // clear only this service
725 eventCache::iterator it = eventDB.find(s);
726 if ( it != eventDB.end() )
728 eventMap &evMap = it->second.first;
729 timeMap &tmMap = it->second.second;
731 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
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() )
743 content_time_tables.erase(it);
748 else // clear complete EPG Cache
750 for (eventCache::iterator it(eventDB.begin());
751 it != eventDB.end(); ++it)
753 eventMap &evMap = it->second.first;
754 timeMap &tmMap = it->second.second;
755 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
761 #ifdef ENABLE_PRIVATE_EPG
762 content_time_tables.clear();
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();
769 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
772 void eEPGCache::cleanLoop()
774 singleLock s(cache_lock);
775 if (!eventDB.empty())
777 eDebug("[EPGC] start cleanloop");
779 time_t now = ::time(0);
781 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
783 bool updated = false;
784 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
786 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
788 // remove entry from eventMap
789 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
790 if ( b != DBIt->second.first.end() )
792 // release Heap Memory for this entry (new ....)
793 // eDebug("[EPGC] delete old event (evmap)");
794 DBIt->second.first.erase(b);
797 // remove entry from timeMap
798 // eDebug("[EPGC] release heap mem");
800 DBIt->second.second.erase(It++);
801 // eDebug("[EPGC] delete old event (timeMap)");
807 #ifdef ENABLE_PRIVATE_EPG
810 contentMaps::iterator x =
811 content_time_tables.find( DBIt->first );
812 if ( x != content_time_tables.end() )
814 timeMap &tmMap = DBIt->second.second;
815 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
817 for ( contentTimeMap::iterator it(i->second.begin());
818 it != i->second.end(); )
820 if ( tmMap.find(it->second.first) == tmMap.end() )
821 i->second.erase(it++);
825 if ( i->second.size() )
828 x->second.erase(i++);
834 eDebug("[EPGC] stop cleanloop");
835 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
837 cleanTimer->start(CLEAN_INTERVAL,true);
840 eEPGCache::~eEPGCache()
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++)
850 void eEPGCache::gotMessage( const Message &msg )
855 flushEPG(msg.service);
857 case Message::startChannel:
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();
866 case Message::leaveChannel:
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();
878 #ifdef ENABLE_PRIVATE_EPG
879 case Message::got_private_pid:
881 singleLock s(channel_map_lock);
882 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
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 )
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)
901 data->startPrivateTimer->start(update, 1);
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);
912 #ifdef ENABLE_MHW_EPG
913 case Message::got_mhw2_channel_pid:
915 singleLock s(channel_map_lock);
916 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
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 )
924 data->m_mhw2_channel_pid = msg.pid;
925 eDebug("[EPGC] got mhw2 channel pid %04x", msg.pid);
931 case Message::got_mhw2_title_pid:
933 singleLock s(channel_map_lock);
934 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
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 )
942 data->m_mhw2_title_pid = msg.pid;
943 eDebug("[EPGC] got mhw2 title pid %04x", msg.pid);
949 case Message::got_mhw2_summary_pid:
951 singleLock s(channel_map_lock);
952 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
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 )
960 data->m_mhw2_summary_pid = msg.pid;
961 eDebug("[EPGC] got mhw2 summary pid %04x", msg.pid);
968 case Message::timeChanged:
972 eDebug("unhandled EPGCache Message!!");
977 void eEPGCache::thread()
987 void eEPGCache::load()
989 FILE *f = fopen(m_filename, "r");
997 unsigned int magic=0;
998 fread( &magic, sizeof(int), 1, f);
999 if (magic != 0x98765432)
1001 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
1006 fread( text1, 13, 1, f);
1007 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
1009 singleLock s(cache_lock);
1010 fread( &size, sizeof(int), 1, f);
1017 fread( &key, sizeof(uniqueEPGKey), 1, f);
1018 fread( &size, sizeof(int), 1, f);
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;
1034 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
1037 eDebug("[EPGC] %d events read from %s", cnt, m_filename);
1038 #ifdef ENABLE_PRIVATE_EPG
1040 fread( text2, 11, 1, f);
1041 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
1044 fread( &size, sizeof(int), 1, f);
1049 fread( &key, sizeof(uniqueEPGKey), 1, f);
1050 eventMap &evMap=eventDB[key].first;
1051 fread( &size, sizeof(int), 1, f);
1056 fread( &content_id, sizeof(int), 1, f);
1057 fread( &size, sizeof(int), 1, f);
1060 time_t time1, time2;
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;
1074 #endif // ENABLE_PRIVATE_EPG
1077 eDebug("[EPGC] don't read old epg database");
1083 void eEPGCache::save()
1085 char *buf = realpath(m_filename, NULL);
1089 eDebug("[EPGC] store epg to '%s'", buf);
1093 if (statfs(buf, &s)<0)
1103 // prevent writes to builtin flash
1104 if ( tmp < 1024*1024*50 ) // storage size < 50MB
1107 // check for enough free space on storage
1110 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
1113 FILE *f = fopen(m_filename, "w");
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)
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)
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);
1138 eDebug("[EPGC] %d events written to %s", cnt, m_filename);
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)
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 )
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 )
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);
1166 // write version string after binary data
1167 // has been written to disk.
1169 fseek(f, sizeof(int), SEEK_SET);
1170 fwrite("ENIGMA_EPG_V7", 13, 1, f);
1175 eEPGCache::channel_data::channel_data(eEPGCache *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))
1182 #ifdef ENABLE_MHW_EPG
1183 ,m_MHWTimeoutTimer(eTimer::create(ml))
1186 #ifdef ENABLE_MHW_EPG
1187 CONNECT(m_MHWTimeoutTimer->timeout, eEPGCache::channel_data::MHWTimeout);
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);
1194 pthread_mutex_init(&channel_active, 0);
1197 bool eEPGCache::channel_data::finishEPG()
1199 if (!isRunning) // epg ready
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)
1206 seenSections[i].clear();
1207 calcedSections[i].clear();
1209 singleLock l(cache->cache_lock);
1210 cache->channelLastUpdated[channel->getChannelID()] = ::time(0);
1211 #ifdef ENABLE_MHW_EPG
1219 void eEPGCache::channel_data::startEPG()
1221 eDebug("[EPGC] start caching events(%ld)", ::time(0));
1224 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1226 seenSections[i].clear();
1227 calcedSections[i].clear();
1230 eDVBSectionFilterMask mask;
1231 memset(&mask, 0, sizeof(mask));
1233 #ifdef ENABLE_MHW_EPG
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);
1240 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1242 mask.pid = m_mhw2_channel_pid;
1243 mask.data[0] = 0xC8;
1244 mask.mask[0] = 0xFF;
1246 mask.mask[1] = 0xFF;
1247 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1248 m_MHWReader2->start(mask);
1250 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1253 m_MHWTimeoutet=false;
1257 mask.flags = eDVBSectionFilterMask::rfCRC;
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;
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;
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;
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;
1284 abortTimer->start(7000,true);
1287 void eEPGCache::channel_data::abortNonAvail()
1291 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1293 eDebug("[EPGC] abort non avail nownext reading");
1294 isRunning &= ~NOWNEXT;
1295 m_NowNextReader->stop();
1298 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1300 eDebug("[EPGC] abort non avail schedule reading");
1301 isRunning &= ~SCHEDULE;
1302 m_ScheduleReader->stop();
1305 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1307 eDebug("[EPGC] abort non avail schedule other reading");
1308 isRunning &= ~SCHEDULE_OTHER;
1309 m_ScheduleOtherReader->stop();
1310 m_ScheduleOtherConn=0;
1312 if ( !(haveData&VIASAT) && (isRunning&VIASAT) )
1314 eDebug("[EPGC] abort non avail viasat reading");
1315 isRunning &= ~VIASAT;
1316 m_ViasatReader->stop();
1319 #ifdef ENABLE_MHW_EPG
1320 if ( !(haveData&MHW) && (isRunning&MHW) )
1322 eDebug("[EPGC] abort non avail mhw reading");
1324 m_MHWReader->stop();
1326 m_MHWReader2->stop();
1330 if ( isRunning & VIASAT )
1331 abortTimer->start(300000, true);
1332 else if ( isRunning )
1333 abortTimer->start(90000, true);
1337 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1339 seenSections[i].clear();
1340 calcedSections[i].clear();
1347 void eEPGCache::channel_data::startChannel()
1349 pthread_mutex_lock(&channel_active);
1350 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1352 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
1354 if (update < ZAP_DELAY)
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);
1364 void eEPGCache::channel_data::abortEPG()
1366 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1368 seenSections[i].clear();
1369 calcedSections[i].clear();
1375 eDebug("[EPGC] abort caching events !!");
1376 if (isRunning & SCHEDULE)
1378 isRunning &= ~SCHEDULE;
1379 m_ScheduleReader->stop();
1382 if (isRunning & NOWNEXT)
1384 isRunning &= ~NOWNEXT;
1385 m_NowNextReader->stop();
1388 if (isRunning & SCHEDULE_OTHER)
1390 isRunning &= ~SCHEDULE_OTHER;
1391 m_ScheduleOtherReader->stop();
1392 m_ScheduleOtherConn=0;
1394 if (isRunning & VIASAT)
1396 isRunning &= ~VIASAT;
1397 m_ViasatReader->stop();
1400 #ifdef ENABLE_MHW_EPG
1401 if (isRunning & MHW)
1404 m_MHWReader->stop();
1406 m_MHWReader2->stop();
1411 #ifdef ENABLE_PRIVATE_EPG
1412 if (m_PrivateReader)
1413 m_PrivateReader->stop();
1417 pthread_mutex_unlock(&channel_active);
1421 void eEPGCache::channel_data::readDataViasat( const __u8 *data)
1424 memcpy(&d, &data, sizeof(__u8*));
1429 void eEPGCache::channel_data::readData( const __u8 *data)
1433 iDVBSectionReader *reader=NULL;
1437 reader=m_NowNextReader;
1442 reader=m_ScheduleReader;
1447 reader=m_ScheduleOtherReader;
1448 source=SCHEDULE_OTHER;
1453 reader=m_ViasatReader;
1458 eDebug("[EPGC] unknown table_id !!!");
1461 tidMap &seenSections = this->seenSections[map];
1462 tidMap &calcedSections = this->calcedSections[map];
1463 if ( (state == 1 && calcedSections == seenSections) || state > 1 )
1465 eDebugNoNewLine("[EPGC] ");
1470 eDebugNoNewLine("nownext");
1474 eDebugNoNewLine("schedule");
1476 case SCHEDULE_OTHER:
1477 m_ScheduleOtherConn=0;
1478 eDebugNoNewLine("schedule other");
1482 eDebugNoNewLine("viasat");
1484 default: eDebugNoNewLine("unknown");break;
1486 eDebug(" finished(%ld)", ::time(0));
1489 isRunning &= ~source;
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;
1501 tidMap::iterator it =
1502 seenSections.find(sectionNo);
1504 if ( it == seenSections.end() )
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 )
1512 if ( i == eit->section_number )
1514 for (int x=i; x <= eit->segment_last_section_number; ++x)
1515 calcedSections.insert(tmpval|(x&0xFF));
1518 calcedSections.insert(tmpval|(i&0xFF));
1520 cache->sectionRead(data, source, this);
1525 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1526 // if t == -1 we search the current event...
1528 singleLock s(cache_lock);
1529 uniqueEPGKey key(handleGroup(service));
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 ?
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() )
1541 if ( direction < 0 || (direction == 0 && i->first > t) )
1543 timeMap::iterator x = i;
1545 if ( x != It->second.second.end() )
1547 time_t start_time = x->first;
1552 if (t > (start_time+x->second->getDuration()))
1567 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1569 singleLock s(cache_lock);
1570 const eventData *data=0;
1571 RESULT ret = lookupEventTime(service, t, data, direction);
1573 result = data->get();
1577 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1579 singleLock s(cache_lock);
1580 const eventData *data=0;
1581 RESULT ret = lookupEventTime(service, t, data, direction);
1583 result = new Event((uint8_t*)data->get());
1587 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1589 singleLock s(cache_lock);
1590 const eventData *data=0;
1591 RESULT ret = lookupEventTime(service, t, data, direction);
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());
1602 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1604 singleLock s(cache_lock);
1605 uniqueEPGKey key(handleGroup(service));
1607 eventCache::iterator It = eventDB.find( key );
1608 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1610 eventMap::iterator i( It->second.first.find( event_id ));
1611 if ( i != It->second.first.end() )
1619 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1625 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1627 singleLock s(cache_lock);
1628 const eventData *data=0;
1629 RESULT ret = lookupEventId(service, event_id, data);
1631 result = data->get();
1635 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1637 singleLock s(cache_lock);
1638 const eventData *data=0;
1639 RESULT ret = lookupEventId(service, event_id, data);
1641 result = new Event((uint8_t*)data->get());
1645 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1647 singleLock s(cache_lock);
1648 const eventData *data=0;
1649 RESULT ret = lookupEventId(service, event_id, data);
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());
1660 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1662 singleLock s(cache_lock);
1663 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1666 eventCache::iterator It = eventDB.find(ref);
1667 if ( It != eventDB.end() && It->second.second.size() )
1669 m_timemap_cursor = It->second.second.lower_bound(begin);
1670 if ( m_timemap_cursor != It->second.second.end() )
1672 if ( m_timemap_cursor->first != begin )
1674 timeMap::iterator x = m_timemap_cursor;
1676 if ( x != It->second.second.end() )
1678 time_t start_time = x->first;
1679 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1680 m_timemap_cursor = x;
1686 m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1688 m_timemap_end = It->second.second.end();
1690 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1691 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1696 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1698 if ( m_timemap_cursor != m_timemap_end )
1700 result = m_timemap_cursor++->second;
1706 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1708 if ( m_timemap_cursor != m_timemap_end )
1710 result = m_timemap_cursor++->second->get();
1716 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1718 if ( m_timemap_cursor != m_timemap_end )
1720 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1726 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1728 if ( m_timemap_cursor != m_timemap_end )
1730 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1731 result = new eServiceEvent();
1732 return result->parseFrom(&ev, currentQueryTsidOnid);
1737 void fillTuple(ePyObject tuple, const char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1742 while(spos < argcount)
1744 bool inc_refcount=false;
1745 switch((c=argstring[spos++]))
1747 case '0': // PyLong 0
1748 tmp = PyLong_FromLong(0);
1750 case 'I': // Event Id
1751 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1753 case 'B': // Event Begin Time
1754 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1756 case 'D': // Event Duration
1757 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1759 case 'T': // Event Title
1760 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1762 case 'S': // Event Short Description
1763 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1765 case 'E': // Event Extended Description
1766 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1768 case 'C': // Current Time
1770 inc_refcount = true;
1772 case 'R': // service reference string
1774 inc_refcount = true;
1776 case 'n': // short service name
1777 case 'N': // service name
1779 inc_refcount = true;
1784 default: // ignore unknown
1786 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1791 inc_refcount = true;
1795 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1799 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1803 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1804 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1808 Py_DECREF(service_name);
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");
1818 PyList_Append(dest_list, result);
1823 ePyObject tuple = PyTuple_New(argcount);
1824 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1825 PyList_Append(dest_list, tuple);
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)
1835 // B = Event Begin Time
1836 // D = Event Duration
1838 // S = Event Short Description
1839 // E = Event Extended Description
1841 // R = Service Reference
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
1851 // -1 = event before given start_time
1852 // 0 = event intersects given start_time
1853 // +1 = event after given start_time
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)
1859 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1861 ePyObject convertFuncArgs;
1863 const char *argstring=NULL;
1864 if (!PyList_Check(list))
1866 PyErr_SetString(PyExc_StandardError,
1872 int listSize=PyList_Size(list);
1875 PyErr_SetString(PyExc_StandardError,
1876 "not params given");
1877 eDebug("not params given");
1882 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1883 if (PyString_Check(argv))
1885 argstring = PyString_AS_STRING(argv);
1889 argstring = "I"; // just event id as default
1890 argcount = strlen(argstring);
1891 // eDebug("have %d args('%s')", argcount, argstring);
1894 bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1900 if (!PyCallable_Check(convertFunc))
1902 PyErr_SetString(PyExc_StandardError,
1903 "convertFunc must be callable");
1904 eDebug("convertFunc is not callable");
1907 convertFuncArgs = PyTuple_New(argcount);
1910 ePyObject nowTime = strchr(argstring, 'C') ?
1911 PyLong_FromLong(::time(0)) :
1914 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1917 ePyObject dest_list=PyList_New(0);
1918 while(listSize > listIt)
1920 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1921 if (PyTuple_Check(item))
1923 bool service_changed=false;
1928 int tupleSize=PyTuple_Size(item);
1931 while(tupleSize > tupleIt) // parse query args
1933 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1938 if (!PyString_Check(entry))
1940 eDebug("tuple entry 0 is no a string");
1947 type=PyInt_AsLong(entry);
1948 if (type < -1 || type > 2)
1950 eDebug("unknown type %d", type);
1955 event_id=stime=PyInt_AsLong(entry);
1958 minutes=PyInt_AsLong(entry);
1961 eDebug("unneeded extra argument");
1966 if (minutes && stime == -1)
1969 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1970 if (ref.type != eServiceReference::idDVB)
1972 eDebug("service reference for epg query is not valid");
1976 // redirect subservice querys to parent service
1977 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1978 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1980 eServiceCenterPtr service_center;
1981 if (!eServiceCenter::getPrivInstance(service_center))
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));
1988 service = PyString_FromString(dvb_ref.toString().c_str());
1989 service_changed = true;
1993 ePyObject service_name;
1994 if (must_get_service_name)
1996 ePtr<iStaticServiceInformation> sptr;
1997 eServiceCenterPtr service_center;
1998 eServiceCenter::getPrivInstance(service_center);
2001 service_center->info(ref, sptr);
2005 sptr->getName(ref, name);
2007 if (must_get_service_name == 1)
2010 // filter short name brakets
2011 while((pos = name.find("\xc2\x86")) != std::string::npos)
2013 while((pos = name.find("\xc2\x87")) != std::string::npos)
2017 name = buildShortName(name);
2020 service_name = PyString_FromString(name.c_str());
2024 service_name = PyString_FromString("<n/a>");
2028 singleLock s(cache_lock);
2029 if (!startTimeQuery(ref, stime, minutes))
2031 while ( m_timemap_cursor != m_timemap_end )
2033 Event ev((uint8_t*)m_timemap_cursor++->second->get());
2035 evt.parseFrom(&ev, currentQueryTsidOnid);
2036 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2040 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2046 const eventData *ev_data=0;
2049 singleLock s(cache_lock);
2051 lookupEventId(ref, event_id, ev_data);
2053 lookupEventTime(ref, stime, ev_data, type);
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());
2063 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2066 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2069 if (service_changed)
2072 Py_DECREF(service_name);
2077 if (convertFuncArgs)
2078 Py_DECREF(convertFuncArgs);
2084 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2088 while(pos < argcount)
2090 bool inc_refcount=false;
2091 switch(argstring[pos])
2093 case '0': // PyLong 0
2094 tmp = PyLong_FromLong(0);
2096 case 'I': // Event Id
2097 tmp = PyLong_FromLong(evData->getEventID());
2099 case 'B': // Event Begin Time
2101 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2103 tmp = PyLong_FromLong(evData->getStartTime());
2105 case 'D': // Event Duration
2107 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2109 tmp = PyLong_FromLong(evData->getDuration());
2111 case 'T': // Event Title
2112 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2114 case 'S': // Event Short Description
2115 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2117 case 'E': // Event Extended Description
2118 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2120 case 'R': // service reference string
2121 tmp = service_reference;
2122 inc_refcount = true;
2124 case 'n': // short service name
2125 case 'N': // service name
2127 inc_refcount = true;
2129 default: // ignore unknown
2131 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2136 inc_refcount = true;
2140 PyTuple_SET_ITEM(tuple, pos++, tmp);
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)
2147 // B = Event Begin Time
2148 // D = Event Duration
2150 // S = Event Short Description
2151 // E = Event Extended Description
2152 // R = Service Reference
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
2166 // 0 = case sensitive (CASE_CHECK)
2167 // 1 = case insensitive (NO_CASECHECK)
2169 PyObject *eEPGCache::search(ePyObject arg)
2175 const char *argstring=0;
2179 bool needServiceEvent=false;
2181 int must_get_service_name = 0;
2182 bool must_get_service_reference = false;
2184 if (PyTuple_Check(arg))
2186 int tuplesize=PyTuple_Size(arg);
2189 ePyObject obj = PyTuple_GET_ITEM(arg,0);
2190 if (PyString_Check(obj))
2192 #if PY_VERSION_HEX < 0x02060000
2193 argcount = PyString_GET_SIZE(obj);
2195 argcount = PyString_Size(obj);
2197 argstring = PyString_AS_STRING(obj);
2198 for (int i=0; i < argcount; ++i)
2199 switch(argstring[i])
2204 needServiceEvent=true;
2207 must_get_service_name = 1;
2210 must_get_service_name = 2;
2213 must_get_service_reference = true;
2221 PyErr_SetString(PyExc_StandardError,
2223 eDebug("tuple arg 0 is not a string");
2228 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2231 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2232 if (tuplesize > 4 && querytype == 0)
2234 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2235 if (PyString_Check(obj))
2237 refstr = PyString_AS_STRING(obj);
2238 eServiceReferenceDVB ref(refstr);
2241 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2242 singleLock s(cache_lock);
2243 const eventData *evData = 0;
2244 lookupEventId(ref, eventid, evData);
2247 __u8 *data = evData->EITdata;
2248 int tmp = evData->ByteSize-10;
2249 __u32 *p = (__u32*)(data+10);
2250 // search short and extended event descriptors
2254 descriptorMap::iterator it =
2255 eventData::descriptors.find(crc);
2256 if (it != eventData::descriptors.end())
2258 __u8 *descr_data = it->second.second;
2259 switch(descr_data[0])
2262 descr[++descridx]=crc;
2271 eDebug("event not found");
2275 PyErr_SetString(PyExc_StandardError, "type error");
2276 eDebug("tuple arg 4 is not a valid service reference string");
2282 PyErr_SetString(PyExc_StandardError, "type error");
2283 eDebug("tuple arg 4 is not a string");
2287 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2289 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2290 if (PyString_Check(obj))
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);
2297 int textlen = PyString_Size(obj);
2300 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
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)
2307 __u8 *data = it->second.second;
2308 if ( data[0] == 0x4D ) // short event descriptor
2310 int title_len = data[5];
2311 if ( querytype == 1 )
2314 // skip DVB-Text Encoding!
2315 if (data[6] == 0x10)
2320 else if(data[6] > 0 && data[6] < 0x20)
2325 if (title_len != textlen)
2329 if ( !strncasecmp((const char*)data+offs, str, title_len) )
2331 // std::string s((const char*)data+offs, title_len);
2332 // eDebug("match1 %s %s", str, s.c_str() );
2333 descr[++descridx] = it->first;
2336 else if ( !strncmp((const char*)data+offs, str, title_len) )
2338 // std::string s((const char*)data+offs, title_len);
2339 // eDebug("match2 %s %s", str, s.c_str() );
2340 descr[++descridx] = it->first;
2346 while((title_len-idx) >= textlen)
2350 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
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() );
2358 else if (!strncmp((const char*)data+6+idx, str, textlen) )
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() );
2373 PyErr_SetString(PyExc_StandardError,
2375 eDebug("tuple arg 4 is not a string");
2381 PyErr_SetString(PyExc_StandardError,
2383 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2389 PyErr_SetString(PyExc_StandardError,
2391 eDebug("not enough args in tuple");
2397 PyErr_SetString(PyExc_StandardError,
2399 eDebug("arg 0 is not a tuple");
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)
2414 if ( ref.valid() && !first && cit->first == ref )
2416 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2420 ePyObject service_name;
2421 ePyObject service_reference;
2422 timeMap &evmap = cit->second.second;
2424 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2426 int evid = evit->second->getEventID();
2427 if ( evid == eventid)
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
2437 for ( int i=0; i <= descridx; ++i)
2439 if (descr[i] == crc32) // found...
2444 if ( (querytype == 0 && cnt == descridx) ||
2445 ((querytype == 1 || querytype == 2) && cnt != -1) )
2447 const uniqueEPGKey &service = cit->first;
2448 eServiceReference ref =
2449 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2452 // create servive event
2454 const eventData *ev_data=0;
2455 if (needServiceEvent)
2457 if (lookupEventId(ref, evid, ev_data))
2458 eDebug("event not found !!!!!!!!!!!");
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());
2466 // create service name
2467 if (must_get_service_name && !service_name)
2469 ePtr<iStaticServiceInformation> sptr;
2470 eServiceCenterPtr service_center;
2471 eServiceCenter::getPrivInstance(service_center);
2474 service_center->info(ref, sptr);
2478 sptr->getName(ref, name);
2480 if (must_get_service_name == 1)
2483 // filter short name brakets
2484 while((pos = name.find("\xc2\x86")) != std::string::npos)
2486 while((pos = name.find("\xc2\x87")) != std::string::npos)
2490 name = buildShortName(name);
2493 service_name = PyString_FromString(name.c_str());
2497 service_name = PyString_FromString("<n/a>");
2499 // create servicereference string
2500 if (must_get_service_reference && !service_reference)
2501 service_reference = PyString_FromString(ref.toString().c_str());
2504 ret = PyList_New(0);
2506 ePyObject tuple = PyTuple_New(argcount);
2508 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2509 PyList_Append(ret, tuple);
2516 Py_DECREF(service_name);
2517 if (service_reference)
2518 Py_DECREF(service_reference);
2521 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2523 cit=eventDB.begin();
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>
2541 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2543 ePtr<eTable<ProgramMapSection> > ptr;
2544 if (!pmthandler->getPMT(ptr) && ptr)
2546 std::vector<ProgramMapSection*>::const_iterator i;
2547 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2549 const ProgramMapSection &pmt = **i;
2551 ElementaryStreamInfoConstIterator es;
2552 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2555 switch ((*es)->getType())
2557 case 0xC1: // user private
2558 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2559 desc != (*es)->getDescriptors()->end(); ++desc)
2561 switch ((*desc)->getTag())
2563 case 0xC2: // user defined
2564 if ((*desc)->getLength() == 8)
2567 (*desc)->writeToBuffer(buffer);
2568 if (!strncmp((const char *)buffer+2, "EPGDATA", 7))
2570 eServiceReferenceDVB ref;
2571 if (!pmthandler->getServiceReference(ref))
2573 int pid = (*es)->getPid();
2574 messages.send(Message(Message::got_mhw2_channel_pid, ref, pid));
2577 else if(!strncmp((const char *)buffer+2, "FICHAS", 6))
2579 eServiceReferenceDVB ref;
2580 if (!pmthandler->getServiceReference(ref))
2582 int pid = (*es)->getPid();
2583 messages.send(Message(Message::got_mhw2_summary_pid, ref, pid));
2586 else if(!strncmp((const char *)buffer+2, "GENEROS", 7))
2588 eServiceReferenceDVB ref;
2589 if (!pmthandler->getServiceReference(ref))
2591 int pid = (*es)->getPid();
2592 messages.send(Message(Message::got_mhw2_title_pid, ref, pid));
2601 case 0x05: // private
2602 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2603 desc != (*es)->getDescriptors()->end(); ++desc)
2605 switch ((*desc)->getTag())
2607 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2608 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2613 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2614 int descr_len = descr->getLength();
2617 uint8_t data[descr_len+2];
2618 descr->writeToBuffer(data);
2619 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2633 eServiceReferenceDVB ref;
2634 if (!pmthandler->getServiceReference(ref))
2636 int pid = (*es)->getPid();
2637 messages.send(Message(Message::got_private_pid, ref, pid));
2645 eDebug("PMTready but no pmt!!");
2652 date_time( const date_time &a )
2654 memcpy(data, a.data, 5);
2657 date_time( const __u8 data[5])
2659 memcpy(this->data, data, 5);
2660 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2665 const __u8& operator[](int pos) const
2671 struct less_datetime
2673 bool operator()( const date_time &a, const date_time &b ) const
2675 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2679 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
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;
2687 int content_id = data[ptr++] << 24;
2688 content_id |= data[ptr++] << 16;
2689 content_id |= data[ptr++] << 8;
2690 content_id |= data[ptr++];
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 )
2697 eventMap::iterator evIt( evMap.find(it->second.second) );
2698 if ( evIt != evMap.end() )
2700 delete evIt->second;
2703 tmMap.erase(it->second.first);
2705 time_event_map.clear();
2708 memcpy(duration, data+ptr, 3);
2711 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2713 const __u8 *descriptors[65];
2714 const __u8 **pdescr = descriptors;
2716 int descriptors_length = (data[ptr++]&0x0F) << 8;
2717 descriptors_length |= data[ptr++];
2718 while ( descriptors_length > 1 )
2720 int descr_type = data[ptr];
2721 int descr_len = data[ptr+1];
2722 descriptors_length -= 2;
2723 if (descriptors_length >= descr_len)
2725 descriptors_length -= descr_len;
2726 if ( descr_type == 0xf2 && descr_len > 5)
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;
2736 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2739 switch( (tsid << 16) | sid )
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;
2750 ////////////////////////////////////////////
2752 uniqueEPGKey service( sid, onid, tsid );
2754 while( descr_len > 2 )
2757 datetime[0] = data[ptr++];
2758 datetime[1] = data[ptr++];
2759 int tmp_len = data[ptr++];
2761 if (descr_len >= tmp_len)
2763 descr_len -= tmp_len;
2764 while( tmp_len > 2 )
2766 memcpy(datetime+2, data+ptr, 3);
2769 start_times[datetime].push_back(service);
2782 ASSERT(pdescr <= &descriptors[65]);
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);
2789 const __u8 **d=descriptors;
2790 while ( d < pdescr )
2792 memcpy(event+ptr, *d, ((*d)[1])+2);
2796 ASSERT(ptr <= 4098);
2797 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2799 time_t now = ::time(0);
2800 if ( (it->first.tm + duration_sec) < now )
2802 memcpy(event+2, it->first.data, 5);
2805 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
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;
2819 int llen = bptr - 12;
2820 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2821 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2823 time_t stime = it->first.tm;
2824 while( tmMap.find(stime) != tmMap.end() )
2826 event[6] += (stime - it->first.tm);
2828 while( evMap.find(event_id) != evMap.end() )
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;
2836 ASSERT(bptr <= 4098);
2840 void eEPGCache::channel_data::startPrivateReader()
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)
2851 mask.data[3] = m_PrevVersion << 1;
2852 mask.mask[3] = 0x3E;
2853 mask.mode[3] = 0x3E;
2855 seenPrivateSections.clear();
2857 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2858 m_PrivateReader->start(mask);
2861 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2863 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2865 cache->privateSectionRead(m_PrivateService, data);
2866 seenPrivateSections.insert(data[6]);
2868 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
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();
2881 #endif // ENABLE_PRIVATE_EPG
2883 #ifdef ENABLE_MHW_EPG
2884 void eEPGCache::channel_data::cleanup()
2889 m_program_ids.clear();
2892 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
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.
2898 for ( i=0; i < len_in; i++ )
2902 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2909 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2912 return_time[0] = toBCD( hours );
2913 return_time[1] = toBCD( minutes );
2917 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2919 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
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
2925 char tz_saved[1024];
2926 // Remove offset in mhw time.
2927 __u8 local_hours = hours;
2930 else if ( hours >= 8 )
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);
2937 char *old_tz = getenv( "TZ" );
2939 strcpy(tz_saved, old_tz);
2940 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2944 localtime_r(&dt, &localnow);
2948 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2950 if (local_hours <= 5)
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.
2957 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2959 if ( old_tz == NULL )
2962 setenv("TZ", tz_saved, 1);
2965 // Calculate MJD according to annex in ETSI EN 300 468
2967 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2969 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2970 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2972 return_time[0] = (mjd & 0xFF00)>>8;
2973 return_time[1] = mjd & 0xFF;
2975 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
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.
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;
2987 eit_t *packet = (eit_t *) data;
2988 packet->table_id = 0x50;
2989 packet->section_syntax_indicator = 1;
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;
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();
3008 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3009 prog_title_length + 1;
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;
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 );
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 );
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;
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);
3049 event_name[prog_title_length] = 0;
3051 if ( sumText.length() > 0 )
3052 // There is summary info
3054 unsigned int sum_length = sumText.length();
3055 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
3056 // Store summary in short event descriptor
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 );
3066 // Store summary in extended event descriptors
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
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;
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;
3088 the_text[-1] = sum_length;
3089 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
3096 // Add content descriptor
3097 u_char *descriptor = (u_char *) data + packet_length;
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 )
3105 else if ( content_descr.find( "SPORT" ) != std::string::npos )
3108 descriptor[0] = 0x54;
3110 descriptor[2] = content_id;
3114 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
3115 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
3117 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
3118 packet->section_length_lo = (packet_length - 3)&0xff;
3120 // Feed the data to eEPGCache::sectionRead()
3121 cache->sectionRead( data, MHW, this );
3124 void eEPGCache::channel_data::startTimeout(int msec)
3126 m_MHWTimeoutTimer->start(msec,true);
3127 m_MHWTimeoutet=false;
3130 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
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);
3138 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
3140 m_MHWFilterMask2.pid = pid;
3141 m_MHWFilterMask2.data[0] = tid;
3144 m_MHWFilterMask2.data[1] = ext;
3145 m_MHWFilterMask2.mask[1] = 0xFF;
3146 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
3150 m_MHWFilterMask2.data[1] = 0;
3151 m_MHWFilterMask2.mask[1] = 0;
3152 // eDebug("start 0x%02x 0x%02x", pid, tid);
3154 m_MHWReader2->start(m_MHWFilterMask2);
3157 void eEPGCache::channel_data::readMHWData(const __u8 *data)
3160 m_MHWReader2->stop();
3162 if ( state > 1 || // aborted
3163 // have si data.. so we dont read mhw data
3164 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3166 eDebug("[EPGC] mhw aborted %d", state);
3168 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
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);
3175 m_channels.resize(nbr_records);
3176 for ( int i = 0; i < nbr_records; i++ )
3178 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
3179 m_channels[i]=*channel;
3183 eDebug("[EPGC] mhw %d channels found", m_channels.size());
3185 // Channels table has been read, start reading the themes table.
3186 startMHWReader(0xD3, 0x92);
3189 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
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);
3196 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
3199 for ( int i = 0; i < nbr_records; i++ )
3201 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
3202 if ( i >= next_idx )
3206 next_idx = (__u8) *(data + 3 + idx_ptr);
3212 m_themes[idx+sub_idx] = *theme;
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);
3220 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3223 mhw_title_t *title = (mhw_title_t*) data;
3225 if ( title->channel_id == 0xFF ) // Separator
3226 return; // Continue reading of the current table.
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);
3235 if ( m_titles.find( title_id ) == m_titles.end() )
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.
3248 else if (!checkTimeout())
3251 if ( !m_program_ids.empty())
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",
3258 m_program_ids.size());
3263 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3266 mhw_summary_t *summary = (mhw_summary_t*) data;
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];
3273 // ugly workaround to convert const __u8* to char*
3275 memcpy(&tmp, &data, sizeof(void*));
3276 tmp[len+3] = 0; // Terminate as a string.
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.
3287 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3290 while((pos = the_text.find("\r\n")) != std::string::npos)
3291 the_text.replace(pos, 2, " ");
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() )
3298 storeTitle( itTitle, the_text, data );
3299 m_titles.erase( itTitle );
3301 m_program_ids.erase( itProgid );
3302 if ( !m_program_ids.empty() )
3303 return; // Continue reading of the current table.
3306 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
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 );
3316 m_MHWReader->stop();
3321 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3323 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3326 m_MHWReader->stop();
3328 if ( state > 1 || // aborted
3329 // have si data.. so we dont read mhw data
3330 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3332 eDebug("[EPGC] mhw2 aborted %d", state);
3334 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3337 int num_channels = data[120];
3338 m_channels.resize(num_channels);
3341 int ptr = 121 + 8 * num_channels;
3344 for( int chid = 0; chid < num_channels; ++chid )
3346 ptr += ( data[ptr] & 0x0f ) + 1;
3356 // data seems consistent...
3357 const __u8 *tmp = data+121;
3358 for (int i=0; i < num_channels; ++i)
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));
3371 for (int i=0; i < num_channels; ++i)
3373 mhw_channel_name_t &channel = m_channels[i];
3374 int channel_name_len=*(tmp++)&0x0f;
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);
3382 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3384 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3387 eDebug("[EPGC] mhw2 themes nyi");
3389 else if (m_MHWFilterMask2.pid == m_mhw2_title_pid && m_MHWFilterMask2.data[0] == 0xe6)
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] );
3400 while( pos < dataLen && !valid)
3403 pos += (data[pos] & 0x3F) + 4;
3404 if( pos == dataLen )
3411 eDebug("mhw2 title table invalid!!");
3414 if (!m_MHWTimeoutTimer->isActive())
3416 return; // continue reading
3419 // data seems consistent...
3422 while (pos < dataLen)
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;
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];
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);
3445 // eDebug("%02x [%02x %02x]: %s", data[pos], data[pos+1], data[pos+2], dest);
3447 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3448 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3450 // if (title.channel_id > m_channels.size())
3451 // eDebug("channel_id(%d %02x) to big!!", title.channel_id);
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);
3456 // eDebug("title_id %08x -> summary_id %04x\n", title_id, summary_id);
3460 std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3461 if ( it == m_titles.end() )
3464 m_titles[ title_id ] = title;
3465 if (summary_id != 0xFFFF)
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)
3471 if (it->second == title_id) {
3478 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3483 if ( !checkTimeout() )
3484 continue; // Continue reading of the current table.
3492 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3493 if (!m_program_ids.empty())
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);
3505 else if (m_MHWFilterMask2.pid == m_mhw2_summary_pid && m_MHWFilterMask2.data[0] == 0x96)
3508 if (!checkTimeout())
3510 int len, loop, pos, lenline;
3519 loop = data[pos] & 0x0f;
3524 for( ; loop > 0; --loop )
3526 if( dataLen > (pos+len) )
3528 lenline = data[pos+len];
3538 return; // continue reading
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] );
3547 // ugly workaround to convert const __u8* to char*
3549 memcpy(&tmp, &data, sizeof(void*));
3554 loop = tmp[pos] & 0x0f;
3556 for( ; loop > 0; loop -- )
3558 lenline = tmp[pos+len];
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.
3576 startTimeout(15000);
3577 std::string the_text = (char *) (data + pos + 1);
3579 // eDebug ("summary id %04x : %s\n", summary_id, data+pos+1);
3581 while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
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() )
3588 storeTitle( itTitle, the_text, data );
3589 m_titles.erase( itTitle );
3591 m_program_ids.erase( itProgId++ );
3593 if ( !m_program_ids.empty() )
3594 return; // Continue reading of the current table.
3598 return; // continue reading
3601 if (isRunning & eEPGCache::MHW)
3603 if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3605 // Channels table has been read, start reading the themes table.
3606 startMHWReader2(m_mhw2_channel_pid, 0xC8, 1);
3609 else if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3611 // Themes table has been read, start reading the titles table.
3612 startMHWReader2(m_mhw2_title_pid, 0xe6);
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",
3623 m_program_ids.size());
3630 m_MHWReader2->stop();