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)), m_running(0)//, paused(0)
218 eDebug("[EPGC] Initialized EPGCache (wait for setCacheFile call now)");
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 !!!!!!!");
229 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
232 memset(m_filename, 0, sizeof(m_filename));
235 void eEPGCache::setCacheFile(const char *path)
237 bool inited = !!strlen(m_filename);
238 strncpy(m_filename, path, 1024);
241 eDebug("[EPGC] setCacheFile read/write epg data from/to '%s'", m_filename);
242 if (eDVBLocalTimeHandler::getInstance()->ready())
247 void eEPGCache::timeUpdated()
249 if (strlen(m_filename))
253 eDebug("[EPGC] time updated.. start EPG Mainloop");
255 singleLock s(channel_map_lock);
256 channelMapIterator it = m_knownChannels.begin();
257 for (; it != m_knownChannels.end(); ++it)
259 if (it->second->state == -1) {
261 messages.send(Message(Message::startChannel, it->first));
265 messages.send(Message(Message::timeChanged));
268 eDebug("[EPGC] time updated.. but cache file not set yet.. dont start epg!!");
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!!");
366 messages.send(Message(Message::startChannel, chan));
367 // -> gotMessage -> changedService
376 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
378 channelMapIterator it =
379 m_knownChannels.find(chan);
380 if ( it != m_knownChannels.end() )
383 chan->getState(state);
384 if ( it->second->prevChannelState != state )
388 case iDVBChannel::state_ok:
390 eDebug("[eEPGCache] channel %p running", chan);
391 DVBChannelRunning(chan);
394 case iDVBChannel::state_release:
396 eDebug("[eEPGCache] remove channel %p", chan);
397 if (it->second->state >= 0)
398 messages.send(Message(Message::leaveChannel, chan));
399 pthread_mutex_lock(&it->second->channel_active);
400 singleLock s(channel_map_lock);
401 m_knownChannels.erase(it);
402 pthread_mutex_unlock(&it->second->channel_active);
405 // -> gotMessage -> abortEPG
408 default: // ignore all other events
412 it->second->prevChannelState = state;
417 bool eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
420 timeMap::iterator tmp = tm_it;
421 while ((tmp->first+tmp->second->getDuration()-300) > TM)
424 #ifdef ENABLE_PRIVATE_EPG
425 && tmp->second->type != PRIVATE
428 && tmp->second->type != MHW
432 __u16 event_id = tmp->second->getEventID();
433 servicemap.first.erase(event_id);
435 Event evt((uint8_t*)tmp->second->get());
437 event.parseFrom(&evt, service.sid<<16|service.onid);
438 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
439 service.sid, event_id,
440 event.getBeginTimeString().c_str(),
441 event.getEventName().c_str(),
442 event.getExtendedDescription().c_str());
445 if (tmp == servicemap.second.begin())
447 servicemap.second.erase(tmp);
451 servicemap.second.erase(tmp--);
456 if (tmp == servicemap.second.begin())
463 while(tmp->first < (TM+duration-300))
465 if (tmp->first != TM && tmp->second->type != PRIVATE)
467 __u16 event_id = tmp->second->getEventID();
468 servicemap.first.erase(event_id);
470 Event evt((uint8_t*)tmp->second->get());
472 event.parseFrom(&evt, service.sid<<16|service.onid);
473 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
474 service.sid, event_id,
475 event.getBeginTimeString().c_str(),
476 event.getEventName().c_str(),
477 event.getExtendedDescription().c_str());
480 servicemap.second.erase(tmp++);
485 if (tmp == servicemap.second.end())
491 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
493 eit_t *eit = (eit_t*) data;
495 int len=HILO(eit->section_length)-1;//+3-4;
500 // This fixed the EPG on the Multichoice irdeto systems
501 // the EIT packet is non-compliant.. their EIT packet stinks
502 if ( data[ptr-1] < 0x40 )
505 // Cablecom HACK .. tsid / onid in eit data are incorrect.. so we use
506 // it from running channel (just for current transport stream eit data)
507 bool use_transponder_chid = source == SCHEDULE || (source == NOWNEXT && data[0] == 0x4E);
508 eDVBChannelID chid = channel->channel->getChannelID();
509 uniqueEPGKey service( HILO(eit->service_id),
510 use_transponder_chid ? chid.original_network_id.get() : HILO(eit->original_network_id),
511 use_transponder_chid ? chid.transport_stream_id.get() : HILO(eit->transport_stream_id));
513 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
517 time_t TM = parseDVBtime(
518 eit_event->start_time_1,
519 eit_event->start_time_2,
520 eit_event->start_time_3,
521 eit_event->start_time_4,
522 eit_event->start_time_5);
523 time_t now = ::time(0);
525 if ( TM != 3599 && TM > -1)
526 channel->haveData |= source;
528 singleLock s(cache_lock);
529 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
530 // oder eine durch [] erzeugte
531 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
532 eventMap::iterator prevEventIt = servicemap.first.end();
533 timeMap::iterator prevTimeIt = servicemap.second.end();
538 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
540 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
542 eit_event->start_time_1,
543 eit_event->start_time_2,
544 eit_event->start_time_3,
545 eit_event->start_time_4,
546 eit_event->start_time_5,
552 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
555 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
557 __u16 event_id = HILO(eit_event->event_id);
559 int ev_erase_count = 0;
560 int tm_erase_count = 0;
563 // hack for some polsat services on 13.0E..... but this also replaces other valid event_ids with value 0..
564 // but we dont care about it...
565 event_id = event_hash;
566 eit_event->event_id_hi = event_hash >> 8;
567 eit_event->event_id_lo = event_hash & 0xFF;
570 // search in eventmap
571 eventMap::iterator ev_it =
572 servicemap.first.find(event_id);
574 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
576 // entry with this event_id is already exist ?
577 if ( ev_it != servicemap.first.end() )
579 if ( source > ev_it->second->type ) // update needed ?
580 goto next; // when not.. then skip this entry
582 // search this event in timemap
583 timeMap::iterator tm_it_tmp =
584 servicemap.second.find(ev_it->second->getStartTime());
586 if ( tm_it_tmp != servicemap.second.end() )
588 if ( tm_it_tmp->first == TM ) // just update eventdata
591 eventData *tmp = ev_it->second;
592 ev_it->second = tm_it_tmp->second =
593 new eventData(eit_event, eit_event_size, source);
594 if (FixOverlapping(servicemap, TM, duration, tm_it_tmp, service))
596 prevEventIt = servicemap.first.end();
597 prevTimeIt = servicemap.second.end();
602 else // event has new event begin time
605 // delete the found record from timemap
606 servicemap.second.erase(tm_it_tmp);
607 prevTimeIt=servicemap.second.end();
612 // search in timemap, for check of a case if new time has coincided with time of other event
613 // or event was is not found in eventmap
614 timeMap::iterator tm_it =
615 servicemap.second.find(TM);
617 if ( tm_it != servicemap.second.end() )
619 // event with same start time but another event_id...
620 if ( source > tm_it->second->type &&
621 ev_it == servicemap.first.end() )
622 goto next; // when not.. then skip this entry
624 // search this time in eventmap
625 eventMap::iterator ev_it_tmp =
626 servicemap.first.find(tm_it->second->getEventID());
628 if ( ev_it_tmp != servicemap.first.end() )
631 // delete the found record from eventmap
632 servicemap.first.erase(ev_it_tmp);
633 prevEventIt=servicemap.first.end();
636 evt = new eventData(eit_event, eit_event_size, source);
638 bool consistencyCheck=true;
640 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
643 delete ev_it->second;
644 delete tm_it->second;
648 else if (ev_erase_count == 0 && tm_erase_count > 0)
651 delete ev_it->second;
652 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
655 else if (ev_erase_count > 0 && tm_erase_count == 0)
658 delete tm_it->second;
659 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
662 else // added new eventData
665 consistencyCheck=false;
667 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
668 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
672 if ( consistencyCheck )
674 if ( tm_it->second != evt || ev_it->second != evt )
675 eFatal("tm_it->second != ev_it->second");
676 else if ( tm_it->second->getStartTime() != tm_it->first )
677 eFatal("event start_time(%d) non equal timemap key(%d)",
678 tm_it->second->getStartTime(), tm_it->first );
679 else if ( tm_it->first != TM )
680 eFatal("timemap key(%d) non equal TM(%d)",
682 else if ( ev_it->second->getEventID() != ev_it->first )
683 eFatal("event_id (%d) non equal event_map key(%d)",
684 ev_it->second->getEventID(), ev_it->first);
685 else if ( ev_it->first != event_id )
686 eFatal("eventmap key(%d) non equal event_id(%d)",
687 ev_it->first, event_id );
690 if (FixOverlapping(servicemap, TM, duration, tm_it, service))
692 prevEventIt = servicemap.first.end();
693 prevTimeIt = servicemap.second.end();
698 if ( servicemap.first.size() != servicemap.second.size() )
700 FILE *f = fopen("/hdd/event_map.txt", "w+");
702 for (eventMap::iterator it(servicemap.first.begin())
703 ; it != servicemap.first.end(); ++it )
704 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
705 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
707 f = fopen("/hdd/time_map.txt", "w+");
709 for (timeMap::iterator it(servicemap.second.begin())
710 ; it != servicemap.second.end(); ++it )
711 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
712 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
715 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
716 service.sid, service.tsid, service.onid,
717 servicemap.first.size(), servicemap.second.size() );
720 ptr += eit_event_size;
721 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
725 void eEPGCache::flushEPG(const uniqueEPGKey & s)
727 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
728 singleLock l(cache_lock);
729 if (s) // clear only this service
731 eventCache::iterator it = eventDB.find(s);
732 if ( it != eventDB.end() )
734 eventMap &evMap = it->second.first;
735 timeMap &tmMap = it->second.second;
737 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
742 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
743 #ifdef ENABLE_PRIVATE_EPG
744 contentMaps::iterator it =
745 content_time_tables.find(s);
746 if ( it != content_time_tables.end() )
749 content_time_tables.erase(it);
754 else // clear complete EPG Cache
756 for (eventCache::iterator it(eventDB.begin());
757 it != eventDB.end(); ++it)
759 eventMap &evMap = it->second.first;
760 timeMap &tmMap = it->second.second;
761 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
767 #ifdef ENABLE_PRIVATE_EPG
768 content_time_tables.clear();
770 channelLastUpdated.clear();
771 singleLock m(channel_map_lock);
772 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
773 it->second->startEPG();
775 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
778 void eEPGCache::cleanLoop()
780 singleLock s(cache_lock);
781 if (!eventDB.empty())
783 eDebug("[EPGC] start cleanloop");
785 time_t now = ::time(0);
787 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
789 bool updated = false;
790 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
792 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
794 // remove entry from eventMap
795 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
796 if ( b != DBIt->second.first.end() )
798 // release Heap Memory for this entry (new ....)
799 // eDebug("[EPGC] delete old event (evmap)");
800 DBIt->second.first.erase(b);
803 // remove entry from timeMap
804 // eDebug("[EPGC] release heap mem");
806 DBIt->second.second.erase(It++);
807 // eDebug("[EPGC] delete old event (timeMap)");
813 #ifdef ENABLE_PRIVATE_EPG
816 contentMaps::iterator x =
817 content_time_tables.find( DBIt->first );
818 if ( x != content_time_tables.end() )
820 timeMap &tmMap = DBIt->second.second;
821 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
823 for ( contentTimeMap::iterator it(i->second.begin());
824 it != i->second.end(); )
826 if ( tmMap.find(it->second.first) == tmMap.end() )
827 i->second.erase(it++);
831 if ( i->second.size() )
834 x->second.erase(i++);
840 eDebug("[EPGC] stop cleanloop");
841 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
843 cleanTimer->start(CLEAN_INTERVAL,true);
846 eEPGCache::~eEPGCache()
848 messages.send(Message::quit);
849 kill(); // waiting for thread shutdown
850 singleLock s(cache_lock);
851 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
852 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
856 void eEPGCache::gotMessage( const Message &msg )
861 flushEPG(msg.service);
863 case Message::startChannel:
865 singleLock s(channel_map_lock);
866 channelMapIterator channel =
867 m_knownChannels.find(msg.channel);
868 if ( channel != m_knownChannels.end() )
869 channel->second->startChannel();
872 case Message::leaveChannel:
874 singleLock s(channel_map_lock);
875 channelMapIterator channel =
876 m_knownChannels.find(msg.channel);
877 if ( channel != m_knownChannels.end() )
878 channel->second->abortEPG();
884 #ifdef ENABLE_PRIVATE_EPG
885 case Message::got_private_pid:
887 singleLock s(channel_map_lock);
888 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
890 eDVBChannel *channel = (eDVBChannel*) it->first;
891 channel_data *data = it->second;
892 eDVBChannelID chid = channel->getChannelID();
893 if ( chid.transport_stream_id.get() == msg.service.tsid &&
894 chid.original_network_id.get() == msg.service.onid &&
895 data->m_PrivatePid == -1 )
897 data->m_PrevVersion = -1;
898 data->m_PrivatePid = msg.pid;
899 data->m_PrivateService = msg.service;
900 int onid = chid.original_network_id.get();
901 onid |= 0x80000000; // we use highest bit as private epg indicator
902 chid.original_network_id = onid;
903 updateMap::iterator It = channelLastUpdated.find( chid );
904 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
905 if (update < ZAP_DELAY)
907 data->startPrivateTimer->start(update, 1);
909 eDebug("[EPGC] next private update in %i min", update/60000);
910 else if (update >= 1000)
911 eDebug("[EPGC] next private update in %i sec", update/1000);
918 #ifdef ENABLE_MHW_EPG
919 case Message::got_mhw2_channel_pid:
921 singleLock s(channel_map_lock);
922 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
924 eDVBChannel *channel = (eDVBChannel*) it->first;
925 channel_data *data = it->second;
926 eDVBChannelID chid = channel->getChannelID();
927 if ( chid.transport_stream_id.get() == msg.service.tsid &&
928 chid.original_network_id.get() == msg.service.onid )
930 data->m_mhw2_channel_pid = msg.pid;
931 eDebug("[EPGC] got mhw2 channel pid %04x", msg.pid);
937 case Message::got_mhw2_title_pid:
939 singleLock s(channel_map_lock);
940 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
942 eDVBChannel *channel = (eDVBChannel*) it->first;
943 channel_data *data = it->second;
944 eDVBChannelID chid = channel->getChannelID();
945 if ( chid.transport_stream_id.get() == msg.service.tsid &&
946 chid.original_network_id.get() == msg.service.onid )
948 data->m_mhw2_title_pid = msg.pid;
949 eDebug("[EPGC] got mhw2 title pid %04x", msg.pid);
955 case Message::got_mhw2_summary_pid:
957 singleLock s(channel_map_lock);
958 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
960 eDVBChannel *channel = (eDVBChannel*) it->first;
961 channel_data *data = it->second;
962 eDVBChannelID chid = channel->getChannelID();
963 if ( chid.transport_stream_id.get() == msg.service.tsid &&
964 chid.original_network_id.get() == msg.service.onid )
966 data->m_mhw2_summary_pid = msg.pid;
967 eDebug("[EPGC] got mhw2 summary pid %04x", msg.pid);
974 case Message::timeChanged:
978 eDebug("unhandled EPGCache Message!!");
983 void eEPGCache::thread()
995 void eEPGCache::load()
997 FILE *f = fopen(m_filename, "r");
1005 unsigned int magic=0;
1006 fread( &magic, sizeof(int), 1, f);
1007 if (magic != 0x98765432)
1009 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
1014 fread( text1, 13, 1, f);
1015 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
1017 singleLock s(cache_lock);
1018 fread( &size, sizeof(int), 1, f);
1025 fread( &key, sizeof(uniqueEPGKey), 1, f);
1026 fread( &size, sizeof(int), 1, f);
1032 fread( &type, sizeof(__u8), 1, f);
1033 fread( &len, sizeof(__u8), 1, f);
1034 event = new eventData(0, len, type);
1035 event->EITdata = new __u8[len];
1036 eventData::CacheSize+=len;
1037 fread( event->EITdata, len, 1, f);
1038 evMap[ event->getEventID() ]=event;
1039 tmMap[ event->getStartTime() ]=event;
1042 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
1045 eDebug("[EPGC] %d events read from %s", cnt, m_filename);
1046 #ifdef ENABLE_PRIVATE_EPG
1048 fread( text2, 11, 1, f);
1049 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
1052 fread( &size, sizeof(int), 1, f);
1057 fread( &key, sizeof(uniqueEPGKey), 1, f);
1058 eventMap &evMap=eventDB[key].first;
1059 fread( &size, sizeof(int), 1, f);
1064 fread( &content_id, sizeof(int), 1, f);
1065 fread( &size, sizeof(int), 1, f);
1068 time_t time1, time2;
1070 fread( &time1, sizeof(time_t), 1, f);
1071 fread( &time2, sizeof(time_t), 1, f);
1072 fread( &event_id, sizeof(__u16), 1, f);
1073 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
1074 eventMap::iterator it =
1075 evMap.find(event_id);
1076 if (it != evMap.end())
1077 it->second->type = PRIVATE;
1082 #endif // ENABLE_PRIVATE_EPG
1085 eDebug("[EPGC] don't read old epg database");
1091 void eEPGCache::save()
1093 /* create empty file */
1094 FILE *f = fopen(m_filename, "w");
1098 eDebug("[EPGC] couldn't save epg data to '%s'(%m)", m_filename);
1102 char *buf = realpath(m_filename, NULL);
1105 eDebug("[EPGC] realpath to '%s' failed in save (%m)", m_filename);
1110 eDebug("[EPGC] store epg to realpath '%s'", buf);
1114 if (statfs(buf, &s) < 0) {
1115 eDebug("[EPGC] statfs '%s' failed in save (%m)", buf);
1122 // check for enough free space on storage
1125 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
1127 eDebug("[EPGC] not enough free space at path '%s' %lld bytes availd but %d needed", buf, tmp, (eventData::CacheSize*12)/10);
1133 unsigned int magic = 0x98765432;
1134 fwrite( &magic, sizeof(int), 1, f);
1135 const char *text = "UNFINISHED_V7";
1136 fwrite( text, 13, 1, f );
1137 int size = eventDB.size();
1138 fwrite( &size, sizeof(int), 1, f );
1139 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1141 timeMap &timemap = service_it->second.second;
1142 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1143 size = timemap.size();
1144 fwrite( &size, sizeof(int), 1, f);
1145 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1147 __u8 len = time_it->second->ByteSize;
1148 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1149 fwrite( &len, sizeof(__u8), 1, f);
1150 fwrite( time_it->second->EITdata, len, 1, f);
1154 eDebug("[EPGC] %d events written to %s", cnt, m_filename);
1156 #ifdef ENABLE_PRIVATE_EPG
1157 const char* text3 = "PRIVATE_EPG";
1158 fwrite( text3, 11, 1, f );
1159 size = content_time_tables.size();
1160 fwrite( &size, sizeof(int), 1, f);
1161 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1163 contentMap &content_time_table = a->second;
1164 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1165 int size = content_time_table.size();
1166 fwrite( &size, sizeof(int), 1, f);
1167 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1169 int size = i->second.size();
1170 fwrite( &i->first, sizeof(int), 1, f);
1171 fwrite( &size, sizeof(int), 1, f);
1172 for ( contentTimeMap::iterator it(i->second.begin());
1173 it != i->second.end(); ++it )
1175 fwrite( &it->first, sizeof(time_t), 1, f);
1176 fwrite( &it->second.first, sizeof(time_t), 1, f);
1177 fwrite( &it->second.second, sizeof(__u16), 1, f);
1182 // write version string after binary data
1183 // has been written to disk.
1185 fseek(f, sizeof(int), SEEK_SET);
1186 fwrite("ENIGMA_EPG_V7", 13, 1, f);
1190 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1192 ,abortTimer(eTimer::create(ml)), zapTimer(eTimer::create(ml)), state(-2)
1193 ,isRunning(0), haveData(0)
1194 #ifdef ENABLE_PRIVATE_EPG
1195 ,startPrivateTimer(eTimer::create(ml))
1197 #ifdef ENABLE_MHW_EPG
1198 ,m_MHWTimeoutTimer(eTimer::create(ml))
1201 #ifdef ENABLE_MHW_EPG
1202 CONNECT(m_MHWTimeoutTimer->timeout, eEPGCache::channel_data::MHWTimeout);
1204 CONNECT(zapTimer->timeout, eEPGCache::channel_data::startEPG);
1205 CONNECT(abortTimer->timeout, eEPGCache::channel_data::abortNonAvail);
1206 #ifdef ENABLE_PRIVATE_EPG
1207 CONNECT(startPrivateTimer->timeout, eEPGCache::channel_data::startPrivateReader);
1209 pthread_mutex_init(&channel_active, 0);
1212 bool eEPGCache::channel_data::finishEPG()
1214 if (!isRunning) // epg ready
1216 eDebug("[EPGC] stop caching events(%ld)", ::time(0));
1217 zapTimer->start(UPDATE_INTERVAL, 1);
1218 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1219 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1221 seenSections[i].clear();
1222 calcedSections[i].clear();
1224 singleLock l(cache->cache_lock);
1225 cache->channelLastUpdated[channel->getChannelID()] = ::time(0);
1226 #ifdef ENABLE_MHW_EPG
1234 void eEPGCache::channel_data::startEPG()
1236 eDebug("[EPGC] start caching events(%ld)", ::time(0));
1239 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1241 seenSections[i].clear();
1242 calcedSections[i].clear();
1245 eDVBSectionFilterMask mask;
1246 memset(&mask, 0, sizeof(mask));
1248 #ifdef ENABLE_MHW_EPG
1250 mask.data[0] = 0x91;
1251 mask.mask[0] = 0xFF;
1252 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1253 m_MHWReader->start(mask);
1255 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1257 mask.pid = m_mhw2_channel_pid;
1258 mask.data[0] = 0xC8;
1259 mask.mask[0] = 0xFF;
1261 mask.mask[1] = 0xFF;
1262 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1263 m_MHWReader2->start(mask);
1265 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1268 m_MHWTimeoutet=false;
1272 mask.flags = eDVBSectionFilterMask::rfCRC;
1274 mask.data[0] = 0x4E;
1275 mask.mask[0] = 0xFE;
1276 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1277 m_NowNextReader->start(mask);
1278 isRunning |= NOWNEXT;
1280 mask.data[0] = 0x50;
1281 mask.mask[0] = 0xF0;
1282 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1283 m_ScheduleReader->start(mask);
1284 isRunning |= SCHEDULE;
1286 mask.data[0] = 0x60;
1287 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1288 m_ScheduleOtherReader->start(mask);
1289 isRunning |= SCHEDULE_OTHER;
1293 mask.data[0] = 0x40;
1294 mask.mask[0] = 0x40;
1295 m_ViasatReader->connectRead(slot(*this, &eEPGCache::channel_data::readDataViasat), m_ViasatConn);
1296 m_ViasatReader->start(mask);
1297 isRunning |= VIASAT;
1299 abortTimer->start(7000,true);
1302 void eEPGCache::channel_data::abortNonAvail()
1306 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1308 eDebug("[EPGC] abort non avail nownext reading");
1309 isRunning &= ~NOWNEXT;
1310 m_NowNextReader->stop();
1313 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1315 eDebug("[EPGC] abort non avail schedule reading");
1316 isRunning &= ~SCHEDULE;
1317 m_ScheduleReader->stop();
1320 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1322 eDebug("[EPGC] abort non avail schedule other reading");
1323 isRunning &= ~SCHEDULE_OTHER;
1324 m_ScheduleOtherReader->stop();
1325 m_ScheduleOtherConn=0;
1327 if ( !(haveData&VIASAT) && (isRunning&VIASAT) )
1329 eDebug("[EPGC] abort non avail viasat reading");
1330 isRunning &= ~VIASAT;
1331 m_ViasatReader->stop();
1334 #ifdef ENABLE_MHW_EPG
1335 if ( !(haveData&MHW) && (isRunning&MHW) )
1337 eDebug("[EPGC] abort non avail mhw reading");
1339 m_MHWReader->stop();
1341 m_MHWReader2->stop();
1345 if ( isRunning & VIASAT )
1346 abortTimer->start(300000, true);
1347 else if ( isRunning )
1348 abortTimer->start(90000, true);
1352 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1354 seenSections[i].clear();
1355 calcedSections[i].clear();
1362 void eEPGCache::channel_data::startChannel()
1364 pthread_mutex_lock(&channel_active);
1365 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1367 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
1369 if (update < ZAP_DELAY)
1372 zapTimer->start(update, 1);
1373 if (update >= 60000)
1374 eDebug("[EPGC] next update in %i min", update/60000);
1375 else if (update >= 1000)
1376 eDebug("[EPGC] next update in %i sec", update/1000);
1379 void eEPGCache::channel_data::abortEPG()
1381 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1383 seenSections[i].clear();
1384 calcedSections[i].clear();
1390 eDebug("[EPGC] abort caching events !!");
1391 if (isRunning & SCHEDULE)
1393 isRunning &= ~SCHEDULE;
1394 m_ScheduleReader->stop();
1397 if (isRunning & NOWNEXT)
1399 isRunning &= ~NOWNEXT;
1400 m_NowNextReader->stop();
1403 if (isRunning & SCHEDULE_OTHER)
1405 isRunning &= ~SCHEDULE_OTHER;
1406 m_ScheduleOtherReader->stop();
1407 m_ScheduleOtherConn=0;
1409 if (isRunning & VIASAT)
1411 isRunning &= ~VIASAT;
1412 m_ViasatReader->stop();
1415 #ifdef ENABLE_MHW_EPG
1416 if (isRunning & MHW)
1419 m_MHWReader->stop();
1421 m_MHWReader2->stop();
1426 #ifdef ENABLE_PRIVATE_EPG
1427 if (m_PrivateReader)
1428 m_PrivateReader->stop();
1432 pthread_mutex_unlock(&channel_active);
1436 void eEPGCache::channel_data::readDataViasat( const __u8 *data)
1439 memcpy(&d, &data, sizeof(__u8*));
1444 void eEPGCache::channel_data::readData( const __u8 *data)
1448 iDVBSectionReader *reader=NULL;
1452 reader=m_NowNextReader;
1457 reader=m_ScheduleReader;
1462 reader=m_ScheduleOtherReader;
1463 source=SCHEDULE_OTHER;
1468 reader=m_ViasatReader;
1473 eDebug("[EPGC] unknown table_id !!!");
1476 tidMap &seenSections = this->seenSections[map];
1477 tidMap &calcedSections = this->calcedSections[map];
1478 if ( (state == 1 && calcedSections == seenSections) || state > 1 )
1480 eDebugNoNewLine("[EPGC] ");
1485 eDebugNoNewLine("nownext");
1489 eDebugNoNewLine("schedule");
1491 case SCHEDULE_OTHER:
1492 m_ScheduleOtherConn=0;
1493 eDebugNoNewLine("schedule other");
1497 eDebugNoNewLine("viasat");
1499 default: eDebugNoNewLine("unknown");break;
1501 eDebug(" finished(%ld)", ::time(0));
1504 isRunning &= ~source;
1510 eit_t *eit = (eit_t*) data;
1511 __u32 sectionNo = data[0] << 24;
1512 sectionNo |= data[3] << 16;
1513 sectionNo |= data[4] << 8;
1514 sectionNo |= eit->section_number;
1516 tidMap::iterator it =
1517 seenSections.find(sectionNo);
1519 if ( it == seenSections.end() )
1521 seenSections.insert(sectionNo);
1522 calcedSections.insert(sectionNo);
1523 __u32 tmpval = sectionNo & 0xFFFFFF00;
1524 __u8 incr = source == NOWNEXT ? 1 : 8;
1525 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1527 if ( i == eit->section_number )
1529 for (int x=i; x <= eit->segment_last_section_number; ++x)
1530 calcedSections.insert(tmpval|(x&0xFF));
1533 calcedSections.insert(tmpval|(i&0xFF));
1535 cache->sectionRead(data, source, this);
1540 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1541 // if t == -1 we search the current event...
1543 singleLock s(cache_lock);
1544 uniqueEPGKey key(handleGroup(service));
1546 // check if EPG for this service is ready...
1547 eventCache::iterator It = eventDB.find( key );
1548 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1552 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1553 It->second.second.upper_bound(t); // just >
1554 if ( i != It->second.second.end() )
1556 if ( direction < 0 || (direction == 0 && i->first > t) )
1558 timeMap::iterator x = i;
1560 if ( x != It->second.second.end() )
1562 time_t start_time = x->first;
1567 if (t > (start_time+x->second->getDuration()))
1582 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1584 singleLock s(cache_lock);
1585 const eventData *data=0;
1586 RESULT ret = lookupEventTime(service, t, data, direction);
1588 result = data->get();
1592 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1594 singleLock s(cache_lock);
1595 const eventData *data=0;
1596 RESULT ret = lookupEventTime(service, t, data, direction);
1598 result = new Event((uint8_t*)data->get());
1602 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1604 singleLock s(cache_lock);
1605 const eventData *data=0;
1606 RESULT ret = lookupEventTime(service, t, data, direction);
1609 Event ev((uint8_t*)data->get());
1610 result = new eServiceEvent();
1611 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1612 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1617 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1619 singleLock s(cache_lock);
1620 uniqueEPGKey key(handleGroup(service));
1622 eventCache::iterator It = eventDB.find( key );
1623 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1625 eventMap::iterator i( It->second.first.find( event_id ));
1626 if ( i != It->second.first.end() )
1634 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1640 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1642 singleLock s(cache_lock);
1643 const eventData *data=0;
1644 RESULT ret = lookupEventId(service, event_id, data);
1646 result = data->get();
1650 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1652 singleLock s(cache_lock);
1653 const eventData *data=0;
1654 RESULT ret = lookupEventId(service, event_id, data);
1656 result = new Event((uint8_t*)data->get());
1660 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1662 singleLock s(cache_lock);
1663 const eventData *data=0;
1664 RESULT ret = lookupEventId(service, event_id, data);
1667 Event ev((uint8_t*)data->get());
1668 result = new eServiceEvent();
1669 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1670 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1675 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1677 singleLock s(cache_lock);
1678 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1681 eventCache::iterator It = eventDB.find(ref);
1682 if ( It != eventDB.end() && It->second.second.size() )
1684 m_timemap_cursor = It->second.second.lower_bound(begin);
1685 if ( m_timemap_cursor != It->second.second.end() )
1687 if ( m_timemap_cursor->first != begin )
1689 timeMap::iterator x = m_timemap_cursor;
1691 if ( x != It->second.second.end() )
1693 time_t start_time = x->first;
1694 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1695 m_timemap_cursor = x;
1701 m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1703 m_timemap_end = It->second.second.end();
1705 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1706 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1711 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1713 if ( m_timemap_cursor != m_timemap_end )
1715 result = m_timemap_cursor++->second;
1721 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1723 if ( m_timemap_cursor != m_timemap_end )
1725 result = m_timemap_cursor++->second->get();
1731 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1733 if ( m_timemap_cursor != m_timemap_end )
1735 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1741 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1743 if ( m_timemap_cursor != m_timemap_end )
1745 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1746 result = new eServiceEvent();
1747 return result->parseFrom(&ev, currentQueryTsidOnid);
1752 void fillTuple(ePyObject tuple, const char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1757 while(spos < argcount)
1759 bool inc_refcount=false;
1760 switch((c=argstring[spos++]))
1762 case '0': // PyLong 0
1763 tmp = PyLong_FromLong(0);
1765 case 'I': // Event Id
1766 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1768 case 'B': // Event Begin Time
1769 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1771 case 'D': // Event Duration
1772 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1774 case 'T': // Event Title
1775 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1777 case 'S': // Event Short Description
1778 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1780 case 'E': // Event Extended Description
1781 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1783 case 'C': // Current Time
1785 inc_refcount = true;
1787 case 'R': // service reference string
1789 inc_refcount = true;
1791 case 'n': // short service name
1792 case 'N': // service name
1794 inc_refcount = true;
1799 default: // ignore unknown
1801 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1806 inc_refcount = true;
1810 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1814 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1818 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1819 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1823 Py_DECREF(service_name);
1826 Py_DECREF(convertFuncArgs);
1827 Py_DECREF(dest_list);
1828 PyErr_SetString(PyExc_StandardError,
1829 "error in convertFunc execute");
1830 eDebug("error in convertFunc execute");
1833 PyList_Append(dest_list, result);
1838 ePyObject tuple = PyTuple_New(argcount);
1839 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1840 PyList_Append(dest_list, tuple);
1846 // here we get a python list
1847 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1850 // B = Event Begin Time
1851 // D = Event Duration
1853 // S = Event Short Description
1854 // E = Event Extended Description
1856 // R = Service Reference
1858 // n = Short Service Name
1859 // X = Return a minimum of one tuple per service in the result list... even when no event was found.
1860 // The returned tuple is filled with all available infos... non avail is filled as None
1861 // The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1862 // then for each service follows a tuple
1863 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1864 // the second is the type of query
1866 // -1 = event before given start_time
1867 // 0 = event intersects given start_time
1868 // +1 = event after given start_time
1870 // when type is eventid it is the event_id
1871 // when type is time then it is the start_time ( -1 for now_time )
1872 // the fourth is the end_time .. ( optional .. for query all events in time range)
1874 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1876 ePyObject convertFuncArgs;
1878 const char *argstring=NULL;
1879 if (!PyList_Check(list))
1881 PyErr_SetString(PyExc_StandardError,
1887 int listSize=PyList_Size(list);
1890 PyErr_SetString(PyExc_StandardError,
1891 "not params given");
1892 eDebug("not params given");
1897 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1898 if (PyString_Check(argv))
1900 argstring = PyString_AS_STRING(argv);
1904 argstring = "I"; // just event id as default
1905 argcount = strlen(argstring);
1906 // eDebug("have %d args('%s')", argcount, argstring);
1909 bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1915 if (!PyCallable_Check(convertFunc))
1917 PyErr_SetString(PyExc_StandardError,
1918 "convertFunc must be callable");
1919 eDebug("convertFunc is not callable");
1922 convertFuncArgs = PyTuple_New(argcount);
1925 ePyObject nowTime = strchr(argstring, 'C') ?
1926 PyLong_FromLong(::time(0)) :
1929 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1932 ePyObject dest_list=PyList_New(0);
1933 while(listSize > listIt)
1935 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1936 if (PyTuple_Check(item))
1938 bool service_changed=false;
1943 int tupleSize=PyTuple_Size(item);
1946 while(tupleSize > tupleIt) // parse query args
1948 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1953 if (!PyString_Check(entry))
1955 eDebug("tuple entry 0 is no a string");
1962 type=PyInt_AsLong(entry);
1963 if (type < -1 || type > 2)
1965 eDebug("unknown type %d", type);
1970 event_id=stime=PyInt_AsLong(entry);
1973 minutes=PyInt_AsLong(entry);
1976 eDebug("unneeded extra argument");
1981 if (minutes && stime == -1)
1984 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1985 if (ref.type != eServiceReference::idDVB)
1987 eDebug("service reference for epg query is not valid");
1991 // redirect subservice querys to parent service
1992 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1993 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1995 eServiceCenterPtr service_center;
1996 if (!eServiceCenter::getPrivInstance(service_center))
1998 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1999 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
2000 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
2001 dvb_ref.setParentServiceID(eServiceID(0));
2003 service = PyString_FromString(dvb_ref.toString().c_str());
2004 service_changed = true;
2008 ePyObject service_name;
2009 if (must_get_service_name)
2011 ePtr<iStaticServiceInformation> sptr;
2012 eServiceCenterPtr service_center;
2013 eServiceCenter::getPrivInstance(service_center);
2016 service_center->info(ref, sptr);
2020 sptr->getName(ref, name);
2022 if (must_get_service_name == 1)
2025 // filter short name brakets
2026 while((pos = name.find("\xc2\x86")) != std::string::npos)
2028 while((pos = name.find("\xc2\x87")) != std::string::npos)
2032 name = buildShortName(name);
2035 service_name = PyString_FromString(name.c_str());
2039 service_name = PyString_FromString("<n/a>");
2043 singleLock s(cache_lock);
2044 if (!startTimeQuery(ref, stime, minutes))
2046 while ( m_timemap_cursor != m_timemap_end )
2048 Event ev((uint8_t*)m_timemap_cursor++->second->get());
2050 evt.parseFrom(&ev, currentQueryTsidOnid);
2051 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2055 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2061 const eventData *ev_data=0;
2064 singleLock s(cache_lock);
2066 lookupEventId(ref, event_id, ev_data);
2068 lookupEventTime(ref, stime, ev_data, type);
2071 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2072 Event ev((uint8_t*)ev_data->get());
2073 evt.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2078 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2081 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2084 if (service_changed)
2087 Py_DECREF(service_name);
2092 if (convertFuncArgs)
2093 Py_DECREF(convertFuncArgs);
2099 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2103 while(pos < argcount)
2105 bool inc_refcount=false;
2106 switch(argstring[pos])
2108 case '0': // PyLong 0
2109 tmp = PyLong_FromLong(0);
2111 case 'I': // Event Id
2112 tmp = PyLong_FromLong(evData->getEventID());
2114 case 'B': // Event Begin Time
2116 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2118 tmp = PyLong_FromLong(evData->getStartTime());
2120 case 'D': // Event Duration
2122 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2124 tmp = PyLong_FromLong(evData->getDuration());
2126 case 'T': // Event Title
2127 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2129 case 'S': // Event Short Description
2130 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2132 case 'E': // Event Extended Description
2133 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2135 case 'R': // service reference string
2136 tmp = service_reference;
2137 inc_refcount = true;
2139 case 'n': // short service name
2140 case 'N': // service name
2142 inc_refcount = true;
2144 default: // ignore unknown
2146 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2151 inc_refcount = true;
2155 PyTuple_SET_ITEM(tuple, pos++, tmp);
2159 // here we get a python tuple
2160 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2162 // B = Event Begin Time
2163 // D = Event Duration
2165 // S = Event Short Description
2166 // E = Event Extended Description
2167 // R = Service Reference
2169 // n = Short Service Name
2170 // the second tuple entry is the MAX matches value
2171 // the third tuple entry is the type of query
2172 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2173 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2174 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2175 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2176 // the fourth is the servicereference string
2177 // the fifth is the eventid
2178 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2179 // the fourth is the search text
2181 // 0 = case sensitive (CASE_CHECK)
2182 // 1 = case insensitive (NO_CASECHECK)
2184 PyObject *eEPGCache::search(ePyObject arg)
2190 const char *argstring=0;
2194 bool needServiceEvent=false;
2196 int must_get_service_name = 0;
2197 bool must_get_service_reference = false;
2199 if (PyTuple_Check(arg))
2201 int tuplesize=PyTuple_Size(arg);
2204 ePyObject obj = PyTuple_GET_ITEM(arg,0);
2205 if (PyString_Check(obj))
2207 #if PY_VERSION_HEX < 0x02060000
2208 argcount = PyString_GET_SIZE(obj);
2210 argcount = PyString_Size(obj);
2212 argstring = PyString_AS_STRING(obj);
2213 for (int i=0; i < argcount; ++i)
2214 switch(argstring[i])
2219 needServiceEvent=true;
2222 must_get_service_name = 1;
2225 must_get_service_name = 2;
2228 must_get_service_reference = true;
2236 PyErr_SetString(PyExc_StandardError,
2238 eDebug("tuple arg 0 is not a string");
2243 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2246 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2247 if (tuplesize > 4 && querytype == 0)
2249 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2250 if (PyString_Check(obj))
2252 refstr = PyString_AS_STRING(obj);
2253 eServiceReferenceDVB ref(refstr);
2256 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2257 singleLock s(cache_lock);
2258 const eventData *evData = 0;
2259 lookupEventId(ref, eventid, evData);
2262 __u8 *data = evData->EITdata;
2263 int tmp = evData->ByteSize-10;
2264 __u32 *p = (__u32*)(data+10);
2265 // search short and extended event descriptors
2269 descriptorMap::iterator it =
2270 eventData::descriptors.find(crc);
2271 if (it != eventData::descriptors.end())
2273 __u8 *descr_data = it->second.second;
2274 switch(descr_data[0])
2277 descr[++descridx]=crc;
2286 eDebug("event not found");
2290 PyErr_SetString(PyExc_StandardError, "type error");
2291 eDebug("tuple arg 4 is not a valid service reference string");
2297 PyErr_SetString(PyExc_StandardError, "type error");
2298 eDebug("tuple arg 4 is not a string");
2302 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2304 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2305 if (PyString_Check(obj))
2307 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2308 const char *str = PyString_AS_STRING(obj);
2309 #if PY_VERSION_HEX < 0x02060000
2310 int textlen = PyString_GET_SIZE(obj);
2312 int textlen = PyString_Size(obj);
2315 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2317 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2318 singleLock s(cache_lock);
2319 for (descriptorMap::iterator it(eventData::descriptors.begin());
2320 it != eventData::descriptors.end() && descridx < 511; ++it)
2322 __u8 *data = it->second.second;
2323 if ( data[0] == 0x4D ) // short event descriptor
2325 int title_len = data[5];
2326 if ( querytype == 1 )
2329 // skip DVB-Text Encoding!
2330 if (data[6] == 0x10)
2335 else if(data[6] > 0 && data[6] < 0x20)
2340 if (title_len != textlen)
2344 if ( !strncasecmp((const char*)data+offs, str, title_len) )
2346 // std::string s((const char*)data+offs, title_len);
2347 // eDebug("match1 %s %s", str, s.c_str() );
2348 descr[++descridx] = it->first;
2351 else if ( !strncmp((const char*)data+offs, str, title_len) )
2353 // std::string s((const char*)data+offs, title_len);
2354 // eDebug("match2 %s %s", str, s.c_str() );
2355 descr[++descridx] = it->first;
2361 while((title_len-idx) >= textlen)
2365 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2367 descr[++descridx] = it->first;
2368 // std::string s((const char*)data+6, title_len);
2369 // eDebug("match 3 %s %s", str, s.c_str() );
2373 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2375 descr[++descridx] = it->first;
2376 // std::string s((const char*)data+6, title_len);
2377 // eDebug("match 4 %s %s", str, s.c_str() );
2388 PyErr_SetString(PyExc_StandardError,
2390 eDebug("tuple arg 4 is not a string");
2396 PyErr_SetString(PyExc_StandardError,
2398 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2404 PyErr_SetString(PyExc_StandardError,
2406 eDebug("not enough args in tuple");
2412 PyErr_SetString(PyExc_StandardError,
2414 eDebug("arg 0 is not a tuple");
2420 int maxcount=maxmatches;
2421 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2422 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2423 // in this case we start searching with the base service
2424 bool first = ref.valid() ? true : false;
2425 singleLock s(cache_lock);
2426 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2427 while(cit != eventDB.end() && maxcount)
2429 if ( ref.valid() && !first && cit->first == ref )
2431 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2435 ePyObject service_name;
2436 ePyObject service_reference;
2437 timeMap &evmap = cit->second.second;
2439 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2441 int evid = evit->second->getEventID();
2442 if ( evid == eventid)
2444 __u8 *data = evit->second->EITdata;
2445 int tmp = evit->second->ByteSize-10;
2446 __u32 *p = (__u32*)(data+10);
2447 // check if any of our descriptor used by this event
2452 for ( int i=0; i <= descridx; ++i)
2454 if (descr[i] == crc32) // found...
2459 if ( (querytype == 0 && cnt == descridx) ||
2460 ((querytype == 1 || querytype == 2) && cnt != -1) )
2462 const uniqueEPGKey &service = cit->first;
2463 eServiceReference ref =
2464 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2467 // create servive event
2469 const eventData *ev_data=0;
2470 if (needServiceEvent)
2472 if (lookupEventId(ref, evid, ev_data))
2473 eDebug("event not found !!!!!!!!!!!");
2476 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2477 Event ev((uint8_t*)ev_data->get());
2478 ptr.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2481 // create service name
2482 if (must_get_service_name && !service_name)
2484 ePtr<iStaticServiceInformation> sptr;
2485 eServiceCenterPtr service_center;
2486 eServiceCenter::getPrivInstance(service_center);
2489 service_center->info(ref, sptr);
2493 sptr->getName(ref, name);
2495 if (must_get_service_name == 1)
2498 // filter short name brakets
2499 while((pos = name.find("\xc2\x86")) != std::string::npos)
2501 while((pos = name.find("\xc2\x87")) != std::string::npos)
2505 name = buildShortName(name);
2508 service_name = PyString_FromString(name.c_str());
2512 service_name = PyString_FromString("<n/a>");
2514 // create servicereference string
2515 if (must_get_service_reference && !service_reference)
2516 service_reference = PyString_FromString(ref.toString().c_str());
2519 ret = PyList_New(0);
2521 ePyObject tuple = PyTuple_New(argcount);
2523 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2524 PyList_Append(ret, tuple);
2531 Py_DECREF(service_name);
2532 if (service_reference)
2533 Py_DECREF(service_reference);
2536 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2538 cit=eventDB.begin();
2551 #ifdef ENABLE_PRIVATE_EPG
2552 #include <dvbsi++/descriptor_tag.h>
2553 #include <dvbsi++/unknown_descriptor.h>
2554 #include <dvbsi++/private_data_specifier_descriptor.h>
2556 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2558 ePtr<eTable<ProgramMapSection> > ptr;
2559 if (!pmthandler->getPMT(ptr) && ptr)
2561 std::vector<ProgramMapSection*>::const_iterator i;
2562 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2564 const ProgramMapSection &pmt = **i;
2566 ElementaryStreamInfoConstIterator es;
2567 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2570 switch ((*es)->getType())
2572 case 0xC1: // user private
2573 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2574 desc != (*es)->getDescriptors()->end(); ++desc)
2576 switch ((*desc)->getTag())
2578 case 0xC2: // user defined
2579 if ((*desc)->getLength() == 8)
2582 (*desc)->writeToBuffer(buffer);
2583 if (!strncmp((const char *)buffer+2, "EPGDATA", 7))
2585 eServiceReferenceDVB ref;
2586 if (!pmthandler->getServiceReference(ref))
2588 int pid = (*es)->getPid();
2589 messages.send(Message(Message::got_mhw2_channel_pid, ref, pid));
2592 else if(!strncmp((const char *)buffer+2, "FICHAS", 6))
2594 eServiceReferenceDVB ref;
2595 if (!pmthandler->getServiceReference(ref))
2597 int pid = (*es)->getPid();
2598 messages.send(Message(Message::got_mhw2_summary_pid, ref, pid));
2601 else if(!strncmp((const char *)buffer+2, "GENEROS", 7))
2603 eServiceReferenceDVB ref;
2604 if (!pmthandler->getServiceReference(ref))
2606 int pid = (*es)->getPid();
2607 messages.send(Message(Message::got_mhw2_title_pid, ref, pid));
2616 case 0x05: // private
2617 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2618 desc != (*es)->getDescriptors()->end(); ++desc)
2620 switch ((*desc)->getTag())
2622 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2623 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2628 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2629 int descr_len = descr->getLength();
2632 uint8_t data[descr_len+2];
2633 descr->writeToBuffer(data);
2634 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2648 eServiceReferenceDVB ref;
2649 if (!pmthandler->getServiceReference(ref))
2651 int pid = (*es)->getPid();
2652 messages.send(Message(Message::got_private_pid, ref, pid));
2660 eDebug("PMTready but no pmt!!");
2667 date_time( const date_time &a )
2669 memcpy(data, a.data, 5);
2672 date_time( const __u8 data[5])
2674 memcpy(this->data, data, 5);
2675 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2680 const __u8& operator[](int pos) const
2686 struct less_datetime
2688 bool operator()( const date_time &a, const date_time &b ) const
2690 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2694 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2696 contentMap &content_time_table = content_time_tables[current_service];
2697 singleLock s(cache_lock);
2698 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2699 eventMap &evMap = eventDB[current_service].first;
2700 timeMap &tmMap = eventDB[current_service].second;
2702 int content_id = data[ptr++] << 24;
2703 content_id |= data[ptr++] << 16;
2704 content_id |= data[ptr++] << 8;
2705 content_id |= data[ptr++];
2707 contentTimeMap &time_event_map =
2708 content_time_table[content_id];
2709 for ( contentTimeMap::iterator it( time_event_map.begin() );
2710 it != time_event_map.end(); ++it )
2712 eventMap::iterator evIt( evMap.find(it->second.second) );
2713 if ( evIt != evMap.end() )
2715 delete evIt->second;
2718 tmMap.erase(it->second.first);
2720 time_event_map.clear();
2723 memcpy(duration, data+ptr, 3);
2726 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2728 const __u8 *descriptors[65];
2729 const __u8 **pdescr = descriptors;
2731 int descriptors_length = (data[ptr++]&0x0F) << 8;
2732 descriptors_length |= data[ptr++];
2733 while ( descriptors_length > 1 )
2735 int descr_type = data[ptr];
2736 int descr_len = data[ptr+1];
2737 descriptors_length -= 2;
2738 if (descriptors_length >= descr_len)
2740 descriptors_length -= descr_len;
2741 if ( descr_type == 0xf2 && descr_len > 5)
2744 int tsid = data[ptr++] << 8;
2745 tsid |= data[ptr++];
2746 int onid = data[ptr++] << 8;
2747 onid |= data[ptr++];
2748 int sid = data[ptr++] << 8;
2751 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2754 switch( (tsid << 16) | sid )
2756 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2757 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2758 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2759 case 0x0300f5: sid = 0xdc; break;
2760 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2761 case 0x1100d3: sid = 0xe3; break;
2762 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2765 ////////////////////////////////////////////
2767 uniqueEPGKey service( sid, onid, tsid );
2769 while( descr_len > 2 )
2772 datetime[0] = data[ptr++];
2773 datetime[1] = data[ptr++];
2774 int tmp_len = data[ptr++];
2776 if (descr_len >= tmp_len)
2778 descr_len -= tmp_len;
2779 while( tmp_len > 2 )
2781 memcpy(datetime+2, data+ptr, 3);
2784 start_times[datetime].push_back(service);
2797 ASSERT(pdescr <= &descriptors[65]);
2799 eit_event_struct *ev_struct = (eit_event_struct*) event;
2800 ev_struct->running_status = 0;
2801 ev_struct->free_CA_mode = 1;
2802 memcpy(event+7, duration, 3);
2804 const __u8 **d=descriptors;
2805 while ( d < pdescr )
2807 memcpy(event+ptr, *d, ((*d)[1])+2);
2811 ASSERT(ptr <= 4098);
2812 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2814 time_t now = ::time(0);
2815 if ( (it->first.tm + duration_sec) < now )
2817 memcpy(event+2, it->first.data, 5);
2820 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2822 event[bptr++] = 0x4A;
2823 __u8 *len = event+(bptr++);
2824 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2825 event[bptr++] = (i->tsid & 0xFF);
2826 event[bptr++] = (i->onid & 0xFF00) >> 8;
2827 event[bptr++] = (i->onid & 0xFF);
2828 event[bptr++] = (i->sid & 0xFF00) >> 8;
2829 event[bptr++] = (i->sid & 0xFF);
2830 event[bptr++] = 0xB0;
2831 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2832 *len = ((event+bptr) - len)-1;
2834 int llen = bptr - 12;
2835 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2836 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2838 time_t stime = it->first.tm;
2839 while( tmMap.find(stime) != tmMap.end() )
2841 event[6] += (stime - it->first.tm);
2843 while( evMap.find(event_id) != evMap.end() )
2845 event[0] = (event_id & 0xFF00) >> 8;
2846 event[1] = (event_id & 0xFF);
2847 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2848 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2849 evMap[event_id] = d;
2851 ASSERT(bptr <= 4098);
2855 void eEPGCache::channel_data::startPrivateReader()
2857 eDVBSectionFilterMask mask;
2858 memset(&mask, 0, sizeof(mask));
2859 mask.pid = m_PrivatePid;
2860 mask.flags = eDVBSectionFilterMask::rfCRC;
2861 mask.data[0] = 0xA0;
2862 mask.mask[0] = 0xFF;
2863 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2864 if (m_PrevVersion != -1)
2866 mask.data[3] = m_PrevVersion << 1;
2867 mask.mask[3] = 0x3E;
2868 mask.mode[3] = 0x3E;
2870 seenPrivateSections.clear();
2872 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2873 m_PrivateReader->start(mask);
2876 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2878 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2880 cache->privateSectionRead(m_PrivateService, data);
2881 seenPrivateSections.insert(data[6]);
2883 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2885 eDebug("[EPGC] private finished");
2886 eDVBChannelID chid = channel->getChannelID();
2887 int tmp = chid.original_network_id.get();
2888 tmp |= 0x80000000; // we use highest bit as private epg indicator
2889 chid.original_network_id = tmp;
2890 cache->channelLastUpdated[chid] = ::time(0);
2891 m_PrevVersion = (data[5] & 0x3E) >> 1;
2892 startPrivateReader();
2896 #endif // ENABLE_PRIVATE_EPG
2898 #ifdef ENABLE_MHW_EPG
2899 void eEPGCache::channel_data::cleanup()
2904 m_program_ids.clear();
2907 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2909 // Names in mhw structs are not strings as they are not '\0' terminated.
2910 // This function converts the mhw name into a string.
2911 // Constraint: "length of out" = "length of in" + 1.
2913 for ( i=0; i < len_in; i++ )
2917 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2924 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2927 return_time[0] = toBCD( hours );
2928 return_time[1] = toBCD( minutes );
2932 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2934 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2937 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2938 // For date plus time of day
2940 char tz_saved[1024];
2941 // Remove offset in mhw time.
2942 __u8 local_hours = hours;
2945 else if ( hours >= 8 )
2948 // As far as we know all mhw time data is sent in central Europe time zone.
2949 // So, temporarily set timezone to western europe
2950 time_t dt = ::time(0);
2952 char *old_tz = getenv( "TZ" );
2954 strcpy(tz_saved, old_tz);
2955 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2959 localtime_r(&dt, &localnow);
2963 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2965 if (local_hours <= 5)
2968 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2969 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2972 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2974 if ( old_tz == NULL )
2977 setenv("TZ", tz_saved, 1);
2980 // Calculate MJD according to annex in ETSI EN 300 468
2982 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2984 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2985 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2987 return_time[0] = (mjd & 0xFF00)>>8;
2988 return_time[1] = mjd & 0xFF;
2990 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2993 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2994 // data is borrowed from calling proc to save memory space.
2998 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2999 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
3000 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
3002 eit_t *packet = (eit_t *) data;
3003 packet->table_id = 0x50;
3004 packet->section_syntax_indicator = 1;
3006 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
3007 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
3008 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3009 packet->current_next_indicator = 0;
3010 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3011 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3012 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
3013 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
3014 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
3015 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
3016 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3017 packet->segment_last_table_id = 0x50;
3019 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
3020 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 35 : 23 );
3021 int prog_title_length = prog_title.length();
3023 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3024 prog_title_length + 1;
3026 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
3027 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
3028 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
3032 u_char *data = (u_char*) event_data;
3033 data[2] = itTitle->second.mhw2_mjd_hi;
3034 data[3] = itTitle->second.mhw2_mjd_lo;
3035 data[4] = itTitle->second.mhw2_hours;
3036 data[5] = itTitle->second.mhw2_minutes;
3037 data[6] = itTitle->second.mhw2_seconds;
3038 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
3042 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
3043 (u_char *) event_data + 2 );
3044 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
3047 event_data->running_status = 0;
3048 event_data->free_CA_mode = 0;
3049 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
3051 eit_short_event_descriptor_struct *short_event_descriptor =
3052 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
3053 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
3054 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3055 prog_title_length - 1;
3056 short_event_descriptor->language_code_1 = 'e';
3057 short_event_descriptor->language_code_2 = 'n';
3058 short_event_descriptor->language_code_3 = 'g';
3059 short_event_descriptor->event_name_length = prog_title_length;
3060 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
3061 memcpy(event_name, prog_title.c_str(), prog_title_length);
3064 event_name[prog_title_length] = 0;
3066 if ( sumText.length() > 0 )
3067 // There is summary info
3069 unsigned int sum_length = sumText.length();
3070 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
3071 // Store summary in short event descriptor
3073 // Increase all relevant lengths
3074 event_name[prog_title_length] = sum_length;
3075 short_event_descriptor->descriptor_length += sum_length;
3076 packet_length += sum_length;
3077 descr_ll += sum_length;
3078 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
3081 // Store summary in extended event descriptors
3083 int remaining_sum_length = sumText.length();
3084 int nbr_descr = int(remaining_sum_length/247) + 1;
3085 for ( int i=0; i < nbr_descr; i++)
3086 // Loop once per extended event descriptor
3088 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
3089 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
3090 remaining_sum_length -= sum_length;
3091 packet_length += 8 + sum_length;
3092 descr_ll += 8 + sum_length;
3094 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
3095 ext_event_descriptor->descriptor_length = sum_length + 6;
3096 ext_event_descriptor->descriptor_number = i;
3097 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
3098 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
3099 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
3100 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
3101 u_char *the_text = (u_char *) ext_event_descriptor + 8;
3103 the_text[-1] = sum_length;
3104 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
3111 // Add content descriptor
3112 u_char *descriptor = (u_char *) data + packet_length;
3117 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
3118 if ( content_descr.find( "FILM" ) != std::string::npos )
3120 else if ( content_descr.find( "SPORT" ) != std::string::npos )
3123 descriptor[0] = 0x54;
3125 descriptor[2] = content_id;
3129 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
3130 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
3132 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
3133 packet->section_length_lo = (packet_length - 3)&0xff;
3135 // Feed the data to eEPGCache::sectionRead()
3136 cache->sectionRead( data, MHW, this );
3139 void eEPGCache::channel_data::startTimeout(int msec)
3141 m_MHWTimeoutTimer->start(msec,true);
3142 m_MHWTimeoutet=false;
3145 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
3147 m_MHWFilterMask.pid = pid;
3148 m_MHWFilterMask.data[0] = tid;
3149 m_MHWReader->start(m_MHWFilterMask);
3150 // eDebug("start 0x%02x 0x%02x", pid, tid);
3153 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
3155 m_MHWFilterMask2.pid = pid;
3156 m_MHWFilterMask2.data[0] = tid;
3159 m_MHWFilterMask2.data[1] = ext;
3160 m_MHWFilterMask2.mask[1] = 0xFF;
3161 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
3165 m_MHWFilterMask2.data[1] = 0;
3166 m_MHWFilterMask2.mask[1] = 0;
3167 // eDebug("start 0x%02x 0x%02x", pid, tid);
3169 m_MHWReader2->start(m_MHWFilterMask2);
3172 void eEPGCache::channel_data::readMHWData(const __u8 *data)
3175 m_MHWReader2->stop();
3177 if ( state > 1 || // aborted
3178 // have si data.. so we dont read mhw data
3179 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3181 eDebug("[EPGC] mhw aborted %d", state);
3183 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
3186 int len = ((data[1]&0xf)<<8) + data[2] - 1;
3187 int record_size = sizeof( mhw_channel_name_t );
3188 int nbr_records = int (len/record_size);
3190 m_channels.resize(nbr_records);
3191 for ( int i = 0; i < nbr_records; i++ )
3193 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
3194 m_channels[i]=*channel;
3198 eDebug("[EPGC] mhw %d channels found", m_channels.size());
3200 // Channels table has been read, start reading the themes table.
3201 startMHWReader(0xD3, 0x92);
3204 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
3207 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3208 int record_size = sizeof( mhw_theme_name_t );
3209 int nbr_records = int (len/record_size);
3211 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
3214 for ( int i = 0; i < nbr_records; i++ )
3216 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
3217 if ( i >= next_idx )
3221 next_idx = (__u8) *(data + 3 + idx_ptr);
3227 m_themes[idx+sub_idx] = *theme;
3229 eDebug("[EPGC] mhw %d themes found", m_themes.size());
3230 // Themes table has been read, start reading the titles table.
3231 startMHWReader(0xD2, 0x90);
3235 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3238 mhw_title_t *title = (mhw_title_t*) data;
3240 if ( title->channel_id == 0xFF ) // Separator
3241 return; // Continue reading of the current table.
3244 // Create unique key per title
3245 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
3246 (title->ms.minutes);
3247 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
3248 ((title->program_id_ml)<<8)|(title->program_id_lo);
3250 if ( m_titles.find( title_id ) == m_titles.end() )
3253 title->mhw2_mjd_hi = 0;
3254 title->mhw2_mjd_lo = 0;
3255 title->mhw2_duration_hi = 0;
3256 title->mhw2_duration_lo = 0;
3257 m_titles[ title_id ] = *title;
3258 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3259 // program_ids will be used to gather summaries.
3260 m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3261 return; // Continue reading of the current table.
3263 else if (!checkTimeout())
3266 if ( !m_program_ids.empty())
3268 // Titles table has been read, there are summaries to read.
3269 // Start reading summaries, store corresponding titles on the fly.
3270 startMHWReader(0xD3, 0x90);
3271 eDebug("[EPGC] mhw %d titles(%d with summary) found",
3273 m_program_ids.size());
3278 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3281 mhw_summary_t *summary = (mhw_summary_t*) data;
3283 // Create unique key per record
3284 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3285 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3286 int len = ((data[1]&0xf)<<8) + data[2];
3288 // ugly workaround to convert const __u8* to char*
3290 memcpy(&tmp, &data, sizeof(void*));
3291 tmp[len+3] = 0; // Terminate as a string.
3293 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3294 if ( itProgid == m_program_ids.end() )
3295 { /* This part is to prevent to looping forever if some summaries are not received yet.
3296 There is a timeout of 4 sec. after the last successfully read summary. */
3297 if (!m_program_ids.empty() && !checkTimeout())
3298 return; // Continue reading of the current table.
3302 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3305 while((pos = the_text.find("\r\n")) != std::string::npos)
3306 the_text.replace(pos, 2, " ");
3308 // Find corresponding title, store title and summary in epgcache.
3309 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3310 if ( itTitle != m_titles.end() )
3313 storeTitle( itTitle, the_text, data );
3314 m_titles.erase( itTitle );
3316 m_program_ids.erase( itProgid );
3317 if ( !m_program_ids.empty() )
3318 return; // Continue reading of the current table.
3321 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3323 m_program_ids.size());
3324 // Summaries have been read, titles that have summaries have been stored.
3325 // Now store titles that do not have summaries.
3326 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3327 storeTitle( itTitle, "", data );
3331 m_MHWReader->stop();
3336 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3338 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3341 m_MHWReader->stop();
3343 if ( state > 1 || // aborted
3344 // have si data.. so we dont read mhw data
3345 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3347 eDebug("[EPGC] mhw2 aborted %d", state);
3349 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3352 int num_channels = data[120];
3353 m_channels.resize(num_channels);
3356 int ptr = 121 + 8 * num_channels;
3359 for( int chid = 0; chid < num_channels; ++chid )
3361 ptr += ( data[ptr] & 0x0f ) + 1;
3371 // data seems consistent...
3372 const __u8 *tmp = data+121;
3373 for (int i=0; i < num_channels; ++i)
3375 mhw_channel_name_t channel;
3376 channel.network_id_hi = *(tmp++);
3377 channel.network_id_lo = *(tmp++);
3378 channel.transport_stream_id_hi = *(tmp++);
3379 channel.transport_stream_id_lo = *(tmp++);
3380 channel.channel_id_hi = *(tmp++);
3381 channel.channel_id_lo = *(tmp++);
3382 m_channels[i]=channel;
3383 // eDebug("%d(%02x) %04x: %02x %02x", i, i, (channel.channel_id_hi << 8) | channel.channel_id_lo, *tmp, *(tmp+1));
3386 for (int i=0; i < num_channels; ++i)
3388 mhw_channel_name_t &channel = m_channels[i];
3389 int channel_name_len=*(tmp++)&0x0f;
3391 for (; x < channel_name_len; ++x)
3392 channel.name[x]=*(tmp++);
3393 channel.name[x+1]=0;
3394 // eDebug("%d(%02x) %s", i, i, channel.name);
3397 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3399 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3402 eDebug("[EPGC] mhw2 themes nyi");
3404 else if (m_MHWFilterMask2.pid == m_mhw2_title_pid && m_MHWFilterMask2.data[0] == 0xe6)
3411 // eDebug("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
3412 // data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10],
3413 // data[11], data[12], data[13], data[14], data[15], data[16], data[17] );
3415 while( pos < dataLen && !valid)
3418 pos += (data[pos] & 0x3F) + 4;
3419 if( pos == dataLen )
3426 eDebug("mhw2 title table invalid!!");
3429 if (!m_MHWTimeoutTimer->isActive())
3431 return; // continue reading
3434 // data seems consistent...
3437 while (pos < dataLen)
3439 // eDebugNoNewLine(" [%02x] %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x [%02x %02x %02x %02x %02x %02x %02x] LL - DESCR - ",
3440 // data[pos], data[pos+1], data[pos+2], data[pos+3], data[pos+4], data[pos+5], data[pos+6], data[pos+7],
3441 // 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]);
3442 title.channel_id = data[pos]+1;
3443 title.mhw2_mjd_hi = data[pos+11];
3444 title.mhw2_mjd_lo = data[pos+12];
3445 title.mhw2_hours = data[pos+13];
3446 title.mhw2_minutes = data[pos+14];
3447 title.mhw2_seconds = data[pos+15];
3448 int duration = ((data[pos+16] << 8)|data[pos+17]) >> 4;
3449 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3450 title.mhw2_duration_lo = duration&0xFF;
3452 // Create unique key per title
3453 __u32 title_id = (data[pos+7] << 24) | (data[pos+8] << 16) | (data[pos+9] << 8) | data[pos+10];
3455 __u8 slen = data[pos+18] & 0x3f;
3456 __u8 *dest = ((__u8*)title.title)-4;
3457 memcpy(dest, &data[pos+19], slen>35 ? 35 : slen);
3458 memset(dest+slen, 0, 35-slen);
3460 // eDebug("%02x [%02x %02x]: %s", data[pos], data[pos+1], data[pos+2], dest);
3462 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3463 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3465 // if (title.channel_id > m_channels.size())
3466 // eDebug("channel_id(%d %02x) to big!!", title.channel_id);
3468 // eDebug("pos %d prog_id %02x %02x chid %02x summary_id %04x dest %p len %d\n",
3469 // pos, title.program_id_ml, title.program_id_lo, title.channel_id, summary_id, dest, slen);
3471 // eDebug("title_id %08x -> summary_id %04x\n", title_id, summary_id);
3475 std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3476 if ( it == m_titles.end() )
3479 m_titles[ title_id ] = title;
3480 if (summary_id != 0xFFFF)
3483 std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3484 while (it != m_program_ids.end() && it->first == summary_id)
3486 if (it->second == title_id) {
3493 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3498 if ( !checkTimeout() )
3499 continue; // Continue reading of the current table.
3507 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3508 if (!m_program_ids.empty())
3510 // Titles table has been read, there are summaries to read.
3511 // Start reading summaries, store corresponding titles on the fly.
3512 startMHWReader2(m_mhw2_summary_pid, 0x96);
3513 startTimeout(15000);
3520 else if (m_MHWFilterMask2.pid == m_mhw2_summary_pid && m_MHWFilterMask2.data[0] == 0x96)
3523 if (!checkTimeout())
3525 int len, loop, pos, lenline;
3534 loop = data[pos] & 0x0f;
3539 for( ; loop > 0; --loop )
3541 if( dataLen > (pos+len) )
3543 lenline = data[pos+len];
3553 return; // continue reading
3557 // data seems consistent...
3558 __u32 summary_id = (data[3]<<8)|data[4];
3559 // eDebug ("summary id %04x\n", summary_id);
3560 // 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] );
3562 // ugly workaround to convert const __u8* to char*
3564 memcpy(&tmp, &data, sizeof(void*));
3569 loop = tmp[pos] & 0x0f;
3571 for( ; loop > 0; loop -- )
3573 lenline = tmp[pos+len];
3582 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3583 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3584 { /* This part is to prevent to looping forever if some summaries are not received yet.
3585 There is a timeout of 4 sec. after the last successfully read summary. */
3586 if ( !m_program_ids.empty() )
3587 return; // Continue reading of the current table.
3591 startTimeout(15000);
3592 std::string the_text = (char *) (data + pos + 1);
3594 // eDebug ("summary id %04x : %s\n", summary_id, data+pos+1);
3596 while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3599 // Find corresponding title, store title and summary in epgcache.
3600 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3601 if ( itTitle != m_titles.end() )
3603 storeTitle( itTitle, the_text, data );
3604 m_titles.erase( itTitle );
3606 m_program_ids.erase( itProgId++ );
3608 if ( !m_program_ids.empty() )
3609 return; // Continue reading of the current table.
3613 return; // continue reading
3616 if (isRunning & eEPGCache::MHW)
3618 if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3620 // Channels table has been read, start reading the themes table.
3621 startMHWReader2(m_mhw2_channel_pid, 0xC8, 1);
3624 else if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3626 // Themes table has been read, start reading the titles table.
3627 startMHWReader2(m_mhw2_title_pid, 0xe6);
3632 // Summaries have been read, titles that have summaries have been stored.
3633 // Now store titles that do not have summaries.
3634 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3635 storeTitle( itTitle, "", data );
3636 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3638 m_program_ids.size());
3645 m_MHWReader2->stop();