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->second));
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
374 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
376 channelMapIterator it =
377 m_knownChannels.find(chan);
378 if ( it != m_knownChannels.end() )
381 chan->getState(state);
382 if ( it->second->prevChannelState != state )
386 case iDVBChannel::state_ok:
388 eDebug("[eEPGCache] channel %p running", chan);
389 DVBChannelRunning(chan);
392 case iDVBChannel::state_release:
394 eDebug("[eEPGCache] remove channel %p", chan);
395 if (it->second->state >= 0)
396 messages.send(Message(Message::leaveChannel, chan));
397 pthread_mutex_lock(&it->second->channel_active);
398 singleLock s(channel_map_lock);
399 m_knownChannels.erase(it);
400 pthread_mutex_unlock(&it->second->channel_active);
403 // -> gotMessage -> abortEPG
406 default: // ignore all other events
410 it->second->prevChannelState = state;
415 bool eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
418 timeMap::iterator tmp = tm_it;
419 while ((tmp->first+tmp->second->getDuration()-300) > TM)
422 #ifdef ENABLE_PRIVATE_EPG
423 && tmp->second->type != PRIVATE
426 && tmp->second->type != MHW
430 __u16 event_id = tmp->second->getEventID();
431 servicemap.first.erase(event_id);
433 Event evt((uint8_t*)tmp->second->get());
435 event.parseFrom(&evt, service.sid<<16|service.onid);
436 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
437 service.sid, event_id,
438 event.getBeginTimeString().c_str(),
439 event.getEventName().c_str(),
440 event.getExtendedDescription().c_str());
443 if (tmp == servicemap.second.begin())
445 servicemap.second.erase(tmp);
449 servicemap.second.erase(tmp--);
454 if (tmp == servicemap.second.begin())
461 while(tmp->first < (TM+duration-300))
463 if (tmp->first != TM && tmp->second->type != PRIVATE)
465 __u16 event_id = tmp->second->getEventID();
466 servicemap.first.erase(event_id);
468 Event evt((uint8_t*)tmp->second->get());
470 event.parseFrom(&evt, service.sid<<16|service.onid);
471 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
472 service.sid, event_id,
473 event.getBeginTimeString().c_str(),
474 event.getEventName().c_str(),
475 event.getExtendedDescription().c_str());
478 servicemap.second.erase(tmp++);
483 if (tmp == servicemap.second.end())
489 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
491 eit_t *eit = (eit_t*) data;
493 int len=HILO(eit->section_length)-1;//+3-4;
498 // This fixed the EPG on the Multichoice irdeto systems
499 // the EIT packet is non-compliant.. their EIT packet stinks
500 if ( data[ptr-1] < 0x40 )
503 // Cablecom HACK .. tsid / onid in eit data are incorrect.. so we use
504 // it from running channel (just for current transport stream eit data)
505 bool use_transponder_chid = source == SCHEDULE || (source == NOWNEXT && data[0] == 0x4E);
506 eDVBChannelID chid = channel->channel->getChannelID();
507 uniqueEPGKey service( HILO(eit->service_id),
508 use_transponder_chid ? chid.original_network_id.get() : HILO(eit->original_network_id),
509 use_transponder_chid ? chid.transport_stream_id.get() : HILO(eit->transport_stream_id));
511 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
515 time_t TM = parseDVBtime(
516 eit_event->start_time_1,
517 eit_event->start_time_2,
518 eit_event->start_time_3,
519 eit_event->start_time_4,
520 eit_event->start_time_5);
521 time_t now = ::time(0);
523 if ( TM != 3599 && TM > -1)
524 channel->haveData |= source;
526 singleLock s(cache_lock);
527 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
528 // oder eine durch [] erzeugte
529 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
530 eventMap::iterator prevEventIt = servicemap.first.end();
531 timeMap::iterator prevTimeIt = servicemap.second.end();
536 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
538 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
540 eit_event->start_time_1,
541 eit_event->start_time_2,
542 eit_event->start_time_3,
543 eit_event->start_time_4,
544 eit_event->start_time_5,
550 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
553 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
555 __u16 event_id = HILO(eit_event->event_id);
557 int ev_erase_count = 0;
558 int tm_erase_count = 0;
561 // hack for some polsat services on 13.0E..... but this also replaces other valid event_ids with value 0..
562 // but we dont care about it...
563 event_id = event_hash;
564 eit_event->event_id_hi = event_hash >> 8;
565 eit_event->event_id_lo = event_hash & 0xFF;
568 // search in eventmap
569 eventMap::iterator ev_it =
570 servicemap.first.find(event_id);
572 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
574 // entry with this event_id is already exist ?
575 if ( ev_it != servicemap.first.end() )
577 if ( source > ev_it->second->type ) // update needed ?
578 goto next; // when not.. then skip this entry
580 // search this event in timemap
581 timeMap::iterator tm_it_tmp =
582 servicemap.second.find(ev_it->second->getStartTime());
584 if ( tm_it_tmp != servicemap.second.end() )
586 if ( tm_it_tmp->first == TM ) // just update eventdata
589 eventData *tmp = ev_it->second;
590 ev_it->second = tm_it_tmp->second =
591 new eventData(eit_event, eit_event_size, source);
592 if (FixOverlapping(servicemap, TM, duration, tm_it_tmp, service))
594 prevEventIt = servicemap.first.end();
595 prevTimeIt = servicemap.second.end();
600 else // event has new event begin time
603 // delete the found record from timemap
604 servicemap.second.erase(tm_it_tmp);
605 prevTimeIt=servicemap.second.end();
610 // search in timemap, for check of a case if new time has coincided with time of other event
611 // or event was is not found in eventmap
612 timeMap::iterator tm_it =
613 servicemap.second.find(TM);
615 if ( tm_it != servicemap.second.end() )
617 // event with same start time but another event_id...
618 if ( source > tm_it->second->type &&
619 ev_it == servicemap.first.end() )
620 goto next; // when not.. then skip this entry
622 // search this time in eventmap
623 eventMap::iterator ev_it_tmp =
624 servicemap.first.find(tm_it->second->getEventID());
626 if ( ev_it_tmp != servicemap.first.end() )
629 // delete the found record from eventmap
630 servicemap.first.erase(ev_it_tmp);
631 prevEventIt=servicemap.first.end();
634 evt = new eventData(eit_event, eit_event_size, source);
636 bool consistencyCheck=true;
638 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
641 delete ev_it->second;
642 delete tm_it->second;
646 else if (ev_erase_count == 0 && tm_erase_count > 0)
649 delete ev_it->second;
650 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
653 else if (ev_erase_count > 0 && tm_erase_count == 0)
656 delete tm_it->second;
657 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
660 else // added new eventData
663 consistencyCheck=false;
665 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
666 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
670 if ( consistencyCheck )
672 if ( tm_it->second != evt || ev_it->second != evt )
673 eFatal("tm_it->second != ev_it->second");
674 else if ( tm_it->second->getStartTime() != tm_it->first )
675 eFatal("event start_time(%d) non equal timemap key(%d)",
676 tm_it->second->getStartTime(), tm_it->first );
677 else if ( tm_it->first != TM )
678 eFatal("timemap key(%d) non equal TM(%d)",
680 else if ( ev_it->second->getEventID() != ev_it->first )
681 eFatal("event_id (%d) non equal event_map key(%d)",
682 ev_it->second->getEventID(), ev_it->first);
683 else if ( ev_it->first != event_id )
684 eFatal("eventmap key(%d) non equal event_id(%d)",
685 ev_it->first, event_id );
688 if (FixOverlapping(servicemap, TM, duration, tm_it, service))
690 prevEventIt = servicemap.first.end();
691 prevTimeIt = servicemap.second.end();
696 if ( servicemap.first.size() != servicemap.second.size() )
698 FILE *f = fopen("/hdd/event_map.txt", "w+");
700 for (eventMap::iterator it(servicemap.first.begin())
701 ; it != servicemap.first.end(); ++it )
702 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
703 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
705 f = fopen("/hdd/time_map.txt", "w+");
707 for (timeMap::iterator it(servicemap.second.begin())
708 ; it != servicemap.second.end(); ++it )
709 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
710 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
713 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
714 service.sid, service.tsid, service.onid,
715 servicemap.first.size(), servicemap.second.size() );
718 ptr += eit_event_size;
719 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
723 void eEPGCache::flushEPG(const uniqueEPGKey & s)
725 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
726 singleLock l(cache_lock);
727 if (s) // clear only this service
729 eventCache::iterator it = eventDB.find(s);
730 if ( it != eventDB.end() )
732 eventMap &evMap = it->second.first;
733 timeMap &tmMap = it->second.second;
735 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
740 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
741 #ifdef ENABLE_PRIVATE_EPG
742 contentMaps::iterator it =
743 content_time_tables.find(s);
744 if ( it != content_time_tables.end() )
747 content_time_tables.erase(it);
752 else // clear complete EPG Cache
754 for (eventCache::iterator it(eventDB.begin());
755 it != eventDB.end(); ++it)
757 eventMap &evMap = it->second.first;
758 timeMap &tmMap = it->second.second;
759 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
765 #ifdef ENABLE_PRIVATE_EPG
766 content_time_tables.clear();
768 channelLastUpdated.clear();
769 singleLock m(channel_map_lock);
770 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
771 it->second->startEPG();
773 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
776 void eEPGCache::cleanLoop()
778 singleLock s(cache_lock);
779 if (!eventDB.empty())
781 eDebug("[EPGC] start cleanloop");
783 time_t now = ::time(0);
785 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
787 bool updated = false;
788 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
790 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
792 // remove entry from eventMap
793 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
794 if ( b != DBIt->second.first.end() )
796 // release Heap Memory for this entry (new ....)
797 // eDebug("[EPGC] delete old event (evmap)");
798 DBIt->second.first.erase(b);
801 // remove entry from timeMap
802 // eDebug("[EPGC] release heap mem");
804 DBIt->second.second.erase(It++);
805 // eDebug("[EPGC] delete old event (timeMap)");
811 #ifdef ENABLE_PRIVATE_EPG
814 contentMaps::iterator x =
815 content_time_tables.find( DBIt->first );
816 if ( x != content_time_tables.end() )
818 timeMap &tmMap = DBIt->second.second;
819 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
821 for ( contentTimeMap::iterator it(i->second.begin());
822 it != i->second.end(); )
824 if ( tmMap.find(it->second.first) == tmMap.end() )
825 i->second.erase(it++);
829 if ( i->second.size() )
832 x->second.erase(i++);
838 eDebug("[EPGC] stop cleanloop");
839 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
841 cleanTimer->start(CLEAN_INTERVAL,true);
844 eEPGCache::~eEPGCache()
846 messages.send(Message::quit);
847 kill(); // waiting for thread shutdown
848 singleLock s(cache_lock);
849 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
850 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
854 void eEPGCache::gotMessage( const Message &msg )
859 flushEPG(msg.service);
861 case Message::startChannel:
863 singleLock s(channel_map_lock);
864 channelMapIterator channel =
865 m_knownChannels.find(msg.channel);
866 if ( channel != m_knownChannels.end() )
867 channel->second->startChannel();
870 case Message::leaveChannel:
872 singleLock s(channel_map_lock);
873 channelMapIterator channel =
874 m_knownChannels.find(msg.channel);
875 if ( channel != m_knownChannels.end() )
876 channel->second->abortEPG();
882 #ifdef ENABLE_PRIVATE_EPG
883 case Message::got_private_pid:
885 singleLock s(channel_map_lock);
886 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
888 eDVBChannel *channel = (eDVBChannel*) it->first;
889 channel_data *data = it->second;
890 eDVBChannelID chid = channel->getChannelID();
891 if ( chid.transport_stream_id.get() == msg.service.tsid &&
892 chid.original_network_id.get() == msg.service.onid &&
893 data->m_PrivatePid == -1 )
895 data->m_PrevVersion = -1;
896 data->m_PrivatePid = msg.pid;
897 data->m_PrivateService = msg.service;
898 int onid = chid.original_network_id.get();
899 onid |= 0x80000000; // we use highest bit as private epg indicator
900 chid.original_network_id = onid;
901 updateMap::iterator It = channelLastUpdated.find( chid );
902 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
903 if (update < ZAP_DELAY)
905 data->startPrivateTimer->start(update, 1);
907 eDebug("[EPGC] next private update in %i min", update/60000);
908 else if (update >= 1000)
909 eDebug("[EPGC] next private update in %i sec", update/1000);
916 #ifdef ENABLE_MHW_EPG
917 case Message::got_mhw2_channel_pid:
919 singleLock s(channel_map_lock);
920 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
922 eDVBChannel *channel = (eDVBChannel*) it->first;
923 channel_data *data = it->second;
924 eDVBChannelID chid = channel->getChannelID();
925 if ( chid.transport_stream_id.get() == msg.service.tsid &&
926 chid.original_network_id.get() == msg.service.onid )
928 data->m_mhw2_channel_pid = msg.pid;
929 eDebug("[EPGC] got mhw2 channel pid %04x", msg.pid);
935 case Message::got_mhw2_title_pid:
937 singleLock s(channel_map_lock);
938 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
940 eDVBChannel *channel = (eDVBChannel*) it->first;
941 channel_data *data = it->second;
942 eDVBChannelID chid = channel->getChannelID();
943 if ( chid.transport_stream_id.get() == msg.service.tsid &&
944 chid.original_network_id.get() == msg.service.onid )
946 data->m_mhw2_title_pid = msg.pid;
947 eDebug("[EPGC] got mhw2 title pid %04x", msg.pid);
953 case Message::got_mhw2_summary_pid:
955 singleLock s(channel_map_lock);
956 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
958 eDVBChannel *channel = (eDVBChannel*) it->first;
959 channel_data *data = it->second;
960 eDVBChannelID chid = channel->getChannelID();
961 if ( chid.transport_stream_id.get() == msg.service.tsid &&
962 chid.original_network_id.get() == msg.service.onid )
964 data->m_mhw2_summary_pid = msg.pid;
965 eDebug("[EPGC] got mhw2 summary pid %04x", msg.pid);
972 case Message::timeChanged:
976 eDebug("unhandled EPGCache Message!!");
981 void eEPGCache::thread()
993 void eEPGCache::load()
995 FILE *f = fopen(m_filename, "r");
1003 unsigned int magic=0;
1004 fread( &magic, sizeof(int), 1, f);
1005 if (magic != 0x98765432)
1007 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
1012 fread( text1, 13, 1, f);
1013 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
1015 singleLock s(cache_lock);
1016 fread( &size, sizeof(int), 1, f);
1023 fread( &key, sizeof(uniqueEPGKey), 1, f);
1024 fread( &size, sizeof(int), 1, f);
1030 fread( &type, sizeof(__u8), 1, f);
1031 fread( &len, sizeof(__u8), 1, f);
1032 event = new eventData(0, len, type);
1033 event->EITdata = new __u8[len];
1034 eventData::CacheSize+=len;
1035 fread( event->EITdata, len, 1, f);
1036 evMap[ event->getEventID() ]=event;
1037 tmMap[ event->getStartTime() ]=event;
1040 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
1043 eDebug("[EPGC] %d events read from %s", cnt, m_filename);
1044 #ifdef ENABLE_PRIVATE_EPG
1046 fread( text2, 11, 1, f);
1047 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
1050 fread( &size, sizeof(int), 1, f);
1055 fread( &key, sizeof(uniqueEPGKey), 1, f);
1056 eventMap &evMap=eventDB[key].first;
1057 fread( &size, sizeof(int), 1, f);
1062 fread( &content_id, sizeof(int), 1, f);
1063 fread( &size, sizeof(int), 1, f);
1066 time_t time1, time2;
1068 fread( &time1, sizeof(time_t), 1, f);
1069 fread( &time2, sizeof(time_t), 1, f);
1070 fread( &event_id, sizeof(__u16), 1, f);
1071 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
1072 eventMap::iterator it =
1073 evMap.find(event_id);
1074 if (it != evMap.end())
1075 it->second->type = PRIVATE;
1080 #endif // ENABLE_PRIVATE_EPG
1083 eDebug("[EPGC] don't read old epg database");
1089 void eEPGCache::save()
1091 /* create empty file */
1092 FILE *f = fopen(m_filename, "w");
1096 eDebug("[EPGC] couldn't save epg data to '%s'(%m)", m_filename);
1100 char *buf = realpath(m_filename, NULL);
1103 eDebug("[EPGC] realpath to '%s' failed in save (%m)", m_filename);
1108 eDebug("[EPGC] store epg to realpath '%s'", buf);
1112 if (statfs(buf, &s) < 0) {
1113 eDebug("[EPGC] statfs '%s' failed in save (%m)", buf);
1120 // check for enough free space on storage
1123 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
1125 eDebug("[EPGC] not enough free space at path '%s' %lld bytes availd but %d needed", buf, tmp, (eventData::CacheSize*12)/10);
1131 unsigned int magic = 0x98765432;
1132 fwrite( &magic, sizeof(int), 1, f);
1133 const char *text = "UNFINISHED_V7";
1134 fwrite( text, 13, 1, f );
1135 int size = eventDB.size();
1136 fwrite( &size, sizeof(int), 1, f );
1137 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1139 timeMap &timemap = service_it->second.second;
1140 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1141 size = timemap.size();
1142 fwrite( &size, sizeof(int), 1, f);
1143 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1145 __u8 len = time_it->second->ByteSize;
1146 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1147 fwrite( &len, sizeof(__u8), 1, f);
1148 fwrite( time_it->second->EITdata, len, 1, f);
1152 eDebug("[EPGC] %d events written to %s", cnt, m_filename);
1154 #ifdef ENABLE_PRIVATE_EPG
1155 const char* text3 = "PRIVATE_EPG";
1156 fwrite( text3, 11, 1, f );
1157 size = content_time_tables.size();
1158 fwrite( &size, sizeof(int), 1, f);
1159 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1161 contentMap &content_time_table = a->second;
1162 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1163 int size = content_time_table.size();
1164 fwrite( &size, sizeof(int), 1, f);
1165 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1167 int size = i->second.size();
1168 fwrite( &i->first, sizeof(int), 1, f);
1169 fwrite( &size, sizeof(int), 1, f);
1170 for ( contentTimeMap::iterator it(i->second.begin());
1171 it != i->second.end(); ++it )
1173 fwrite( &it->first, sizeof(time_t), 1, f);
1174 fwrite( &it->second.first, sizeof(time_t), 1, f);
1175 fwrite( &it->second.second, sizeof(__u16), 1, f);
1180 // write version string after binary data
1181 // has been written to disk.
1183 fseek(f, sizeof(int), SEEK_SET);
1184 fwrite("ENIGMA_EPG_V7", 13, 1, f);
1188 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1190 ,abortTimer(eTimer::create(ml)), zapTimer(eTimer::create(ml)), state(-1)
1191 ,isRunning(0), haveData(0)
1192 #ifdef ENABLE_PRIVATE_EPG
1193 ,startPrivateTimer(eTimer::create(ml))
1195 #ifdef ENABLE_MHW_EPG
1196 ,m_MHWTimeoutTimer(eTimer::create(ml))
1199 #ifdef ENABLE_MHW_EPG
1200 CONNECT(m_MHWTimeoutTimer->timeout, eEPGCache::channel_data::MHWTimeout);
1202 CONNECT(zapTimer->timeout, eEPGCache::channel_data::startEPG);
1203 CONNECT(abortTimer->timeout, eEPGCache::channel_data::abortNonAvail);
1204 #ifdef ENABLE_PRIVATE_EPG
1205 CONNECT(startPrivateTimer->timeout, eEPGCache::channel_data::startPrivateReader);
1207 pthread_mutex_init(&channel_active, 0);
1210 bool eEPGCache::channel_data::finishEPG()
1212 if (!isRunning) // epg ready
1214 eDebug("[EPGC] stop caching events(%ld)", ::time(0));
1215 zapTimer->start(UPDATE_INTERVAL, 1);
1216 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1217 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1219 seenSections[i].clear();
1220 calcedSections[i].clear();
1222 singleLock l(cache->cache_lock);
1223 cache->channelLastUpdated[channel->getChannelID()] = ::time(0);
1224 #ifdef ENABLE_MHW_EPG
1232 void eEPGCache::channel_data::startEPG()
1234 eDebug("[EPGC] start caching events(%ld)", ::time(0));
1237 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1239 seenSections[i].clear();
1240 calcedSections[i].clear();
1243 eDVBSectionFilterMask mask;
1244 memset(&mask, 0, sizeof(mask));
1246 #ifdef ENABLE_MHW_EPG
1248 mask.data[0] = 0x91;
1249 mask.mask[0] = 0xFF;
1250 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1251 m_MHWReader->start(mask);
1253 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1255 mask.pid = m_mhw2_channel_pid;
1256 mask.data[0] = 0xC8;
1257 mask.mask[0] = 0xFF;
1259 mask.mask[1] = 0xFF;
1260 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1261 m_MHWReader2->start(mask);
1263 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1266 m_MHWTimeoutet=false;
1270 mask.flags = eDVBSectionFilterMask::rfCRC;
1272 mask.data[0] = 0x4E;
1273 mask.mask[0] = 0xFE;
1274 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1275 m_NowNextReader->start(mask);
1276 isRunning |= NOWNEXT;
1278 mask.data[0] = 0x50;
1279 mask.mask[0] = 0xF0;
1280 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1281 m_ScheduleReader->start(mask);
1282 isRunning |= SCHEDULE;
1284 mask.data[0] = 0x60;
1285 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1286 m_ScheduleOtherReader->start(mask);
1287 isRunning |= SCHEDULE_OTHER;
1291 mask.data[0] = 0x40;
1292 mask.mask[0] = 0x40;
1293 m_ViasatReader->connectRead(slot(*this, &eEPGCache::channel_data::readDataViasat), m_ViasatConn);
1294 m_ViasatReader->start(mask);
1295 isRunning |= VIASAT;
1297 abortTimer->start(7000,true);
1300 void eEPGCache::channel_data::abortNonAvail()
1304 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1306 eDebug("[EPGC] abort non avail nownext reading");
1307 isRunning &= ~NOWNEXT;
1308 m_NowNextReader->stop();
1311 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1313 eDebug("[EPGC] abort non avail schedule reading");
1314 isRunning &= ~SCHEDULE;
1315 m_ScheduleReader->stop();
1318 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1320 eDebug("[EPGC] abort non avail schedule other reading");
1321 isRunning &= ~SCHEDULE_OTHER;
1322 m_ScheduleOtherReader->stop();
1323 m_ScheduleOtherConn=0;
1325 if ( !(haveData&VIASAT) && (isRunning&VIASAT) )
1327 eDebug("[EPGC] abort non avail viasat reading");
1328 isRunning &= ~VIASAT;
1329 m_ViasatReader->stop();
1332 #ifdef ENABLE_MHW_EPG
1333 if ( !(haveData&MHW) && (isRunning&MHW) )
1335 eDebug("[EPGC] abort non avail mhw reading");
1337 m_MHWReader->stop();
1339 m_MHWReader2->stop();
1343 if ( isRunning & VIASAT )
1344 abortTimer->start(300000, true);
1345 else if ( isRunning )
1346 abortTimer->start(90000, true);
1350 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1352 seenSections[i].clear();
1353 calcedSections[i].clear();
1360 void eEPGCache::channel_data::startChannel()
1362 pthread_mutex_lock(&channel_active);
1363 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1365 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
1367 if (update < ZAP_DELAY)
1370 zapTimer->start(update, 1);
1371 if (update >= 60000)
1372 eDebug("[EPGC] next update in %i min", update/60000);
1373 else if (update >= 1000)
1374 eDebug("[EPGC] next update in %i sec", update/1000);
1377 void eEPGCache::channel_data::abortEPG()
1379 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1381 seenSections[i].clear();
1382 calcedSections[i].clear();
1388 eDebug("[EPGC] abort caching events !!");
1389 if (isRunning & SCHEDULE)
1391 isRunning &= ~SCHEDULE;
1392 m_ScheduleReader->stop();
1395 if (isRunning & NOWNEXT)
1397 isRunning &= ~NOWNEXT;
1398 m_NowNextReader->stop();
1401 if (isRunning & SCHEDULE_OTHER)
1403 isRunning &= ~SCHEDULE_OTHER;
1404 m_ScheduleOtherReader->stop();
1405 m_ScheduleOtherConn=0;
1407 if (isRunning & VIASAT)
1409 isRunning &= ~VIASAT;
1410 m_ViasatReader->stop();
1413 #ifdef ENABLE_MHW_EPG
1414 if (isRunning & MHW)
1417 m_MHWReader->stop();
1419 m_MHWReader2->stop();
1424 #ifdef ENABLE_PRIVATE_EPG
1425 if (m_PrivateReader)
1426 m_PrivateReader->stop();
1430 pthread_mutex_unlock(&channel_active);
1434 void eEPGCache::channel_data::readDataViasat( const __u8 *data)
1437 memcpy(&d, &data, sizeof(__u8*));
1442 void eEPGCache::channel_data::readData( const __u8 *data)
1446 iDVBSectionReader *reader=NULL;
1450 reader=m_NowNextReader;
1455 reader=m_ScheduleReader;
1460 reader=m_ScheduleOtherReader;
1461 source=SCHEDULE_OTHER;
1466 reader=m_ViasatReader;
1471 eDebug("[EPGC] unknown table_id !!!");
1474 tidMap &seenSections = this->seenSections[map];
1475 tidMap &calcedSections = this->calcedSections[map];
1476 if ( (state == 1 && calcedSections == seenSections) || state > 1 )
1478 eDebugNoNewLine("[EPGC] ");
1483 eDebugNoNewLine("nownext");
1487 eDebugNoNewLine("schedule");
1489 case SCHEDULE_OTHER:
1490 m_ScheduleOtherConn=0;
1491 eDebugNoNewLine("schedule other");
1495 eDebugNoNewLine("viasat");
1497 default: eDebugNoNewLine("unknown");break;
1499 eDebug(" finished(%ld)", ::time(0));
1502 isRunning &= ~source;
1508 eit_t *eit = (eit_t*) data;
1509 __u32 sectionNo = data[0] << 24;
1510 sectionNo |= data[3] << 16;
1511 sectionNo |= data[4] << 8;
1512 sectionNo |= eit->section_number;
1514 tidMap::iterator it =
1515 seenSections.find(sectionNo);
1517 if ( it == seenSections.end() )
1519 seenSections.insert(sectionNo);
1520 calcedSections.insert(sectionNo);
1521 __u32 tmpval = sectionNo & 0xFFFFFF00;
1522 __u8 incr = source == NOWNEXT ? 1 : 8;
1523 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1525 if ( i == eit->section_number )
1527 for (int x=i; x <= eit->segment_last_section_number; ++x)
1528 calcedSections.insert(tmpval|(x&0xFF));
1531 calcedSections.insert(tmpval|(i&0xFF));
1533 cache->sectionRead(data, source, this);
1538 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1539 // if t == -1 we search the current event...
1541 singleLock s(cache_lock);
1542 uniqueEPGKey key(handleGroup(service));
1544 // check if EPG for this service is ready...
1545 eventCache::iterator It = eventDB.find( key );
1546 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1550 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1551 It->second.second.upper_bound(t); // just >
1552 if ( i != It->second.second.end() )
1554 if ( direction < 0 || (direction == 0 && i->first > t) )
1556 timeMap::iterator x = i;
1558 if ( x != It->second.second.end() )
1560 time_t start_time = x->first;
1565 if (t > (start_time+x->second->getDuration()))
1580 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1582 singleLock s(cache_lock);
1583 const eventData *data=0;
1584 RESULT ret = lookupEventTime(service, t, data, direction);
1586 result = data->get();
1590 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1592 singleLock s(cache_lock);
1593 const eventData *data=0;
1594 RESULT ret = lookupEventTime(service, t, data, direction);
1596 result = new Event((uint8_t*)data->get());
1600 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1602 singleLock s(cache_lock);
1603 const eventData *data=0;
1604 RESULT ret = lookupEventTime(service, t, data, direction);
1607 Event ev((uint8_t*)data->get());
1608 result = new eServiceEvent();
1609 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1610 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1615 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1617 singleLock s(cache_lock);
1618 uniqueEPGKey key(handleGroup(service));
1620 eventCache::iterator It = eventDB.find( key );
1621 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1623 eventMap::iterator i( It->second.first.find( event_id ));
1624 if ( i != It->second.first.end() )
1632 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1638 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1640 singleLock s(cache_lock);
1641 const eventData *data=0;
1642 RESULT ret = lookupEventId(service, event_id, data);
1644 result = data->get();
1648 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1650 singleLock s(cache_lock);
1651 const eventData *data=0;
1652 RESULT ret = lookupEventId(service, event_id, data);
1654 result = new Event((uint8_t*)data->get());
1658 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1660 singleLock s(cache_lock);
1661 const eventData *data=0;
1662 RESULT ret = lookupEventId(service, event_id, data);
1665 Event ev((uint8_t*)data->get());
1666 result = new eServiceEvent();
1667 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1668 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1673 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1675 singleLock s(cache_lock);
1676 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1679 eventCache::iterator It = eventDB.find(ref);
1680 if ( It != eventDB.end() && It->second.second.size() )
1682 m_timemap_cursor = It->second.second.lower_bound(begin);
1683 if ( m_timemap_cursor != It->second.second.end() )
1685 if ( m_timemap_cursor->first != begin )
1687 timeMap::iterator x = m_timemap_cursor;
1689 if ( x != It->second.second.end() )
1691 time_t start_time = x->first;
1692 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1693 m_timemap_cursor = x;
1699 m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1701 m_timemap_end = It->second.second.end();
1703 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1704 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1709 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1711 if ( m_timemap_cursor != m_timemap_end )
1713 result = m_timemap_cursor++->second;
1719 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1721 if ( m_timemap_cursor != m_timemap_end )
1723 result = m_timemap_cursor++->second->get();
1729 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1731 if ( m_timemap_cursor != m_timemap_end )
1733 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1739 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1741 if ( m_timemap_cursor != m_timemap_end )
1743 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1744 result = new eServiceEvent();
1745 return result->parseFrom(&ev, currentQueryTsidOnid);
1750 void fillTuple(ePyObject tuple, const char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1755 while(spos < argcount)
1757 bool inc_refcount=false;
1758 switch((c=argstring[spos++]))
1760 case '0': // PyLong 0
1761 tmp = PyLong_FromLong(0);
1763 case 'I': // Event Id
1764 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1766 case 'B': // Event Begin Time
1767 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1769 case 'D': // Event Duration
1770 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1772 case 'T': // Event Title
1773 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1775 case 'S': // Event Short Description
1776 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1778 case 'E': // Event Extended Description
1779 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1781 case 'C': // Current Time
1783 inc_refcount = true;
1785 case 'R': // service reference string
1787 inc_refcount = true;
1789 case 'n': // short service name
1790 case 'N': // service name
1792 inc_refcount = true;
1797 default: // ignore unknown
1799 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1804 inc_refcount = true;
1808 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1812 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1816 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1817 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1821 Py_DECREF(service_name);
1824 Py_DECREF(convertFuncArgs);
1825 Py_DECREF(dest_list);
1826 PyErr_SetString(PyExc_StandardError,
1827 "error in convertFunc execute");
1828 eDebug("error in convertFunc execute");
1831 PyList_Append(dest_list, result);
1836 ePyObject tuple = PyTuple_New(argcount);
1837 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1838 PyList_Append(dest_list, tuple);
1844 // here we get a python list
1845 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1848 // B = Event Begin Time
1849 // D = Event Duration
1851 // S = Event Short Description
1852 // E = Event Extended Description
1854 // R = Service Reference
1856 // n = Short Service Name
1857 // X = Return a minimum of one tuple per service in the result list... even when no event was found.
1858 // The returned tuple is filled with all available infos... non avail is filled as None
1859 // The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1860 // then for each service follows a tuple
1861 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1862 // the second is the type of query
1864 // -1 = event before given start_time
1865 // 0 = event intersects given start_time
1866 // +1 = event after given start_time
1868 // when type is eventid it is the event_id
1869 // when type is time then it is the start_time ( -1 for now_time )
1870 // the fourth is the end_time .. ( optional .. for query all events in time range)
1872 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1874 ePyObject convertFuncArgs;
1876 const char *argstring=NULL;
1877 if (!PyList_Check(list))
1879 PyErr_SetString(PyExc_StandardError,
1885 int listSize=PyList_Size(list);
1888 PyErr_SetString(PyExc_StandardError,
1889 "not params given");
1890 eDebug("not params given");
1895 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1896 if (PyString_Check(argv))
1898 argstring = PyString_AS_STRING(argv);
1902 argstring = "I"; // just event id as default
1903 argcount = strlen(argstring);
1904 // eDebug("have %d args('%s')", argcount, argstring);
1907 bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1913 if (!PyCallable_Check(convertFunc))
1915 PyErr_SetString(PyExc_StandardError,
1916 "convertFunc must be callable");
1917 eDebug("convertFunc is not callable");
1920 convertFuncArgs = PyTuple_New(argcount);
1923 ePyObject nowTime = strchr(argstring, 'C') ?
1924 PyLong_FromLong(::time(0)) :
1927 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1930 ePyObject dest_list=PyList_New(0);
1931 while(listSize > listIt)
1933 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1934 if (PyTuple_Check(item))
1936 bool service_changed=false;
1941 int tupleSize=PyTuple_Size(item);
1944 while(tupleSize > tupleIt) // parse query args
1946 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1951 if (!PyString_Check(entry))
1953 eDebug("tuple entry 0 is no a string");
1960 type=PyInt_AsLong(entry);
1961 if (type < -1 || type > 2)
1963 eDebug("unknown type %d", type);
1968 event_id=stime=PyInt_AsLong(entry);
1971 minutes=PyInt_AsLong(entry);
1974 eDebug("unneeded extra argument");
1979 if (minutes && stime == -1)
1982 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1983 if (ref.type != eServiceReference::idDVB)
1985 eDebug("service reference for epg query is not valid");
1989 // redirect subservice querys to parent service
1990 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1991 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1993 eServiceCenterPtr service_center;
1994 if (!eServiceCenter::getPrivInstance(service_center))
1996 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1997 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1998 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1999 dvb_ref.setParentServiceID(eServiceID(0));
2001 service = PyString_FromString(dvb_ref.toString().c_str());
2002 service_changed = true;
2006 ePyObject service_name;
2007 if (must_get_service_name)
2009 ePtr<iStaticServiceInformation> sptr;
2010 eServiceCenterPtr service_center;
2011 eServiceCenter::getPrivInstance(service_center);
2014 service_center->info(ref, sptr);
2018 sptr->getName(ref, name);
2020 if (must_get_service_name == 1)
2023 // filter short name brakets
2024 while((pos = name.find("\xc2\x86")) != std::string::npos)
2026 while((pos = name.find("\xc2\x87")) != std::string::npos)
2030 name = buildShortName(name);
2033 service_name = PyString_FromString(name.c_str());
2037 service_name = PyString_FromString("<n/a>");
2041 singleLock s(cache_lock);
2042 if (!startTimeQuery(ref, stime, minutes))
2044 while ( m_timemap_cursor != m_timemap_end )
2046 Event ev((uint8_t*)m_timemap_cursor++->second->get());
2048 evt.parseFrom(&ev, currentQueryTsidOnid);
2049 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2053 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2059 const eventData *ev_data=0;
2062 singleLock s(cache_lock);
2064 lookupEventId(ref, event_id, ev_data);
2066 lookupEventTime(ref, stime, ev_data, type);
2069 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2070 Event ev((uint8_t*)ev_data->get());
2071 evt.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2076 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2079 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2082 if (service_changed)
2085 Py_DECREF(service_name);
2090 if (convertFuncArgs)
2091 Py_DECREF(convertFuncArgs);
2097 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2101 while(pos < argcount)
2103 bool inc_refcount=false;
2104 switch(argstring[pos])
2106 case '0': // PyLong 0
2107 tmp = PyLong_FromLong(0);
2109 case 'I': // Event Id
2110 tmp = PyLong_FromLong(evData->getEventID());
2112 case 'B': // Event Begin Time
2114 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2116 tmp = PyLong_FromLong(evData->getStartTime());
2118 case 'D': // Event Duration
2120 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2122 tmp = PyLong_FromLong(evData->getDuration());
2124 case 'T': // Event Title
2125 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2127 case 'S': // Event Short Description
2128 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2130 case 'E': // Event Extended Description
2131 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2133 case 'R': // service reference string
2134 tmp = service_reference;
2135 inc_refcount = true;
2137 case 'n': // short service name
2138 case 'N': // service name
2140 inc_refcount = true;
2142 default: // ignore unknown
2144 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2149 inc_refcount = true;
2153 PyTuple_SET_ITEM(tuple, pos++, tmp);
2157 // here we get a python tuple
2158 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2160 // B = Event Begin Time
2161 // D = Event Duration
2163 // S = Event Short Description
2164 // E = Event Extended Description
2165 // R = Service Reference
2167 // n = Short Service Name
2168 // the second tuple entry is the MAX matches value
2169 // the third tuple entry is the type of query
2170 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2171 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2172 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2173 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2174 // the fourth is the servicereference string
2175 // the fifth is the eventid
2176 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2177 // the fourth is the search text
2179 // 0 = case sensitive (CASE_CHECK)
2180 // 1 = case insensitive (NO_CASECHECK)
2182 PyObject *eEPGCache::search(ePyObject arg)
2188 const char *argstring=0;
2192 bool needServiceEvent=false;
2194 int must_get_service_name = 0;
2195 bool must_get_service_reference = false;
2197 if (PyTuple_Check(arg))
2199 int tuplesize=PyTuple_Size(arg);
2202 ePyObject obj = PyTuple_GET_ITEM(arg,0);
2203 if (PyString_Check(obj))
2205 #if PY_VERSION_HEX < 0x02060000
2206 argcount = PyString_GET_SIZE(obj);
2208 argcount = PyString_Size(obj);
2210 argstring = PyString_AS_STRING(obj);
2211 for (int i=0; i < argcount; ++i)
2212 switch(argstring[i])
2217 needServiceEvent=true;
2220 must_get_service_name = 1;
2223 must_get_service_name = 2;
2226 must_get_service_reference = true;
2234 PyErr_SetString(PyExc_StandardError,
2236 eDebug("tuple arg 0 is not a string");
2241 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2244 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2245 if (tuplesize > 4 && querytype == 0)
2247 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2248 if (PyString_Check(obj))
2250 refstr = PyString_AS_STRING(obj);
2251 eServiceReferenceDVB ref(refstr);
2254 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2255 singleLock s(cache_lock);
2256 const eventData *evData = 0;
2257 lookupEventId(ref, eventid, evData);
2260 __u8 *data = evData->EITdata;
2261 int tmp = evData->ByteSize-10;
2262 __u32 *p = (__u32*)(data+10);
2263 // search short and extended event descriptors
2267 descriptorMap::iterator it =
2268 eventData::descriptors.find(crc);
2269 if (it != eventData::descriptors.end())
2271 __u8 *descr_data = it->second.second;
2272 switch(descr_data[0])
2275 descr[++descridx]=crc;
2284 eDebug("event not found");
2288 PyErr_SetString(PyExc_StandardError, "type error");
2289 eDebug("tuple arg 4 is not a valid service reference string");
2295 PyErr_SetString(PyExc_StandardError, "type error");
2296 eDebug("tuple arg 4 is not a string");
2300 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2302 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2303 if (PyString_Check(obj))
2305 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2306 const char *str = PyString_AS_STRING(obj);
2307 #if PY_VERSION_HEX < 0x02060000
2308 int textlen = PyString_GET_SIZE(obj);
2310 int textlen = PyString_Size(obj);
2313 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2315 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2316 singleLock s(cache_lock);
2317 for (descriptorMap::iterator it(eventData::descriptors.begin());
2318 it != eventData::descriptors.end() && descridx < 511; ++it)
2320 __u8 *data = it->second.second;
2321 if ( data[0] == 0x4D ) // short event descriptor
2323 int title_len = data[5];
2324 if ( querytype == 1 )
2327 // skip DVB-Text Encoding!
2328 if (data[6] == 0x10)
2333 else if(data[6] > 0 && data[6] < 0x20)
2338 if (title_len != textlen)
2342 if ( !strncasecmp((const char*)data+offs, str, title_len) )
2344 // std::string s((const char*)data+offs, title_len);
2345 // eDebug("match1 %s %s", str, s.c_str() );
2346 descr[++descridx] = it->first;
2349 else if ( !strncmp((const char*)data+offs, str, title_len) )
2351 // std::string s((const char*)data+offs, title_len);
2352 // eDebug("match2 %s %s", str, s.c_str() );
2353 descr[++descridx] = it->first;
2359 while((title_len-idx) >= textlen)
2363 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2365 descr[++descridx] = it->first;
2366 // std::string s((const char*)data+6, title_len);
2367 // eDebug("match 3 %s %s", str, s.c_str() );
2371 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2373 descr[++descridx] = it->first;
2374 // std::string s((const char*)data+6, title_len);
2375 // eDebug("match 4 %s %s", str, s.c_str() );
2386 PyErr_SetString(PyExc_StandardError,
2388 eDebug("tuple arg 4 is not a string");
2394 PyErr_SetString(PyExc_StandardError,
2396 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2402 PyErr_SetString(PyExc_StandardError,
2404 eDebug("not enough args in tuple");
2410 PyErr_SetString(PyExc_StandardError,
2412 eDebug("arg 0 is not a tuple");
2418 int maxcount=maxmatches;
2419 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2420 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2421 // in this case we start searching with the base service
2422 bool first = ref.valid() ? true : false;
2423 singleLock s(cache_lock);
2424 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2425 while(cit != eventDB.end() && maxcount)
2427 if ( ref.valid() && !first && cit->first == ref )
2429 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2433 ePyObject service_name;
2434 ePyObject service_reference;
2435 timeMap &evmap = cit->second.second;
2437 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2439 int evid = evit->second->getEventID();
2440 if ( evid == eventid)
2442 __u8 *data = evit->second->EITdata;
2443 int tmp = evit->second->ByteSize-10;
2444 __u32 *p = (__u32*)(data+10);
2445 // check if any of our descriptor used by this event
2450 for ( int i=0; i <= descridx; ++i)
2452 if (descr[i] == crc32) // found...
2457 if ( (querytype == 0 && cnt == descridx) ||
2458 ((querytype == 1 || querytype == 2) && cnt != -1) )
2460 const uniqueEPGKey &service = cit->first;
2461 eServiceReference ref =
2462 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2465 // create servive event
2467 const eventData *ev_data=0;
2468 if (needServiceEvent)
2470 if (lookupEventId(ref, evid, ev_data))
2471 eDebug("event not found !!!!!!!!!!!");
2474 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2475 Event ev((uint8_t*)ev_data->get());
2476 ptr.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2479 // create service name
2480 if (must_get_service_name && !service_name)
2482 ePtr<iStaticServiceInformation> sptr;
2483 eServiceCenterPtr service_center;
2484 eServiceCenter::getPrivInstance(service_center);
2487 service_center->info(ref, sptr);
2491 sptr->getName(ref, name);
2493 if (must_get_service_name == 1)
2496 // filter short name brakets
2497 while((pos = name.find("\xc2\x86")) != std::string::npos)
2499 while((pos = name.find("\xc2\x87")) != std::string::npos)
2503 name = buildShortName(name);
2506 service_name = PyString_FromString(name.c_str());
2510 service_name = PyString_FromString("<n/a>");
2512 // create servicereference string
2513 if (must_get_service_reference && !service_reference)
2514 service_reference = PyString_FromString(ref.toString().c_str());
2517 ret = PyList_New(0);
2519 ePyObject tuple = PyTuple_New(argcount);
2521 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2522 PyList_Append(ret, tuple);
2529 Py_DECREF(service_name);
2530 if (service_reference)
2531 Py_DECREF(service_reference);
2534 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2536 cit=eventDB.begin();
2549 #ifdef ENABLE_PRIVATE_EPG
2550 #include <dvbsi++/descriptor_tag.h>
2551 #include <dvbsi++/unknown_descriptor.h>
2552 #include <dvbsi++/private_data_specifier_descriptor.h>
2554 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2556 ePtr<eTable<ProgramMapSection> > ptr;
2557 if (!pmthandler->getPMT(ptr) && ptr)
2559 std::vector<ProgramMapSection*>::const_iterator i;
2560 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2562 const ProgramMapSection &pmt = **i;
2564 ElementaryStreamInfoConstIterator es;
2565 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2568 switch ((*es)->getType())
2570 case 0xC1: // user private
2571 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2572 desc != (*es)->getDescriptors()->end(); ++desc)
2574 switch ((*desc)->getTag())
2576 case 0xC2: // user defined
2577 if ((*desc)->getLength() == 8)
2580 (*desc)->writeToBuffer(buffer);
2581 if (!strncmp((const char *)buffer+2, "EPGDATA", 7))
2583 eServiceReferenceDVB ref;
2584 if (!pmthandler->getServiceReference(ref))
2586 int pid = (*es)->getPid();
2587 messages.send(Message(Message::got_mhw2_channel_pid, ref, pid));
2590 else if(!strncmp((const char *)buffer+2, "FICHAS", 6))
2592 eServiceReferenceDVB ref;
2593 if (!pmthandler->getServiceReference(ref))
2595 int pid = (*es)->getPid();
2596 messages.send(Message(Message::got_mhw2_summary_pid, ref, pid));
2599 else if(!strncmp((const char *)buffer+2, "GENEROS", 7))
2601 eServiceReferenceDVB ref;
2602 if (!pmthandler->getServiceReference(ref))
2604 int pid = (*es)->getPid();
2605 messages.send(Message(Message::got_mhw2_title_pid, ref, pid));
2614 case 0x05: // private
2615 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2616 desc != (*es)->getDescriptors()->end(); ++desc)
2618 switch ((*desc)->getTag())
2620 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2621 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2626 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2627 int descr_len = descr->getLength();
2630 uint8_t data[descr_len+2];
2631 descr->writeToBuffer(data);
2632 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2646 eServiceReferenceDVB ref;
2647 if (!pmthandler->getServiceReference(ref))
2649 int pid = (*es)->getPid();
2650 messages.send(Message(Message::got_private_pid, ref, pid));
2658 eDebug("PMTready but no pmt!!");
2665 date_time( const date_time &a )
2667 memcpy(data, a.data, 5);
2670 date_time( const __u8 data[5])
2672 memcpy(this->data, data, 5);
2673 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2678 const __u8& operator[](int pos) const
2684 struct less_datetime
2686 bool operator()( const date_time &a, const date_time &b ) const
2688 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2692 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2694 contentMap &content_time_table = content_time_tables[current_service];
2695 singleLock s(cache_lock);
2696 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2697 eventMap &evMap = eventDB[current_service].first;
2698 timeMap &tmMap = eventDB[current_service].second;
2700 int content_id = data[ptr++] << 24;
2701 content_id |= data[ptr++] << 16;
2702 content_id |= data[ptr++] << 8;
2703 content_id |= data[ptr++];
2705 contentTimeMap &time_event_map =
2706 content_time_table[content_id];
2707 for ( contentTimeMap::iterator it( time_event_map.begin() );
2708 it != time_event_map.end(); ++it )
2710 eventMap::iterator evIt( evMap.find(it->second.second) );
2711 if ( evIt != evMap.end() )
2713 delete evIt->second;
2716 tmMap.erase(it->second.first);
2718 time_event_map.clear();
2721 memcpy(duration, data+ptr, 3);
2724 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2726 const __u8 *descriptors[65];
2727 const __u8 **pdescr = descriptors;
2729 int descriptors_length = (data[ptr++]&0x0F) << 8;
2730 descriptors_length |= data[ptr++];
2731 while ( descriptors_length > 1 )
2733 int descr_type = data[ptr];
2734 int descr_len = data[ptr+1];
2735 descriptors_length -= 2;
2736 if (descriptors_length >= descr_len)
2738 descriptors_length -= descr_len;
2739 if ( descr_type == 0xf2 && descr_len > 5)
2742 int tsid = data[ptr++] << 8;
2743 tsid |= data[ptr++];
2744 int onid = data[ptr++] << 8;
2745 onid |= data[ptr++];
2746 int sid = data[ptr++] << 8;
2749 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2752 switch( (tsid << 16) | sid )
2754 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2755 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2756 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2757 case 0x0300f5: sid = 0xdc; break;
2758 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2759 case 0x1100d3: sid = 0xe3; break;
2760 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2763 ////////////////////////////////////////////
2765 uniqueEPGKey service( sid, onid, tsid );
2767 while( descr_len > 2 )
2770 datetime[0] = data[ptr++];
2771 datetime[1] = data[ptr++];
2772 int tmp_len = data[ptr++];
2774 if (descr_len >= tmp_len)
2776 descr_len -= tmp_len;
2777 while( tmp_len > 2 )
2779 memcpy(datetime+2, data+ptr, 3);
2782 start_times[datetime].push_back(service);
2795 ASSERT(pdescr <= &descriptors[65]);
2797 eit_event_struct *ev_struct = (eit_event_struct*) event;
2798 ev_struct->running_status = 0;
2799 ev_struct->free_CA_mode = 1;
2800 memcpy(event+7, duration, 3);
2802 const __u8 **d=descriptors;
2803 while ( d < pdescr )
2805 memcpy(event+ptr, *d, ((*d)[1])+2);
2809 ASSERT(ptr <= 4098);
2810 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2812 time_t now = ::time(0);
2813 if ( (it->first.tm + duration_sec) < now )
2815 memcpy(event+2, it->first.data, 5);
2818 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2820 event[bptr++] = 0x4A;
2821 __u8 *len = event+(bptr++);
2822 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2823 event[bptr++] = (i->tsid & 0xFF);
2824 event[bptr++] = (i->onid & 0xFF00) >> 8;
2825 event[bptr++] = (i->onid & 0xFF);
2826 event[bptr++] = (i->sid & 0xFF00) >> 8;
2827 event[bptr++] = (i->sid & 0xFF);
2828 event[bptr++] = 0xB0;
2829 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2830 *len = ((event+bptr) - len)-1;
2832 int llen = bptr - 12;
2833 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2834 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2836 time_t stime = it->first.tm;
2837 while( tmMap.find(stime) != tmMap.end() )
2839 event[6] += (stime - it->first.tm);
2841 while( evMap.find(event_id) != evMap.end() )
2843 event[0] = (event_id & 0xFF00) >> 8;
2844 event[1] = (event_id & 0xFF);
2845 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2846 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2847 evMap[event_id] = d;
2849 ASSERT(bptr <= 4098);
2853 void eEPGCache::channel_data::startPrivateReader()
2855 eDVBSectionFilterMask mask;
2856 memset(&mask, 0, sizeof(mask));
2857 mask.pid = m_PrivatePid;
2858 mask.flags = eDVBSectionFilterMask::rfCRC;
2859 mask.data[0] = 0xA0;
2860 mask.mask[0] = 0xFF;
2861 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2862 if (m_PrevVersion != -1)
2864 mask.data[3] = m_PrevVersion << 1;
2865 mask.mask[3] = 0x3E;
2866 mask.mode[3] = 0x3E;
2868 seenPrivateSections.clear();
2870 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2871 m_PrivateReader->start(mask);
2874 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2876 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2878 cache->privateSectionRead(m_PrivateService, data);
2879 seenPrivateSections.insert(data[6]);
2881 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2883 eDebug("[EPGC] private finished");
2884 eDVBChannelID chid = channel->getChannelID();
2885 int tmp = chid.original_network_id.get();
2886 tmp |= 0x80000000; // we use highest bit as private epg indicator
2887 chid.original_network_id = tmp;
2888 cache->channelLastUpdated[chid] = ::time(0);
2889 m_PrevVersion = (data[5] & 0x3E) >> 1;
2890 startPrivateReader();
2894 #endif // ENABLE_PRIVATE_EPG
2896 #ifdef ENABLE_MHW_EPG
2897 void eEPGCache::channel_data::cleanup()
2902 m_program_ids.clear();
2905 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2907 // Names in mhw structs are not strings as they are not '\0' terminated.
2908 // This function converts the mhw name into a string.
2909 // Constraint: "length of out" = "length of in" + 1.
2911 for ( i=0; i < len_in; i++ )
2915 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2922 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2925 return_time[0] = toBCD( hours );
2926 return_time[1] = toBCD( minutes );
2930 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2932 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2935 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2936 // For date plus time of day
2938 char tz_saved[1024];
2939 // Remove offset in mhw time.
2940 __u8 local_hours = hours;
2943 else if ( hours >= 8 )
2946 // As far as we know all mhw time data is sent in central Europe time zone.
2947 // So, temporarily set timezone to western europe
2948 time_t dt = ::time(0);
2950 char *old_tz = getenv( "TZ" );
2952 strcpy(tz_saved, old_tz);
2953 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2957 localtime_r(&dt, &localnow);
2961 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2963 if (local_hours <= 5)
2966 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2967 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2970 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2972 if ( old_tz == NULL )
2975 setenv("TZ", tz_saved, 1);
2978 // Calculate MJD according to annex in ETSI EN 300 468
2980 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2982 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2983 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2985 return_time[0] = (mjd & 0xFF00)>>8;
2986 return_time[1] = mjd & 0xFF;
2988 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2991 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2992 // data is borrowed from calling proc to save memory space.
2996 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2997 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2998 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
3000 eit_t *packet = (eit_t *) data;
3001 packet->table_id = 0x50;
3002 packet->section_syntax_indicator = 1;
3004 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
3005 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
3006 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3007 packet->current_next_indicator = 0;
3008 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3009 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3010 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
3011 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
3012 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
3013 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
3014 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3015 packet->segment_last_table_id = 0x50;
3017 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
3018 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 35 : 23 );
3019 int prog_title_length = prog_title.length();
3021 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3022 prog_title_length + 1;
3024 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
3025 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
3026 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
3030 u_char *data = (u_char*) event_data;
3031 data[2] = itTitle->second.mhw2_mjd_hi;
3032 data[3] = itTitle->second.mhw2_mjd_lo;
3033 data[4] = itTitle->second.mhw2_hours;
3034 data[5] = itTitle->second.mhw2_minutes;
3035 data[6] = itTitle->second.mhw2_seconds;
3036 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
3040 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
3041 (u_char *) event_data + 2 );
3042 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
3045 event_data->running_status = 0;
3046 event_data->free_CA_mode = 0;
3047 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
3049 eit_short_event_descriptor_struct *short_event_descriptor =
3050 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
3051 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
3052 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3053 prog_title_length - 1;
3054 short_event_descriptor->language_code_1 = 'e';
3055 short_event_descriptor->language_code_2 = 'n';
3056 short_event_descriptor->language_code_3 = 'g';
3057 short_event_descriptor->event_name_length = prog_title_length;
3058 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
3059 memcpy(event_name, prog_title.c_str(), prog_title_length);
3062 event_name[prog_title_length] = 0;
3064 if ( sumText.length() > 0 )
3065 // There is summary info
3067 unsigned int sum_length = sumText.length();
3068 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
3069 // Store summary in short event descriptor
3071 // Increase all relevant lengths
3072 event_name[prog_title_length] = sum_length;
3073 short_event_descriptor->descriptor_length += sum_length;
3074 packet_length += sum_length;
3075 descr_ll += sum_length;
3076 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
3079 // Store summary in extended event descriptors
3081 int remaining_sum_length = sumText.length();
3082 int nbr_descr = int(remaining_sum_length/247) + 1;
3083 for ( int i=0; i < nbr_descr; i++)
3084 // Loop once per extended event descriptor
3086 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
3087 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
3088 remaining_sum_length -= sum_length;
3089 packet_length += 8 + sum_length;
3090 descr_ll += 8 + sum_length;
3092 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
3093 ext_event_descriptor->descriptor_length = sum_length + 6;
3094 ext_event_descriptor->descriptor_number = i;
3095 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
3096 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
3097 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
3098 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
3099 u_char *the_text = (u_char *) ext_event_descriptor + 8;
3101 the_text[-1] = sum_length;
3102 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
3109 // Add content descriptor
3110 u_char *descriptor = (u_char *) data + packet_length;
3115 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
3116 if ( content_descr.find( "FILM" ) != std::string::npos )
3118 else if ( content_descr.find( "SPORT" ) != std::string::npos )
3121 descriptor[0] = 0x54;
3123 descriptor[2] = content_id;
3127 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
3128 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
3130 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
3131 packet->section_length_lo = (packet_length - 3)&0xff;
3133 // Feed the data to eEPGCache::sectionRead()
3134 cache->sectionRead( data, MHW, this );
3137 void eEPGCache::channel_data::startTimeout(int msec)
3139 m_MHWTimeoutTimer->start(msec,true);
3140 m_MHWTimeoutet=false;
3143 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
3145 m_MHWFilterMask.pid = pid;
3146 m_MHWFilterMask.data[0] = tid;
3147 m_MHWReader->start(m_MHWFilterMask);
3148 // eDebug("start 0x%02x 0x%02x", pid, tid);
3151 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
3153 m_MHWFilterMask2.pid = pid;
3154 m_MHWFilterMask2.data[0] = tid;
3157 m_MHWFilterMask2.data[1] = ext;
3158 m_MHWFilterMask2.mask[1] = 0xFF;
3159 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
3163 m_MHWFilterMask2.data[1] = 0;
3164 m_MHWFilterMask2.mask[1] = 0;
3165 // eDebug("start 0x%02x 0x%02x", pid, tid);
3167 m_MHWReader2->start(m_MHWFilterMask2);
3170 void eEPGCache::channel_data::readMHWData(const __u8 *data)
3173 m_MHWReader2->stop();
3175 if ( state > 1 || // aborted
3176 // have si data.. so we dont read mhw data
3177 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3179 eDebug("[EPGC] mhw aborted %d", state);
3181 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
3184 int len = ((data[1]&0xf)<<8) + data[2] - 1;
3185 int record_size = sizeof( mhw_channel_name_t );
3186 int nbr_records = int (len/record_size);
3188 m_channels.resize(nbr_records);
3189 for ( int i = 0; i < nbr_records; i++ )
3191 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
3192 m_channels[i]=*channel;
3196 eDebug("[EPGC] mhw %d channels found", m_channels.size());
3198 // Channels table has been read, start reading the themes table.
3199 startMHWReader(0xD3, 0x92);
3202 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
3205 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3206 int record_size = sizeof( mhw_theme_name_t );
3207 int nbr_records = int (len/record_size);
3209 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
3212 for ( int i = 0; i < nbr_records; i++ )
3214 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
3215 if ( i >= next_idx )
3219 next_idx = (__u8) *(data + 3 + idx_ptr);
3225 m_themes[idx+sub_idx] = *theme;
3227 eDebug("[EPGC] mhw %d themes found", m_themes.size());
3228 // Themes table has been read, start reading the titles table.
3229 startMHWReader(0xD2, 0x90);
3233 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3236 mhw_title_t *title = (mhw_title_t*) data;
3238 if ( title->channel_id == 0xFF ) // Separator
3239 return; // Continue reading of the current table.
3242 // Create unique key per title
3243 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
3244 (title->ms.minutes);
3245 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
3246 ((title->program_id_ml)<<8)|(title->program_id_lo);
3248 if ( m_titles.find( title_id ) == m_titles.end() )
3251 title->mhw2_mjd_hi = 0;
3252 title->mhw2_mjd_lo = 0;
3253 title->mhw2_duration_hi = 0;
3254 title->mhw2_duration_lo = 0;
3255 m_titles[ title_id ] = *title;
3256 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3257 // program_ids will be used to gather summaries.
3258 m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3259 return; // Continue reading of the current table.
3261 else if (!checkTimeout())
3264 if ( !m_program_ids.empty())
3266 // Titles table has been read, there are summaries to read.
3267 // Start reading summaries, store corresponding titles on the fly.
3268 startMHWReader(0xD3, 0x90);
3269 eDebug("[EPGC] mhw %d titles(%d with summary) found",
3271 m_program_ids.size());
3276 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3279 mhw_summary_t *summary = (mhw_summary_t*) data;
3281 // Create unique key per record
3282 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3283 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3284 int len = ((data[1]&0xf)<<8) + data[2];
3286 // ugly workaround to convert const __u8* to char*
3288 memcpy(&tmp, &data, sizeof(void*));
3289 tmp[len+3] = 0; // Terminate as a string.
3291 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3292 if ( itProgid == m_program_ids.end() )
3293 { /* This part is to prevent to looping forever if some summaries are not received yet.
3294 There is a timeout of 4 sec. after the last successfully read summary. */
3295 if (!m_program_ids.empty() && !checkTimeout())
3296 return; // Continue reading of the current table.
3300 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3303 while((pos = the_text.find("\r\n")) != std::string::npos)
3304 the_text.replace(pos, 2, " ");
3306 // Find corresponding title, store title and summary in epgcache.
3307 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3308 if ( itTitle != m_titles.end() )
3311 storeTitle( itTitle, the_text, data );
3312 m_titles.erase( itTitle );
3314 m_program_ids.erase( itProgid );
3315 if ( !m_program_ids.empty() )
3316 return; // Continue reading of the current table.
3319 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3321 m_program_ids.size());
3322 // Summaries have been read, titles that have summaries have been stored.
3323 // Now store titles that do not have summaries.
3324 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3325 storeTitle( itTitle, "", data );
3329 m_MHWReader->stop();
3334 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3336 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3339 m_MHWReader->stop();
3341 if ( state > 1 || // aborted
3342 // have si data.. so we dont read mhw data
3343 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3345 eDebug("[EPGC] mhw2 aborted %d", state);
3347 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3350 int num_channels = data[120];
3351 m_channels.resize(num_channels);
3354 int ptr = 121 + 8 * num_channels;
3357 for( int chid = 0; chid < num_channels; ++chid )
3359 ptr += ( data[ptr] & 0x0f ) + 1;
3369 // data seems consistent...
3370 const __u8 *tmp = data+121;
3371 for (int i=0; i < num_channels; ++i)
3373 mhw_channel_name_t channel;
3374 channel.network_id_hi = *(tmp++);
3375 channel.network_id_lo = *(tmp++);
3376 channel.transport_stream_id_hi = *(tmp++);
3377 channel.transport_stream_id_lo = *(tmp++);
3378 channel.channel_id_hi = *(tmp++);
3379 channel.channel_id_lo = *(tmp++);
3380 m_channels[i]=channel;
3381 // eDebug("%d(%02x) %04x: %02x %02x", i, i, (channel.channel_id_hi << 8) | channel.channel_id_lo, *tmp, *(tmp+1));
3384 for (int i=0; i < num_channels; ++i)
3386 mhw_channel_name_t &channel = m_channels[i];
3387 int channel_name_len=*(tmp++)&0x0f;
3389 for (; x < channel_name_len; ++x)
3390 channel.name[x]=*(tmp++);
3391 channel.name[x+1]=0;
3392 // eDebug("%d(%02x) %s", i, i, channel.name);
3395 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3397 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3400 eDebug("[EPGC] mhw2 themes nyi");
3402 else if (m_MHWFilterMask2.pid == m_mhw2_title_pid && m_MHWFilterMask2.data[0] == 0xe6)
3409 // eDebug("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
3410 // data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10],
3411 // data[11], data[12], data[13], data[14], data[15], data[16], data[17] );
3413 while( pos < dataLen && !valid)
3416 pos += (data[pos] & 0x3F) + 4;
3417 if( pos == dataLen )
3424 eDebug("mhw2 title table invalid!!");
3427 if (!m_MHWTimeoutTimer->isActive())
3429 return; // continue reading
3432 // data seems consistent...
3435 while (pos < dataLen)
3437 // eDebugNoNewLine(" [%02x] %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x [%02x %02x %02x %02x %02x %02x %02x] LL - DESCR - ",
3438 // data[pos], data[pos+1], data[pos+2], data[pos+3], data[pos+4], data[pos+5], data[pos+6], data[pos+7],
3439 // 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]);
3440 title.channel_id = data[pos]+1;
3441 title.mhw2_mjd_hi = data[pos+11];
3442 title.mhw2_mjd_lo = data[pos+12];
3443 title.mhw2_hours = data[pos+13];
3444 title.mhw2_minutes = data[pos+14];
3445 title.mhw2_seconds = data[pos+15];
3446 int duration = ((data[pos+16] << 8)|data[pos+17]) >> 4;
3447 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3448 title.mhw2_duration_lo = duration&0xFF;
3450 // Create unique key per title
3451 __u32 title_id = (data[pos+7] << 24) | (data[pos+8] << 16) | (data[pos+9] << 8) | data[pos+10];
3453 __u8 slen = data[pos+18] & 0x3f;
3454 __u8 *dest = ((__u8*)title.title)-4;
3455 memcpy(dest, &data[pos+19], slen>35 ? 35 : slen);
3456 memset(dest+slen, 0, 35-slen);
3458 // eDebug("%02x [%02x %02x]: %s", data[pos], data[pos+1], data[pos+2], dest);
3460 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3461 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3463 // if (title.channel_id > m_channels.size())
3464 // eDebug("channel_id(%d %02x) to big!!", title.channel_id);
3466 // eDebug("pos %d prog_id %02x %02x chid %02x summary_id %04x dest %p len %d\n",
3467 // pos, title.program_id_ml, title.program_id_lo, title.channel_id, summary_id, dest, slen);
3469 // eDebug("title_id %08x -> summary_id %04x\n", title_id, summary_id);
3473 std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3474 if ( it == m_titles.end() )
3477 m_titles[ title_id ] = title;
3478 if (summary_id != 0xFFFF)
3481 std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3482 while (it != m_program_ids.end() && it->first == summary_id)
3484 if (it->second == title_id) {
3491 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3496 if ( !checkTimeout() )
3497 continue; // Continue reading of the current table.
3505 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3506 if (!m_program_ids.empty())
3508 // Titles table has been read, there are summaries to read.
3509 // Start reading summaries, store corresponding titles on the fly.
3510 startMHWReader2(m_mhw2_summary_pid, 0x96);
3511 startTimeout(15000);
3518 else if (m_MHWFilterMask2.pid == m_mhw2_summary_pid && m_MHWFilterMask2.data[0] == 0x96)
3521 if (!checkTimeout())
3523 int len, loop, pos, lenline;
3532 loop = data[pos] & 0x0f;
3537 for( ; loop > 0; --loop )
3539 if( dataLen > (pos+len) )
3541 lenline = data[pos+len];
3551 return; // continue reading
3555 // data seems consistent...
3556 __u32 summary_id = (data[3]<<8)|data[4];
3557 // eDebug ("summary id %04x\n", summary_id);
3558 // 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] );
3560 // ugly workaround to convert const __u8* to char*
3562 memcpy(&tmp, &data, sizeof(void*));
3567 loop = tmp[pos] & 0x0f;
3569 for( ; loop > 0; loop -- )
3571 lenline = tmp[pos+len];
3580 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3581 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3582 { /* This part is to prevent to looping forever if some summaries are not received yet.
3583 There is a timeout of 4 sec. after the last successfully read summary. */
3584 if ( !m_program_ids.empty() )
3585 return; // Continue reading of the current table.
3589 startTimeout(15000);
3590 std::string the_text = (char *) (data + pos + 1);
3592 // eDebug ("summary id %04x : %s\n", summary_id, data+pos+1);
3594 while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3597 // Find corresponding title, store title and summary in epgcache.
3598 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3599 if ( itTitle != m_titles.end() )
3601 storeTitle( itTitle, the_text, data );
3602 m_titles.erase( itTitle );
3604 m_program_ids.erase( itProgId++ );
3606 if ( !m_program_ids.empty() )
3607 return; // Continue reading of the current table.
3611 return; // continue reading
3614 if (isRunning & eEPGCache::MHW)
3616 if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3618 // Channels table has been read, start reading the themes table.
3619 startMHWReader2(m_mhw2_channel_pid, 0xC8, 1);
3622 else if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3624 // Themes table has been read, start reading the titles table.
3625 startMHWReader2(m_mhw2_title_pid, 0xe6);
3630 // Summaries have been read, titles that have summaries have been stored.
3631 // Now store titles that do not have summaries.
3632 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3633 storeTitle( itTitle, "", data );
3634 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3636 m_program_ids.size());
3643 m_MHWReader2->stop();