1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
7 #include <lib/service/event.h>
11 #include <unistd.h> // for usleep
12 #include <sys/vfs.h> // for statfs
13 // #include <libmd5sum.h>
14 #include <lib/base/eerror.h>
15 #include <lib/base/estring.h>
16 #include <lib/dvb/pmt.h>
17 #include <lib/dvb/db.h>
18 #include <lib/python/python.h>
19 #include <dvbsi++/descriptor_tag.h>
21 int eventData::CacheSize=0;
22 descriptorMap eventData::descriptors;
23 __u8 eventData::data[4108];
24 extern const uint32_t crc32_table[256];
26 const eServiceReference &handleGroup(const eServiceReference &ref)
28 if (ref.flags & eServiceReference::isGroup)
30 ePtr<eDVBResourceManager> res;
31 if (!eDVBResourceManager::getInstance(res))
33 ePtr<iDVBChannelList> db;
34 if (!res->getChannelList(db))
37 if (!db->getBouquet(ref, bouquet))
39 std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
40 if (it != bouquet->m_services.end())
49 eventData::eventData(const eit_event_struct* e, int size, int type)
50 :ByteSize(size&0xFF), type(type&0xFF)
58 __u8 *data = (__u8*)e;
64 __u8 *descr = data+ptr;
65 int descr_len = descr[1];
67 if (size >= descr_len)
71 case EXTENDED_EVENT_DESCRIPTOR:
72 case SHORT_EVENT_DESCRIPTOR:
73 case LINKAGE_DESCRIPTOR:
74 case COMPONENT_DESCRIPTOR:
78 while(cnt++ < descr_len)
79 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
81 descriptorMap::iterator it =
82 descriptors.find(crc);
83 if ( it == descriptors.end() )
86 __u8 *d = new __u8[descr_len];
87 memcpy(d, descr, descr_len);
88 descriptors[crc] = descriptorPair(1, d);
95 default: // do not cache all other descriptors
104 ASSERT(pdescr <= &descr[65]);
105 ByteSize = 10+((pdescr-descr)*4);
106 EITdata = new __u8[ByteSize];
108 memcpy(EITdata, (__u8*) e, 10);
109 memcpy(EITdata+10, descr, ByteSize-10);
112 const eit_event_struct* eventData::get() const
115 int tmp = ByteSize-10;
116 memcpy(data, EITdata, 10);
117 int descriptors_length=0;
118 __u32 *p = (__u32*)(EITdata+10);
121 descriptorMap::iterator it =
122 descriptors.find(*p++);
123 if ( it != descriptors.end() )
125 int b = it->second.second[1]+2;
126 memcpy(data+pos, it->second.second, b );
128 descriptors_length += b;
131 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(p-1));
135 data[10] = (descriptors_length >> 8) & 0x0F;
136 data[11] = descriptors_length & 0xFF;
137 return (eit_event_struct*)data;
140 eventData::~eventData()
144 CacheSize -= ByteSize;
145 __u32 *d = (__u32*)(EITdata+10);
149 descriptorMap::iterator it =
150 descriptors.find(*d++);
151 if ( it != descriptors.end() )
153 descriptorPair &p = it->second;
154 if (!--p.first) // no more used descriptor
156 CacheSize -= it->second.second[1];
157 delete [] it->second.second; // free descriptor memory
158 descriptors.erase(it); // remove entry from descriptor map
162 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(d-1));
169 void eventData::load(FILE *f)
175 fread(&size, sizeof(int), 1, f);
178 fread(&id, sizeof(__u32), 1, f);
179 fread(&p.first, sizeof(int), 1, f);
180 fread(header, 2, 1, f);
181 int bytes = header[1]+2;
182 p.second = new __u8[bytes];
183 p.second[0] = header[0];
184 p.second[1] = header[1];
185 fread(p.second+2, bytes-2, 1, f);
192 void eventData::save(FILE *f)
194 int size=descriptors.size();
195 descriptorMap::iterator it(descriptors.begin());
196 fwrite(&size, sizeof(int), 1, f);
199 fwrite(&it->first, sizeof(__u32), 1, f);
200 fwrite(&it->second.first, sizeof(int), 1, f);
201 fwrite(it->second.second, it->second.second[1]+2, 1, f);
207 eEPGCache* eEPGCache::instance;
208 pthread_mutex_t eEPGCache::cache_lock=
209 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
210 pthread_mutex_t eEPGCache::channel_map_lock=
211 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
213 DEFINE_REF(eEPGCache)
215 eEPGCache::eEPGCache()
216 :messages(this,1), cleanTimer(eTimer::create(this))//, paused(0)
218 eDebug("[EPGC] Initialized EPGCache");
220 CONNECT(messages.recv_msg, eEPGCache::gotMessage);
221 CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
222 CONNECT(cleanTimer->timeout, eEPGCache::cleanLoop);
224 ePtr<eDVBResourceManager> res_mgr;
225 eDVBResourceManager::getInstance(res_mgr);
227 eDebug("[eEPGCache] no resource manager !!!!!!!");
230 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
231 if (eDVBLocalTimeHandler::getInstance()->ready())
237 void eEPGCache::timeUpdated()
241 eDebug("[EPGC] time updated.. start EPG Mainloop");
244 messages.send(Message(Message::timeChanged));
247 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
251 // eDebug("[eEPGCache] add channel %p", chan);
252 channel_data *data = new channel_data(this);
253 data->channel = chan;
254 data->prevChannelState = -1;
255 #ifdef ENABLE_PRIVATE_EPG
256 data->m_PrivatePid = -1;
258 #ifdef ENABLE_MHW_EPG
259 data->m_mhw2_channel_pid = 0x231; // defaults for astra 19.2 D+
260 data->m_mhw2_title_pid = 0x234; // defaults for astra 19.2 D+
261 data->m_mhw2_summary_pid = 0x236; // defaults for astra 19.2 D+
263 singleLock s(channel_map_lock);
264 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
265 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
269 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
271 channelMapIterator it =
272 m_knownChannels.find(chan);
273 if ( it == m_knownChannels.end() )
274 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
277 channel_data &data = *it->second;
278 ePtr<eDVBResourceManager> res_mgr;
279 if ( eDVBResourceManager::getInstance( res_mgr ) )
280 eDebug("[eEPGCache] no res manager!!");
283 ePtr<iDVBDemux> demux;
284 if ( data.channel->getDemux(demux, 0) )
286 eDebug("[eEPGCache] no demux!!");
291 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
294 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
298 res = demux->createSectionReader( this, data.m_ScheduleReader );
301 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
305 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
308 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
312 res = demux->createSectionReader( this, data.m_ViasatReader );
315 eDebug("[eEPGCache] couldnt initialize viasat reader!!");
318 #ifdef ENABLE_PRIVATE_EPG
319 res = demux->createSectionReader( this, data.m_PrivateReader );
322 eDebug("[eEPGCache] couldnt initialize private reader!!");
326 #ifdef ENABLE_MHW_EPG
327 res = demux->createSectionReader( this, data.m_MHWReader );
330 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
333 res = demux->createSectionReader( this, data.m_MHWReader2 );
336 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
340 messages.send(Message(Message::startChannel, chan));
341 // -> gotMessage -> changedService
347 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
349 channelMapIterator it =
350 m_knownChannels.find(chan);
351 if ( it != m_knownChannels.end() )
354 chan->getState(state);
355 if ( it->second->prevChannelState != state )
359 case iDVBChannel::state_ok:
361 eDebug("[eEPGCache] channel %p running", chan);
362 DVBChannelRunning(chan);
365 case iDVBChannel::state_release:
367 eDebug("[eEPGCache] remove channel %p", chan);
368 messages.send(Message(Message::leaveChannel, chan));
369 pthread_mutex_lock(&it->second->channel_active);
370 singleLock s(channel_map_lock);
371 m_knownChannels.erase(it);
372 pthread_mutex_unlock(&it->second->channel_active);
375 // -> gotMessage -> abortEPG
378 default: // ignore all other events
382 it->second->prevChannelState = state;
387 bool eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
390 timeMap::iterator tmp = tm_it;
391 while ((tmp->first+tmp->second->getDuration()-300) > TM)
394 #ifdef ENABLE_PRIVATE_EPG
395 && tmp->second->type != PRIVATE
398 && tmp->second->type != MHW
402 __u16 event_id = tmp->second->getEventID();
403 servicemap.first.erase(event_id);
405 Event evt((uint8_t*)tmp->second->get());
407 event.parseFrom(&evt, service.sid<<16|service.onid);
408 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
409 service.sid, event_id,
410 event.getBeginTimeString().c_str(),
411 event.getEventName().c_str(),
412 event.getExtendedDescription().c_str());
415 if (tmp == servicemap.second.begin())
417 servicemap.second.erase(tmp);
421 servicemap.second.erase(tmp--);
426 if (tmp == servicemap.second.begin())
433 while(tmp->first < (TM+duration-300))
435 if (tmp->first != TM && tmp->second->type != PRIVATE)
437 __u16 event_id = tmp->second->getEventID();
438 servicemap.first.erase(event_id);
440 Event evt((uint8_t*)tmp->second->get());
442 event.parseFrom(&evt, service.sid<<16|service.onid);
443 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
444 service.sid, event_id,
445 event.getBeginTimeString().c_str(),
446 event.getEventName().c_str(),
447 event.getExtendedDescription().c_str());
450 servicemap.second.erase(tmp++);
455 if (tmp == servicemap.second.end())
461 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
463 eit_t *eit = (eit_t*) data;
465 int len=HILO(eit->section_length)-1;//+3-4;
470 // This fixed the EPG on the Multichoice irdeto systems
471 // the EIT packet is non-compliant.. their EIT packet stinks
472 if ( data[ptr-1] < 0x40 )
475 // Cablecom HACK .. tsid / onid in eit data are incorrect.. so we use
476 // it from running channel (just for current transport stream eit data)
477 bool use_transponder_chid = source == SCHEDULE || (source == NOWNEXT && data[0] == 0x4E);
478 eDVBChannelID chid = channel->channel->getChannelID();
479 uniqueEPGKey service( HILO(eit->service_id),
480 use_transponder_chid ? chid.original_network_id.get() : HILO(eit->original_network_id),
481 use_transponder_chid ? chid.transport_stream_id.get() : HILO(eit->transport_stream_id));
483 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
487 time_t TM = parseDVBtime(
488 eit_event->start_time_1,
489 eit_event->start_time_2,
490 eit_event->start_time_3,
491 eit_event->start_time_4,
492 eit_event->start_time_5);
493 time_t now = ::time(0);
495 if ( TM != 3599 && TM > -1)
496 channel->haveData |= source;
498 singleLock s(cache_lock);
499 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
500 // oder eine durch [] erzeugte
501 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
502 eventMap::iterator prevEventIt = servicemap.first.end();
503 timeMap::iterator prevTimeIt = servicemap.second.end();
508 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
510 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
512 eit_event->start_time_1,
513 eit_event->start_time_2,
514 eit_event->start_time_3,
515 eit_event->start_time_4,
516 eit_event->start_time_5,
522 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
525 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
527 __u16 event_id = HILO(eit_event->event_id);
529 int ev_erase_count = 0;
530 int tm_erase_count = 0;
533 // hack for some polsat services on 13.0E..... but this also replaces other valid event_ids with value 0..
534 // but we dont care about it...
535 event_id = event_hash;
536 eit_event->event_id_hi = event_hash >> 8;
537 eit_event->event_id_lo = event_hash & 0xFF;
540 // search in eventmap
541 eventMap::iterator ev_it =
542 servicemap.first.find(event_id);
544 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
546 // entry with this event_id is already exist ?
547 if ( ev_it != servicemap.first.end() )
549 if ( source > ev_it->second->type ) // update needed ?
550 goto next; // when not.. then skip this entry
552 // search this event in timemap
553 timeMap::iterator tm_it_tmp =
554 servicemap.second.find(ev_it->second->getStartTime());
556 if ( tm_it_tmp != servicemap.second.end() )
558 if ( tm_it_tmp->first == TM ) // just update eventdata
561 eventData *tmp = ev_it->second;
562 ev_it->second = tm_it_tmp->second =
563 new eventData(eit_event, eit_event_size, source);
564 if (FixOverlapping(servicemap, TM, duration, tm_it_tmp, service))
566 prevEventIt = servicemap.first.end();
567 prevTimeIt = servicemap.second.end();
572 else // event has new event begin time
575 // delete the found record from timemap
576 servicemap.second.erase(tm_it_tmp);
577 prevTimeIt=servicemap.second.end();
582 // search in timemap, for check of a case if new time has coincided with time of other event
583 // or event was is not found in eventmap
584 timeMap::iterator tm_it =
585 servicemap.second.find(TM);
587 if ( tm_it != servicemap.second.end() )
589 // event with same start time but another event_id...
590 if ( source > tm_it->second->type &&
591 ev_it == servicemap.first.end() )
592 goto next; // when not.. then skip this entry
594 // search this time in eventmap
595 eventMap::iterator ev_it_tmp =
596 servicemap.first.find(tm_it->second->getEventID());
598 if ( ev_it_tmp != servicemap.first.end() )
601 // delete the found record from eventmap
602 servicemap.first.erase(ev_it_tmp);
603 prevEventIt=servicemap.first.end();
606 evt = new eventData(eit_event, eit_event_size, source);
608 bool consistencyCheck=true;
610 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
613 delete ev_it->second;
614 delete tm_it->second;
618 else if (ev_erase_count == 0 && tm_erase_count > 0)
621 delete ev_it->second;
622 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
625 else if (ev_erase_count > 0 && tm_erase_count == 0)
628 delete tm_it->second;
629 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
632 else // added new eventData
635 consistencyCheck=false;
637 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
638 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
642 if ( consistencyCheck )
644 if ( tm_it->second != evt || ev_it->second != evt )
645 eFatal("tm_it->second != ev_it->second");
646 else if ( tm_it->second->getStartTime() != tm_it->first )
647 eFatal("event start_time(%d) non equal timemap key(%d)",
648 tm_it->second->getStartTime(), tm_it->first );
649 else if ( tm_it->first != TM )
650 eFatal("timemap key(%d) non equal TM(%d)",
652 else if ( ev_it->second->getEventID() != ev_it->first )
653 eFatal("event_id (%d) non equal event_map key(%d)",
654 ev_it->second->getEventID(), ev_it->first);
655 else if ( ev_it->first != event_id )
656 eFatal("eventmap key(%d) non equal event_id(%d)",
657 ev_it->first, event_id );
660 if (FixOverlapping(servicemap, TM, duration, tm_it, service))
662 prevEventIt = servicemap.first.end();
663 prevTimeIt = servicemap.second.end();
668 if ( servicemap.first.size() != servicemap.second.size() )
670 FILE *f = fopen("/hdd/event_map.txt", "w+");
672 for (eventMap::iterator it(servicemap.first.begin())
673 ; it != servicemap.first.end(); ++it )
674 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
675 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
677 f = fopen("/hdd/time_map.txt", "w+");
679 for (timeMap::iterator it(servicemap.second.begin())
680 ; it != servicemap.second.end(); ++it )
681 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
682 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
685 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
686 service.sid, service.tsid, service.onid,
687 servicemap.first.size(), servicemap.second.size() );
690 ptr += eit_event_size;
691 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
695 void eEPGCache::flushEPG(const uniqueEPGKey & s)
697 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
698 singleLock l(cache_lock);
699 if (s) // clear only this service
701 eventCache::iterator it = eventDB.find(s);
702 if ( it != eventDB.end() )
704 eventMap &evMap = it->second.first;
705 timeMap &tmMap = it->second.second;
707 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
712 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
713 #ifdef ENABLE_PRIVATE_EPG
714 contentMaps::iterator it =
715 content_time_tables.find(s);
716 if ( it != content_time_tables.end() )
719 content_time_tables.erase(it);
724 else // clear complete EPG Cache
726 for (eventCache::iterator it(eventDB.begin());
727 it != eventDB.end(); ++it)
729 eventMap &evMap = it->second.first;
730 timeMap &tmMap = it->second.second;
731 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
737 #ifdef ENABLE_PRIVATE_EPG
738 content_time_tables.clear();
740 channelLastUpdated.clear();
741 singleLock m(channel_map_lock);
742 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
743 it->second->startEPG();
745 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
748 void eEPGCache::cleanLoop()
750 singleLock s(cache_lock);
751 if (!eventDB.empty())
753 eDebug("[EPGC] start cleanloop");
755 time_t now = ::time(0);
757 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
759 bool updated = false;
760 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
762 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
764 // remove entry from eventMap
765 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
766 if ( b != DBIt->second.first.end() )
768 // release Heap Memory for this entry (new ....)
769 // eDebug("[EPGC] delete old event (evmap)");
770 DBIt->second.first.erase(b);
773 // remove entry from timeMap
774 // eDebug("[EPGC] release heap mem");
776 DBIt->second.second.erase(It++);
777 // eDebug("[EPGC] delete old event (timeMap)");
783 #ifdef ENABLE_PRIVATE_EPG
786 contentMaps::iterator x =
787 content_time_tables.find( DBIt->first );
788 if ( x != content_time_tables.end() )
790 timeMap &tmMap = DBIt->second.second;
791 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
793 for ( contentTimeMap::iterator it(i->second.begin());
794 it != i->second.end(); )
796 if ( tmMap.find(it->second.first) == tmMap.end() )
797 i->second.erase(it++);
801 if ( i->second.size() )
804 x->second.erase(i++);
810 eDebug("[EPGC] stop cleanloop");
811 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
813 cleanTimer->start(CLEAN_INTERVAL,true);
816 eEPGCache::~eEPGCache()
818 messages.send(Message::quit);
819 kill(); // waiting for thread shutdown
820 singleLock s(cache_lock);
821 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
822 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
826 void eEPGCache::gotMessage( const Message &msg )
831 flushEPG(msg.service);
833 case Message::startChannel:
835 singleLock s(channel_map_lock);
836 channelMapIterator channel =
837 m_knownChannels.find(msg.channel);
838 if ( channel != m_knownChannels.end() )
839 channel->second->startChannel();
842 case Message::leaveChannel:
844 singleLock s(channel_map_lock);
845 channelMapIterator channel =
846 m_knownChannels.find(msg.channel);
847 if ( channel != m_knownChannels.end() )
848 channel->second->abortEPG();
854 #ifdef ENABLE_PRIVATE_EPG
855 case Message::got_private_pid:
857 singleLock s(channel_map_lock);
858 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
860 eDVBChannel *channel = (eDVBChannel*) it->first;
861 channel_data *data = it->second;
862 eDVBChannelID chid = channel->getChannelID();
863 if ( chid.transport_stream_id.get() == msg.service.tsid &&
864 chid.original_network_id.get() == msg.service.onid &&
865 data->m_PrivatePid == -1 )
867 data->m_PrevVersion = -1;
868 data->m_PrivatePid = msg.pid;
869 data->m_PrivateService = msg.service;
870 int onid = chid.original_network_id.get();
871 onid |= 0x80000000; // we use highest bit as private epg indicator
872 chid.original_network_id = onid;
873 updateMap::iterator It = channelLastUpdated.find( chid );
874 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
875 if (update < ZAP_DELAY)
877 data->startPrivateTimer->start(update, 1);
879 eDebug("[EPGC] next private update in %i min", update/60000);
880 else if (update >= 1000)
881 eDebug("[EPGC] next private update in %i sec", update/1000);
888 #ifdef ENABLE_MHW_EPG
889 case Message::got_mhw2_channel_pid:
891 singleLock s(channel_map_lock);
892 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
894 eDVBChannel *channel = (eDVBChannel*) it->first;
895 channel_data *data = it->second;
896 eDVBChannelID chid = channel->getChannelID();
897 if ( chid.transport_stream_id.get() == msg.service.tsid &&
898 chid.original_network_id.get() == msg.service.onid )
900 data->m_mhw2_channel_pid = msg.pid;
901 eDebug("[EPGC] got mhw2 channel pid %04x", msg.pid);
907 case Message::got_mhw2_title_pid:
909 singleLock s(channel_map_lock);
910 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
912 eDVBChannel *channel = (eDVBChannel*) it->first;
913 channel_data *data = it->second;
914 eDVBChannelID chid = channel->getChannelID();
915 if ( chid.transport_stream_id.get() == msg.service.tsid &&
916 chid.original_network_id.get() == msg.service.onid )
918 data->m_mhw2_title_pid = msg.pid;
919 eDebug("[EPGC] got mhw2 title pid %04x", msg.pid);
925 case Message::got_mhw2_summary_pid:
927 singleLock s(channel_map_lock);
928 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
930 eDVBChannel *channel = (eDVBChannel*) it->first;
931 channel_data *data = it->second;
932 eDVBChannelID chid = channel->getChannelID();
933 if ( chid.transport_stream_id.get() == msg.service.tsid &&
934 chid.original_network_id.get() == msg.service.onid )
936 data->m_mhw2_summary_pid = msg.pid;
937 eDebug("[EPGC] got mhw2 summary pid %04x", msg.pid);
944 case Message::timeChanged:
948 eDebug("unhandled EPGCache Message!!");
953 void eEPGCache::thread()
963 void eEPGCache::load()
965 FILE *f = fopen("/hdd/epg.dat", "r");
968 unlink("/hdd/epg.dat");
972 unsigned char md5_saved[16];
973 unsigned char md5[16];
976 if (!md5_file("/hdd/epg.dat", 1, md5))
978 FILE *f = fopen("/hdd/epg.dat.md5", "r");
981 fread( md5_saved, 16, 1, f);
983 if ( !memcmp(md5_saved, md5, 16) )
990 unsigned int magic=0;
991 fread( &magic, sizeof(int), 1, f);
992 if (magic != 0x98765432)
994 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
999 fread( text1, 13, 1, f);
1000 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
1002 singleLock s(cache_lock);
1003 fread( &size, sizeof(int), 1, f);
1010 fread( &key, sizeof(uniqueEPGKey), 1, f);
1011 fread( &size, sizeof(int), 1, f);
1017 fread( &type, sizeof(__u8), 1, f);
1018 fread( &len, sizeof(__u8), 1, f);
1019 event = new eventData(0, len, type);
1020 event->EITdata = new __u8[len];
1021 eventData::CacheSize+=len;
1022 fread( event->EITdata, len, 1, f);
1023 evMap[ event->getEventID() ]=event;
1024 tmMap[ event->getStartTime() ]=event;
1027 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
1030 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
1031 #ifdef ENABLE_PRIVATE_EPG
1033 fread( text2, 11, 1, f);
1034 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
1037 fread( &size, sizeof(int), 1, f);
1042 fread( &key, sizeof(uniqueEPGKey), 1, f);
1043 eventMap &evMap=eventDB[key].first;
1044 fread( &size, sizeof(int), 1, f);
1049 fread( &content_id, sizeof(int), 1, f);
1050 fread( &size, sizeof(int), 1, f);
1053 time_t time1, time2;
1055 fread( &time1, sizeof(time_t), 1, f);
1056 fread( &time2, sizeof(time_t), 1, f);
1057 fread( &event_id, sizeof(__u16), 1, f);
1058 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
1059 eventMap::iterator it =
1060 evMap.find(event_id);
1061 if (it != evMap.end())
1062 it->second->type = PRIVATE;
1067 #endif // ENABLE_PRIVATE_EPG
1070 eDebug("[EPGC] don't read old epg database");
1076 void eEPGCache::save()
1080 if (statfs("/hdd", &s)<0)
1088 // prevent writes to builtin flash
1089 if ( tmp < 1024*1024*50 ) // storage size < 50MB
1092 // check for enough free space on storage
1095 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
1098 FILE *f = fopen("/hdd/epg.dat", "w");
1102 unsigned int magic = 0x98765432;
1103 fwrite( &magic, sizeof(int), 1, f);
1104 const char *text = "UNFINISHED_V7";
1105 fwrite( text, 13, 1, f );
1106 int size = eventDB.size();
1107 fwrite( &size, sizeof(int), 1, f );
1108 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1110 timeMap &timemap = service_it->second.second;
1111 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1112 size = timemap.size();
1113 fwrite( &size, sizeof(int), 1, f);
1114 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1116 __u8 len = time_it->second->ByteSize;
1117 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1118 fwrite( &len, sizeof(__u8), 1, f);
1119 fwrite( time_it->second->EITdata, len, 1, f);
1123 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
1125 #ifdef ENABLE_PRIVATE_EPG
1126 const char* text3 = "PRIVATE_EPG";
1127 fwrite( text3, 11, 1, f );
1128 size = content_time_tables.size();
1129 fwrite( &size, sizeof(int), 1, f);
1130 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1132 contentMap &content_time_table = a->second;
1133 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1134 int size = content_time_table.size();
1135 fwrite( &size, sizeof(int), 1, f);
1136 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1138 int size = i->second.size();
1139 fwrite( &i->first, sizeof(int), 1, f);
1140 fwrite( &size, sizeof(int), 1, f);
1141 for ( contentTimeMap::iterator it(i->second.begin());
1142 it != i->second.end(); ++it )
1144 fwrite( &it->first, sizeof(time_t), 1, f);
1145 fwrite( &it->second.first, sizeof(time_t), 1, f);
1146 fwrite( &it->second.second, sizeof(__u16), 1, f);
1151 // write version string after binary data
1152 // has been written to disk.
1154 fseek(f, sizeof(int), SEEK_SET);
1155 fwrite("ENIGMA_EPG_V7", 13, 1, f);
1158 unsigned char md5[16];
1159 if (!md5_file("/hdd/epg.dat", 1, md5))
1161 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1164 fwrite( md5, 16, 1, f);
1172 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1174 ,abortTimer(eTimer::create(ml)), zapTimer(eTimer::create(ml)), state(0)
1175 ,isRunning(0), haveData(0)
1176 #ifdef ENABLE_PRIVATE_EPG
1177 ,startPrivateTimer(eTimer::create(ml))
1179 #ifdef ENABLE_MHW_EPG
1180 ,m_MHWTimeoutTimer(eTimer::create(ml))
1183 #ifdef ENABLE_MHW_EPG
1184 CONNECT(m_MHWTimeoutTimer->timeout, eEPGCache::channel_data::MHWTimeout);
1186 CONNECT(zapTimer->timeout, eEPGCache::channel_data::startEPG);
1187 CONNECT(abortTimer->timeout, eEPGCache::channel_data::abortNonAvail);
1188 #ifdef ENABLE_PRIVATE_EPG
1189 CONNECT(startPrivateTimer->timeout, eEPGCache::channel_data::startPrivateReader);
1191 pthread_mutex_init(&channel_active, 0);
1194 bool eEPGCache::channel_data::finishEPG()
1196 if (!isRunning) // epg ready
1198 eDebug("[EPGC] stop caching events(%ld)", ::time(0));
1199 zapTimer->start(UPDATE_INTERVAL, 1);
1200 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1201 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1203 seenSections[i].clear();
1204 calcedSections[i].clear();
1206 singleLock l(cache->cache_lock);
1207 cache->channelLastUpdated[channel->getChannelID()] = ::time(0);
1208 #ifdef ENABLE_MHW_EPG
1216 void eEPGCache::channel_data::startEPG()
1218 eDebug("[EPGC] start caching events(%ld)", ::time(0));
1221 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1223 seenSections[i].clear();
1224 calcedSections[i].clear();
1227 eDVBSectionFilterMask mask;
1228 memset(&mask, 0, sizeof(mask));
1230 #ifdef ENABLE_MHW_EPG
1232 mask.data[0] = 0x91;
1233 mask.mask[0] = 0xFF;
1234 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1235 m_MHWReader->start(mask);
1237 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1239 mask.pid = m_mhw2_channel_pid;
1240 mask.data[0] = 0xC8;
1241 mask.mask[0] = 0xFF;
1243 mask.mask[1] = 0xFF;
1244 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1245 m_MHWReader2->start(mask);
1247 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1250 m_MHWTimeoutet=false;
1254 mask.flags = eDVBSectionFilterMask::rfCRC;
1256 mask.data[0] = 0x4E;
1257 mask.mask[0] = 0xFE;
1258 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1259 m_NowNextReader->start(mask);
1260 isRunning |= NOWNEXT;
1262 mask.data[0] = 0x50;
1263 mask.mask[0] = 0xF0;
1264 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1265 m_ScheduleReader->start(mask);
1266 isRunning |= SCHEDULE;
1268 mask.data[0] = 0x60;
1269 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1270 m_ScheduleOtherReader->start(mask);
1271 isRunning |= SCHEDULE_OTHER;
1275 mask.data[0] = 0x40;
1276 mask.mask[0] = 0x40;
1277 m_ViasatReader->connectRead(slot(*this, &eEPGCache::channel_data::readDataViasat), m_ViasatConn);
1278 m_ViasatReader->start(mask);
1279 isRunning |= VIASAT;
1281 abortTimer->start(7000,true);
1284 void eEPGCache::channel_data::abortNonAvail()
1288 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1290 eDebug("[EPGC] abort non avail nownext reading");
1291 isRunning &= ~NOWNEXT;
1292 m_NowNextReader->stop();
1295 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1297 eDebug("[EPGC] abort non avail schedule reading");
1298 isRunning &= ~SCHEDULE;
1299 m_ScheduleReader->stop();
1302 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1304 eDebug("[EPGC] abort non avail schedule other reading");
1305 isRunning &= ~SCHEDULE_OTHER;
1306 m_ScheduleOtherReader->stop();
1307 m_ScheduleOtherConn=0;
1309 if ( !(haveData&VIASAT) && (isRunning&VIASAT) )
1311 eDebug("[EPGC] abort non avail viasat reading");
1312 isRunning &= ~VIASAT;
1313 m_ViasatReader->stop();
1316 #ifdef ENABLE_MHW_EPG
1317 if ( !(haveData&MHW) && (isRunning&MHW) )
1319 eDebug("[EPGC] abort non avail mhw reading");
1321 m_MHWReader->stop();
1323 m_MHWReader2->stop();
1327 if ( isRunning & VIASAT )
1328 abortTimer->start(300000, true);
1329 else if ( isRunning )
1330 abortTimer->start(90000, true);
1334 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1336 seenSections[i].clear();
1337 calcedSections[i].clear();
1344 void eEPGCache::channel_data::startChannel()
1346 pthread_mutex_lock(&channel_active);
1347 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1349 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
1351 if (update < ZAP_DELAY)
1354 zapTimer->start(update, 1);
1355 if (update >= 60000)
1356 eDebug("[EPGC] next update in %i min", update/60000);
1357 else if (update >= 1000)
1358 eDebug("[EPGC] next update in %i sec", update/1000);
1361 void eEPGCache::channel_data::abortEPG()
1363 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1365 seenSections[i].clear();
1366 calcedSections[i].clear();
1372 eDebug("[EPGC] abort caching events !!");
1373 if (isRunning & SCHEDULE)
1375 isRunning &= ~SCHEDULE;
1376 m_ScheduleReader->stop();
1379 if (isRunning & NOWNEXT)
1381 isRunning &= ~NOWNEXT;
1382 m_NowNextReader->stop();
1385 if (isRunning & SCHEDULE_OTHER)
1387 isRunning &= ~SCHEDULE_OTHER;
1388 m_ScheduleOtherReader->stop();
1389 m_ScheduleOtherConn=0;
1391 if (isRunning & VIASAT)
1393 isRunning &= ~VIASAT;
1394 m_ViasatReader->stop();
1397 #ifdef ENABLE_MHW_EPG
1398 if (isRunning & MHW)
1401 m_MHWReader->stop();
1403 m_MHWReader2->stop();
1408 #ifdef ENABLE_PRIVATE_EPG
1409 if (m_PrivateReader)
1410 m_PrivateReader->stop();
1414 pthread_mutex_unlock(&channel_active);
1418 void eEPGCache::channel_data::readDataViasat( const __u8 *data)
1421 memcpy(&d, &data, sizeof(__u8*));
1426 void eEPGCache::channel_data::readData( const __u8 *data)
1430 iDVBSectionReader *reader=NULL;
1434 reader=m_NowNextReader;
1439 reader=m_ScheduleReader;
1444 reader=m_ScheduleOtherReader;
1445 source=SCHEDULE_OTHER;
1450 reader=m_ViasatReader;
1455 eDebug("[EPGC] unknown table_id !!!");
1458 tidMap &seenSections = this->seenSections[map];
1459 tidMap &calcedSections = this->calcedSections[map];
1460 if ( state == 1 && calcedSections == seenSections || state > 1 )
1462 eDebugNoNewLine("[EPGC] ");
1467 eDebugNoNewLine("nownext");
1471 eDebugNoNewLine("schedule");
1473 case SCHEDULE_OTHER:
1474 m_ScheduleOtherConn=0;
1475 eDebugNoNewLine("schedule other");
1479 eDebugNoNewLine("viasat");
1481 default: eDebugNoNewLine("unknown");break;
1483 eDebug(" finished(%ld)", ::time(0));
1486 isRunning &= ~source;
1492 eit_t *eit = (eit_t*) data;
1493 __u32 sectionNo = data[0] << 24;
1494 sectionNo |= data[3] << 16;
1495 sectionNo |= data[4] << 8;
1496 sectionNo |= eit->section_number;
1498 tidMap::iterator it =
1499 seenSections.find(sectionNo);
1501 if ( it == seenSections.end() )
1503 seenSections.insert(sectionNo);
1504 calcedSections.insert(sectionNo);
1505 __u32 tmpval = sectionNo & 0xFFFFFF00;
1506 __u8 incr = source == NOWNEXT ? 1 : 8;
1507 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1509 if ( i == eit->section_number )
1511 for (int x=i; x <= eit->segment_last_section_number; ++x)
1512 calcedSections.insert(tmpval|(x&0xFF));
1515 calcedSections.insert(tmpval|(i&0xFF));
1517 cache->sectionRead(data, source, this);
1522 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1523 // if t == -1 we search the current event...
1525 singleLock s(cache_lock);
1526 uniqueEPGKey key(handleGroup(service));
1528 // check if EPG for this service is ready...
1529 eventCache::iterator It = eventDB.find( key );
1530 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1534 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1535 It->second.second.upper_bound(t); // just >
1536 if ( i != It->second.second.end() )
1538 if ( direction < 0 || (direction == 0 && i->first > t) )
1540 timeMap::iterator x = i;
1542 if ( x != It->second.second.end() )
1544 time_t start_time = x->first;
1549 if (t > (start_time+x->second->getDuration()))
1564 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1566 singleLock s(cache_lock);
1567 const eventData *data=0;
1568 RESULT ret = lookupEventTime(service, t, data, direction);
1570 result = data->get();
1574 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1576 singleLock s(cache_lock);
1577 const eventData *data=0;
1578 RESULT ret = lookupEventTime(service, t, data, direction);
1580 result = new Event((uint8_t*)data->get());
1584 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1586 singleLock s(cache_lock);
1587 const eventData *data=0;
1588 RESULT ret = lookupEventTime(service, t, data, direction);
1591 Event ev((uint8_t*)data->get());
1592 result = new eServiceEvent();
1593 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1594 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1599 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1601 singleLock s(cache_lock);
1602 uniqueEPGKey key(handleGroup(service));
1604 eventCache::iterator It = eventDB.find( key );
1605 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1607 eventMap::iterator i( It->second.first.find( event_id ));
1608 if ( i != It->second.first.end() )
1616 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1622 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1624 singleLock s(cache_lock);
1625 const eventData *data=0;
1626 RESULT ret = lookupEventId(service, event_id, data);
1628 result = data->get();
1632 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1634 singleLock s(cache_lock);
1635 const eventData *data=0;
1636 RESULT ret = lookupEventId(service, event_id, data);
1638 result = new Event((uint8_t*)data->get());
1642 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1644 singleLock s(cache_lock);
1645 const eventData *data=0;
1646 RESULT ret = lookupEventId(service, event_id, data);
1649 Event ev((uint8_t*)data->get());
1650 result = new eServiceEvent();
1651 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1652 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1657 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1659 singleLock s(cache_lock);
1660 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1663 eventCache::iterator It = eventDB.find(ref);
1664 if ( It != eventDB.end() && It->second.second.size() )
1666 m_timemap_cursor = It->second.second.lower_bound(begin);
1667 if ( m_timemap_cursor != It->second.second.end() )
1669 if ( m_timemap_cursor->first != begin )
1671 timeMap::iterator x = m_timemap_cursor;
1673 if ( x != It->second.second.end() )
1675 time_t start_time = x->first;
1676 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1677 m_timemap_cursor = x;
1683 m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1685 m_timemap_end = It->second.second.end();
1687 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1688 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1693 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1695 if ( m_timemap_cursor != m_timemap_end )
1697 result = m_timemap_cursor++->second;
1703 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1705 if ( m_timemap_cursor != m_timemap_end )
1707 result = m_timemap_cursor++->second->get();
1713 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1715 if ( m_timemap_cursor != m_timemap_end )
1717 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1723 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1725 if ( m_timemap_cursor != m_timemap_end )
1727 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1728 result = new eServiceEvent();
1729 return result->parseFrom(&ev, currentQueryTsidOnid);
1734 void fillTuple(ePyObject tuple, const char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1739 while(spos < argcount)
1741 bool inc_refcount=false;
1742 switch((c=argstring[spos++]))
1744 case '0': // PyLong 0
1745 tmp = PyLong_FromLong(0);
1747 case 'I': // Event Id
1748 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1750 case 'B': // Event Begin Time
1751 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1753 case 'D': // Event Duration
1754 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1756 case 'T': // Event Title
1757 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1759 case 'S': // Event Short Description
1760 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1762 case 'E': // Event Extended Description
1763 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1765 case 'C': // Current Time
1767 inc_refcount = true;
1769 case 'R': // service reference string
1771 inc_refcount = true;
1773 case 'n': // short service name
1774 case 'N': // service name
1776 inc_refcount = true;
1781 default: // ignore unknown
1783 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1788 inc_refcount = true;
1792 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1796 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1800 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1801 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1805 Py_DECREF(service_name);
1808 Py_DECREF(convertFuncArgs);
1809 Py_DECREF(dest_list);
1810 PyErr_SetString(PyExc_StandardError,
1811 "error in convertFunc execute");
1812 eDebug("error in convertFunc execute");
1815 PyList_Append(dest_list, result);
1820 ePyObject tuple = PyTuple_New(argcount);
1821 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1822 PyList_Append(dest_list, tuple);
1828 // here we get a python list
1829 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1832 // B = Event Begin Time
1833 // D = Event Duration
1835 // S = Event Short Description
1836 // E = Event Extended Description
1838 // R = Service Reference
1840 // n = Short Service Name
1841 // X = Return a minimum of one tuple per service in the result list... even when no event was found.
1842 // The returned tuple is filled with all available infos... non avail is filled as None
1843 // The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1844 // then for each service follows a tuple
1845 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1846 // the second is the type of query
1848 // -1 = event before given start_time
1849 // 0 = event intersects given start_time
1850 // +1 = event after given start_time
1852 // when type is eventid it is the event_id
1853 // when type is time then it is the start_time ( -1 for now_time )
1854 // the fourth is the end_time .. ( optional .. for query all events in time range)
1856 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1858 ePyObject convertFuncArgs;
1860 const char *argstring=NULL;
1861 if (!PyList_Check(list))
1863 PyErr_SetString(PyExc_StandardError,
1869 int listSize=PyList_Size(list);
1872 PyErr_SetString(PyExc_StandardError,
1873 "not params given");
1874 eDebug("not params given");
1879 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1880 if (PyString_Check(argv))
1882 argstring = PyString_AS_STRING(argv);
1886 argstring = "I"; // just event id as default
1887 argcount = strlen(argstring);
1888 // eDebug("have %d args('%s')", argcount, argstring);
1891 bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1897 if (!PyCallable_Check(convertFunc))
1899 PyErr_SetString(PyExc_StandardError,
1900 "convertFunc must be callable");
1901 eDebug("convertFunc is not callable");
1904 convertFuncArgs = PyTuple_New(argcount);
1907 ePyObject nowTime = strchr(argstring, 'C') ?
1908 PyLong_FromLong(::time(0)) :
1911 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1914 ePyObject dest_list=PyList_New(0);
1915 while(listSize > listIt)
1917 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1918 if (PyTuple_Check(item))
1920 bool service_changed=false;
1925 int tupleSize=PyTuple_Size(item);
1928 while(tupleSize > tupleIt) // parse query args
1930 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1935 if (!PyString_Check(entry))
1937 eDebug("tuple entry 0 is no a string");
1944 type=PyInt_AsLong(entry);
1945 if (type < -1 || type > 2)
1947 eDebug("unknown type %d", type);
1952 event_id=stime=PyInt_AsLong(entry);
1955 minutes=PyInt_AsLong(entry);
1958 eDebug("unneeded extra argument");
1963 if (minutes && stime == -1)
1966 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1967 if (ref.type != eServiceReference::idDVB)
1969 eDebug("service reference for epg query is not valid");
1973 // redirect subservice querys to parent service
1974 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1975 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1977 eServiceCenterPtr service_center;
1978 if (!eServiceCenter::getPrivInstance(service_center))
1980 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1981 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1982 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1983 dvb_ref.setParentServiceID(eServiceID(0));
1985 service = PyString_FromString(dvb_ref.toString().c_str());
1986 service_changed = true;
1990 ePyObject service_name;
1991 if (must_get_service_name)
1993 ePtr<iStaticServiceInformation> sptr;
1994 eServiceCenterPtr service_center;
1995 eServiceCenter::getPrivInstance(service_center);
1998 service_center->info(ref, sptr);
2002 sptr->getName(ref, name);
2004 if (must_get_service_name == 1)
2007 // filter short name brakets
2008 while((pos = name.find("\xc2\x86")) != std::string::npos)
2010 while((pos = name.find("\xc2\x87")) != std::string::npos)
2014 name = buildShortName(name);
2017 service_name = PyString_FromString(name.c_str());
2021 service_name = PyString_FromString("<n/a>");
2025 singleLock s(cache_lock);
2026 if (!startTimeQuery(ref, stime, minutes))
2028 while ( m_timemap_cursor != m_timemap_end )
2030 Event ev((uint8_t*)m_timemap_cursor++->second->get());
2032 evt.parseFrom(&ev, currentQueryTsidOnid);
2033 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2037 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2043 const eventData *ev_data=0;
2046 singleLock s(cache_lock);
2048 lookupEventId(ref, event_id, ev_data);
2050 lookupEventTime(ref, stime, ev_data, type);
2053 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2054 Event ev((uint8_t*)ev_data->get());
2055 evt.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2060 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2063 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2066 if (service_changed)
2069 Py_DECREF(service_name);
2074 if (convertFuncArgs)
2075 Py_DECREF(convertFuncArgs);
2081 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2085 while(pos < argcount)
2087 bool inc_refcount=false;
2088 switch(argstring[pos])
2090 case '0': // PyLong 0
2091 tmp = PyLong_FromLong(0);
2093 case 'I': // Event Id
2094 tmp = PyLong_FromLong(evData->getEventID());
2096 case 'B': // Event Begin Time
2098 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2100 tmp = PyLong_FromLong(evData->getStartTime());
2102 case 'D': // Event Duration
2104 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2106 tmp = PyLong_FromLong(evData->getDuration());
2108 case 'T': // Event Title
2109 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2111 case 'S': // Event Short Description
2112 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2114 case 'E': // Event Extended Description
2115 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2117 case 'R': // service reference string
2118 tmp = service_reference;
2119 inc_refcount = true;
2121 case 'n': // short service name
2122 case 'N': // service name
2124 inc_refcount = true;
2126 default: // ignore unknown
2128 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2133 inc_refcount = true;
2137 PyTuple_SET_ITEM(tuple, pos++, tmp);
2141 // here we get a python tuple
2142 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2144 // B = Event Begin Time
2145 // D = Event Duration
2147 // S = Event Short Description
2148 // E = Event Extended Description
2149 // R = Service Reference
2151 // n = Short Service Name
2152 // the second tuple entry is the MAX matches value
2153 // the third tuple entry is the type of query
2154 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2155 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2156 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2157 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2158 // the fourth is the servicereference string
2159 // the fifth is the eventid
2160 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2161 // the fourth is the search text
2163 // 0 = case sensitive (CASE_CHECK)
2164 // 1 = case insensitive (NO_CASECHECK)
2166 PyObject *eEPGCache::search(ePyObject arg)
2172 const char *argstring=0;
2176 bool needServiceEvent=false;
2178 int must_get_service_name = 0;
2179 bool must_get_service_reference = false;
2181 if (PyTuple_Check(arg))
2183 int tuplesize=PyTuple_Size(arg);
2186 ePyObject obj = PyTuple_GET_ITEM(arg,0);
2187 if (PyString_Check(obj))
2189 #if PY_VERSION_HEX < 0x02060000
2190 argcount = PyString_GET_SIZE(obj);
2192 argcount = PyString_Size(obj);
2194 argstring = PyString_AS_STRING(obj);
2195 for (int i=0; i < argcount; ++i)
2196 switch(argstring[i])
2201 needServiceEvent=true;
2204 must_get_service_name = 1;
2207 must_get_service_name = 2;
2210 must_get_service_reference = true;
2218 PyErr_SetString(PyExc_StandardError,
2220 eDebug("tuple arg 0 is not a string");
2225 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2228 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2229 if (tuplesize > 4 && querytype == 0)
2231 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2232 if (PyString_Check(obj))
2234 refstr = PyString_AS_STRING(obj);
2235 eServiceReferenceDVB ref(refstr);
2238 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2239 singleLock s(cache_lock);
2240 const eventData *evData = 0;
2241 lookupEventId(ref, eventid, evData);
2244 __u8 *data = evData->EITdata;
2245 int tmp = evData->ByteSize-10;
2246 __u32 *p = (__u32*)(data+10);
2247 // search short and extended event descriptors
2251 descriptorMap::iterator it =
2252 eventData::descriptors.find(crc);
2253 if (it != eventData::descriptors.end())
2255 __u8 *descr_data = it->second.second;
2256 switch(descr_data[0])
2259 descr[++descridx]=crc;
2268 eDebug("event not found");
2272 PyErr_SetString(PyExc_StandardError, "type error");
2273 eDebug("tuple arg 4 is not a valid service reference string");
2279 PyErr_SetString(PyExc_StandardError, "type error");
2280 eDebug("tuple arg 4 is not a string");
2284 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2286 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2287 if (PyString_Check(obj))
2289 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2290 const char *str = PyString_AS_STRING(obj);
2291 #if PY_VERSION_HEX < 0x02060000
2292 int textlen = PyString_GET_SIZE(obj);
2294 int textlen = PyString_Size(obj);
2297 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2299 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2300 singleLock s(cache_lock);
2301 for (descriptorMap::iterator it(eventData::descriptors.begin());
2302 it != eventData::descriptors.end() && descridx < 511; ++it)
2304 __u8 *data = it->second.second;
2305 if ( data[0] == 0x4D ) // short event descriptor
2307 int title_len = data[5];
2308 if ( querytype == 1 )
2311 // skip DVB-Text Encoding!
2312 if (data[6] == 0x10)
2317 else if(data[6] > 0 && data[6] < 0x20)
2322 if (title_len != textlen)
2326 if ( !strncasecmp((const char*)data+offs, str, title_len) )
2328 // std::string s((const char*)data+offs, title_len);
2329 // eDebug("match1 %s %s", str, s.c_str() );
2330 descr[++descridx] = it->first;
2333 else if ( !strncmp((const char*)data+offs, str, title_len) )
2335 // std::string s((const char*)data+offs, title_len);
2336 // eDebug("match2 %s %s", str, s.c_str() );
2337 descr[++descridx] = it->first;
2343 while((title_len-idx) >= textlen)
2347 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2349 descr[++descridx] = it->first;
2350 // std::string s((const char*)data+6, title_len);
2351 // eDebug("match 3 %s %s", str, s.c_str() );
2355 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2357 descr[++descridx] = it->first;
2358 // std::string s((const char*)data+6, title_len);
2359 // eDebug("match 4 %s %s", str, s.c_str() );
2370 PyErr_SetString(PyExc_StandardError,
2372 eDebug("tuple arg 4 is not a string");
2378 PyErr_SetString(PyExc_StandardError,
2380 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2386 PyErr_SetString(PyExc_StandardError,
2388 eDebug("not enough args in tuple");
2394 PyErr_SetString(PyExc_StandardError,
2396 eDebug("arg 0 is not a tuple");
2402 int maxcount=maxmatches;
2403 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2404 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2405 // in this case we start searching with the base service
2406 bool first = ref.valid() ? true : false;
2407 singleLock s(cache_lock);
2408 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2409 while(cit != eventDB.end() && maxcount)
2411 if ( ref.valid() && !first && cit->first == ref )
2413 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2417 ePyObject service_name;
2418 ePyObject service_reference;
2419 timeMap &evmap = cit->second.second;
2421 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2423 int evid = evit->second->getEventID();
2424 if ( evid == eventid)
2426 __u8 *data = evit->second->EITdata;
2427 int tmp = evit->second->ByteSize-10;
2428 __u32 *p = (__u32*)(data+10);
2429 // check if any of our descriptor used by this event
2434 for ( int i=0; i <= descridx; ++i)
2436 if (descr[i] == crc32) // found...
2441 if ( (querytype == 0 && cnt == descridx) ||
2442 ((querytype == 1 || querytype == 2) && cnt != -1) )
2444 const uniqueEPGKey &service = cit->first;
2445 eServiceReference ref =
2446 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2449 // create servive event
2451 const eventData *ev_data=0;
2452 if (needServiceEvent)
2454 if (lookupEventId(ref, evid, ev_data))
2455 eDebug("event not found !!!!!!!!!!!");
2458 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2459 Event ev((uint8_t*)ev_data->get());
2460 ptr.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2463 // create service name
2464 if (must_get_service_name && !service_name)
2466 ePtr<iStaticServiceInformation> sptr;
2467 eServiceCenterPtr service_center;
2468 eServiceCenter::getPrivInstance(service_center);
2471 service_center->info(ref, sptr);
2475 sptr->getName(ref, name);
2477 if (must_get_service_name == 1)
2480 // filter short name brakets
2481 while((pos = name.find("\xc2\x86")) != std::string::npos)
2483 while((pos = name.find("\xc2\x87")) != std::string::npos)
2487 name = buildShortName(name);
2490 service_name = PyString_FromString(name.c_str());
2494 service_name = PyString_FromString("<n/a>");
2496 // create servicereference string
2497 if (must_get_service_reference && !service_reference)
2498 service_reference = PyString_FromString(ref.toString().c_str());
2501 ret = PyList_New(0);
2503 ePyObject tuple = PyTuple_New(argcount);
2505 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2506 PyList_Append(ret, tuple);
2513 Py_DECREF(service_name);
2514 if (service_reference)
2515 Py_DECREF(service_reference);
2518 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2520 cit=eventDB.begin();
2533 #ifdef ENABLE_PRIVATE_EPG
2534 #include <dvbsi++/descriptor_tag.h>
2535 #include <dvbsi++/unknown_descriptor.h>
2536 #include <dvbsi++/private_data_specifier_descriptor.h>
2538 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2540 ePtr<eTable<ProgramMapSection> > ptr;
2541 if (!pmthandler->getPMT(ptr) && ptr)
2543 std::vector<ProgramMapSection*>::const_iterator i;
2544 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2546 const ProgramMapSection &pmt = **i;
2548 ElementaryStreamInfoConstIterator es;
2549 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2552 switch ((*es)->getType())
2554 case 0xC1: // user private
2555 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2556 desc != (*es)->getDescriptors()->end(); ++desc)
2558 switch ((*desc)->getTag())
2560 case 0xC2: // user defined
2561 if ((*desc)->getLength() == 8)
2564 (*desc)->writeToBuffer(buffer);
2565 if (!strncmp((unsigned char*)buffer+2, "EPGDATA", 7))
2567 eServiceReferenceDVB ref;
2568 if (!pmthandler->getServiceReference(ref))
2570 int pid = (*es)->getPid();
2571 messages.send(Message(Message::got_mhw2_channel_pid, ref, pid));
2574 else if(!strncmp((unsigned char*)buffer+2, "FICHAS", 6))
2576 eServiceReferenceDVB ref;
2577 if (!pmthandler->getServiceReference(ref))
2579 int pid = (*es)->getPid();
2580 messages.send(Message(Message::got_mhw2_summary_pid, ref, pid));
2583 else if(!strncmp((unsigned char*)buffer+2, "GENEROS", 7))
2585 eServiceReferenceDVB ref;
2586 if (!pmthandler->getServiceReference(ref))
2588 int pid = (*es)->getPid();
2589 messages.send(Message(Message::got_mhw2_title_pid, ref, pid));
2598 case 0x05: // private
2599 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2600 desc != (*es)->getDescriptors()->end(); ++desc)
2602 switch ((*desc)->getTag())
2604 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2605 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2610 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2611 int descr_len = descr->getLength();
2614 uint8_t data[descr_len+2];
2615 descr->writeToBuffer(data);
2616 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2630 eServiceReferenceDVB ref;
2631 if (!pmthandler->getServiceReference(ref))
2633 int pid = (*es)->getPid();
2634 messages.send(Message(Message::got_private_pid, ref, pid));
2642 eDebug("PMTready but no pmt!!");
2649 date_time( const date_time &a )
2651 memcpy(data, a.data, 5);
2654 date_time( const __u8 data[5])
2656 memcpy(this->data, data, 5);
2657 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2662 const __u8& operator[](int pos) const
2668 struct less_datetime
2670 bool operator()( const date_time &a, const date_time &b ) const
2672 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2676 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2678 contentMap &content_time_table = content_time_tables[current_service];
2679 singleLock s(cache_lock);
2680 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2681 eventMap &evMap = eventDB[current_service].first;
2682 timeMap &tmMap = eventDB[current_service].second;
2684 int content_id = data[ptr++] << 24;
2685 content_id |= data[ptr++] << 16;
2686 content_id |= data[ptr++] << 8;
2687 content_id |= data[ptr++];
2689 contentTimeMap &time_event_map =
2690 content_time_table[content_id];
2691 for ( contentTimeMap::iterator it( time_event_map.begin() );
2692 it != time_event_map.end(); ++it )
2694 eventMap::iterator evIt( evMap.find(it->second.second) );
2695 if ( evIt != evMap.end() )
2697 delete evIt->second;
2700 tmMap.erase(it->second.first);
2702 time_event_map.clear();
2705 memcpy(duration, data+ptr, 3);
2708 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2710 const __u8 *descriptors[65];
2711 const __u8 **pdescr = descriptors;
2713 int descriptors_length = (data[ptr++]&0x0F) << 8;
2714 descriptors_length |= data[ptr++];
2715 while ( descriptors_length > 1 )
2717 int descr_type = data[ptr];
2718 int descr_len = data[ptr+1];
2719 descriptors_length -= 2;
2720 if (descriptors_length >= descr_len)
2722 descriptors_length -= descr_len;
2723 if ( descr_type == 0xf2 && descr_len > 5)
2726 int tsid = data[ptr++] << 8;
2727 tsid |= data[ptr++];
2728 int onid = data[ptr++] << 8;
2729 onid |= data[ptr++];
2730 int sid = data[ptr++] << 8;
2733 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2736 switch( (tsid << 16) | sid )
2738 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2739 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2740 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2741 case 0x0300f5: sid = 0xdc; break;
2742 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2743 case 0x1100d3: sid = 0xe3; break;
2744 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2747 ////////////////////////////////////////////
2749 uniqueEPGKey service( sid, onid, tsid );
2751 while( descr_len > 2 )
2754 datetime[0] = data[ptr++];
2755 datetime[1] = data[ptr++];
2756 int tmp_len = data[ptr++];
2758 if (descr_len >= tmp_len)
2760 descr_len -= tmp_len;
2761 while( tmp_len > 2 )
2763 memcpy(datetime+2, data+ptr, 3);
2766 start_times[datetime].push_back(service);
2779 ASSERT(pdescr <= &descriptors[65]);
2781 eit_event_struct *ev_struct = (eit_event_struct*) event;
2782 ev_struct->running_status = 0;
2783 ev_struct->free_CA_mode = 1;
2784 memcpy(event+7, duration, 3);
2786 const __u8 **d=descriptors;
2787 while ( d < pdescr )
2789 memcpy(event+ptr, *d, ((*d)[1])+2);
2793 ASSERT(ptr <= 4098);
2794 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2796 time_t now = ::time(0);
2797 if ( (it->first.tm + duration_sec) < now )
2799 memcpy(event+2, it->first.data, 5);
2802 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2804 event[bptr++] = 0x4A;
2805 __u8 *len = event+(bptr++);
2806 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2807 event[bptr++] = (i->tsid & 0xFF);
2808 event[bptr++] = (i->onid & 0xFF00) >> 8;
2809 event[bptr++] = (i->onid & 0xFF);
2810 event[bptr++] = (i->sid & 0xFF00) >> 8;
2811 event[bptr++] = (i->sid & 0xFF);
2812 event[bptr++] = 0xB0;
2813 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2814 *len = ((event+bptr) - len)-1;
2816 int llen = bptr - 12;
2817 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2818 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2820 time_t stime = it->first.tm;
2821 while( tmMap.find(stime) != tmMap.end() )
2823 event[6] += (stime - it->first.tm);
2825 while( evMap.find(event_id) != evMap.end() )
2827 event[0] = (event_id & 0xFF00) >> 8;
2828 event[1] = (event_id & 0xFF);
2829 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2830 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2831 evMap[event_id] = d;
2833 ASSERT(bptr <= 4098);
2837 void eEPGCache::channel_data::startPrivateReader()
2839 eDVBSectionFilterMask mask;
2840 memset(&mask, 0, sizeof(mask));
2841 mask.pid = m_PrivatePid;
2842 mask.flags = eDVBSectionFilterMask::rfCRC;
2843 mask.data[0] = 0xA0;
2844 mask.mask[0] = 0xFF;
2845 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2846 if (m_PrevVersion != -1)
2848 mask.data[3] = m_PrevVersion << 1;
2849 mask.mask[3] = 0x3E;
2850 mask.mode[3] = 0x3E;
2852 seenPrivateSections.clear();
2854 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2855 m_PrivateReader->start(mask);
2858 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2860 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2862 cache->privateSectionRead(m_PrivateService, data);
2863 seenPrivateSections.insert(data[6]);
2865 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2867 eDebug("[EPGC] private finished");
2868 eDVBChannelID chid = channel->getChannelID();
2869 int tmp = chid.original_network_id.get();
2870 tmp |= 0x80000000; // we use highest bit as private epg indicator
2871 chid.original_network_id = tmp;
2872 cache->channelLastUpdated[chid] = ::time(0);
2873 m_PrevVersion = (data[5] & 0x3E) >> 1;
2874 startPrivateReader();
2878 #endif // ENABLE_PRIVATE_EPG
2880 #ifdef ENABLE_MHW_EPG
2881 void eEPGCache::channel_data::cleanup()
2886 m_program_ids.clear();
2889 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2891 // Names in mhw structs are not strings as they are not '\0' terminated.
2892 // This function converts the mhw name into a string.
2893 // Constraint: "length of out" = "length of in" + 1.
2895 for ( i=0; i < len_in; i++ )
2899 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2906 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2909 return_time[0] = toBCD( hours );
2910 return_time[1] = toBCD( minutes );
2914 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2916 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2919 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2920 // For date plus time of day
2922 char tz_saved[1024];
2923 // Remove offset in mhw time.
2924 __u8 local_hours = hours;
2927 else if ( hours >= 8 )
2930 // As far as we know all mhw time data is sent in central Europe time zone.
2931 // So, temporarily set timezone to western europe
2932 time_t dt = ::time(0);
2934 char *old_tz = getenv( "TZ" );
2936 strcpy(tz_saved, old_tz);
2937 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2941 localtime_r(&dt, &localnow);
2945 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2947 if (local_hours <= 5)
2950 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2951 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2954 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2956 if ( old_tz == NULL )
2959 setenv("TZ", tz_saved, 1);
2962 // Calculate MJD according to annex in ETSI EN 300 468
2964 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2966 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2967 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2969 return_time[0] = (mjd & 0xFF00)>>8;
2970 return_time[1] = mjd & 0xFF;
2972 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2975 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2976 // data is borrowed from calling proc to save memory space.
2980 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2981 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2982 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2984 eit_t *packet = (eit_t *) data;
2985 packet->table_id = 0x50;
2986 packet->section_syntax_indicator = 1;
2988 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2989 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2990 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2991 packet->current_next_indicator = 0;
2992 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2993 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2994 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2995 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2996 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2997 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2998 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2999 packet->segment_last_table_id = 0x50;
3001 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
3002 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 35 : 23 );
3003 int prog_title_length = prog_title.length();
3005 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3006 prog_title_length + 1;
3008 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
3009 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
3010 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
3014 u_char *data = (u_char*) event_data;
3015 data[2] = itTitle->second.mhw2_mjd_hi;
3016 data[3] = itTitle->second.mhw2_mjd_lo;
3017 data[4] = itTitle->second.mhw2_hours;
3018 data[5] = itTitle->second.mhw2_minutes;
3019 data[6] = itTitle->second.mhw2_seconds;
3020 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
3024 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
3025 (u_char *) event_data + 2 );
3026 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
3029 event_data->running_status = 0;
3030 event_data->free_CA_mode = 0;
3031 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
3033 eit_short_event_descriptor_struct *short_event_descriptor =
3034 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
3035 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
3036 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3037 prog_title_length - 1;
3038 short_event_descriptor->language_code_1 = 'e';
3039 short_event_descriptor->language_code_2 = 'n';
3040 short_event_descriptor->language_code_3 = 'g';
3041 short_event_descriptor->event_name_length = prog_title_length;
3042 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
3043 memcpy(event_name, prog_title.c_str(), prog_title_length);
3046 event_name[prog_title_length] = 0;
3048 if ( sumText.length() > 0 )
3049 // There is summary info
3051 unsigned int sum_length = sumText.length();
3052 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
3053 // Store summary in short event descriptor
3055 // Increase all relevant lengths
3056 event_name[prog_title_length] = sum_length;
3057 short_event_descriptor->descriptor_length += sum_length;
3058 packet_length += sum_length;
3059 descr_ll += sum_length;
3060 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
3063 // Store summary in extended event descriptors
3065 int remaining_sum_length = sumText.length();
3066 int nbr_descr = int(remaining_sum_length/247) + 1;
3067 for ( int i=0; i < nbr_descr; i++)
3068 // Loop once per extended event descriptor
3070 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
3071 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
3072 remaining_sum_length -= sum_length;
3073 packet_length += 8 + sum_length;
3074 descr_ll += 8 + sum_length;
3076 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
3077 ext_event_descriptor->descriptor_length = sum_length + 6;
3078 ext_event_descriptor->descriptor_number = i;
3079 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
3080 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
3081 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
3082 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
3083 u_char *the_text = (u_char *) ext_event_descriptor + 8;
3085 the_text[-1] = sum_length;
3086 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
3093 // Add content descriptor
3094 u_char *descriptor = (u_char *) data + packet_length;
3099 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
3100 if ( content_descr.find( "FILM" ) != std::string::npos )
3102 else if ( content_descr.find( "SPORT" ) != std::string::npos )
3105 descriptor[0] = 0x54;
3107 descriptor[2] = content_id;
3111 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
3112 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
3114 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
3115 packet->section_length_lo = (packet_length - 3)&0xff;
3117 // Feed the data to eEPGCache::sectionRead()
3118 cache->sectionRead( data, MHW, this );
3121 void eEPGCache::channel_data::startTimeout(int msec)
3123 m_MHWTimeoutTimer->start(msec,true);
3124 m_MHWTimeoutet=false;
3127 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
3129 m_MHWFilterMask.pid = pid;
3130 m_MHWFilterMask.data[0] = tid;
3131 m_MHWReader->start(m_MHWFilterMask);
3132 // eDebug("start 0x%02x 0x%02x", pid, tid);
3135 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
3137 m_MHWFilterMask2.pid = pid;
3138 m_MHWFilterMask2.data[0] = tid;
3141 m_MHWFilterMask2.data[1] = ext;
3142 m_MHWFilterMask2.mask[1] = 0xFF;
3143 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
3147 m_MHWFilterMask2.data[1] = 0;
3148 m_MHWFilterMask2.mask[1] = 0;
3149 // eDebug("start 0x%02x 0x%02x", pid, tid);
3151 m_MHWReader2->start(m_MHWFilterMask2);
3154 void eEPGCache::channel_data::readMHWData(const __u8 *data)
3157 m_MHWReader2->stop();
3159 if ( state > 1 || // aborted
3160 // have si data.. so we dont read mhw data
3161 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3163 eDebug("[EPGC] mhw aborted %d", state);
3165 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
3168 int len = ((data[1]&0xf)<<8) + data[2] - 1;
3169 int record_size = sizeof( mhw_channel_name_t );
3170 int nbr_records = int (len/record_size);
3172 m_channels.resize(nbr_records);
3173 for ( int i = 0; i < nbr_records; i++ )
3175 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
3176 m_channels[i]=*channel;
3180 eDebug("[EPGC] mhw %d channels found", m_channels.size());
3182 // Channels table has been read, start reading the themes table.
3183 startMHWReader(0xD3, 0x92);
3186 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
3189 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3190 int record_size = sizeof( mhw_theme_name_t );
3191 int nbr_records = int (len/record_size);
3193 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
3196 for ( int i = 0; i < nbr_records; i++ )
3198 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
3199 if ( i >= next_idx )
3203 next_idx = (__u8) *(data + 3 + idx_ptr);
3209 m_themes[idx+sub_idx] = *theme;
3211 eDebug("[EPGC] mhw %d themes found", m_themes.size());
3212 // Themes table has been read, start reading the titles table.
3213 startMHWReader(0xD2, 0x90);
3217 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3220 mhw_title_t *title = (mhw_title_t*) data;
3222 if ( title->channel_id == 0xFF ) // Separator
3223 return; // Continue reading of the current table.
3226 // Create unique key per title
3227 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
3228 (title->ms.minutes);
3229 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
3230 ((title->program_id_ml)<<8)|(title->program_id_lo);
3232 if ( m_titles.find( title_id ) == m_titles.end() )
3235 title->mhw2_mjd_hi = 0;
3236 title->mhw2_mjd_lo = 0;
3237 title->mhw2_duration_hi = 0;
3238 title->mhw2_duration_lo = 0;
3239 m_titles[ title_id ] = *title;
3240 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3241 // program_ids will be used to gather summaries.
3242 m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3243 return; // Continue reading of the current table.
3245 else if (!checkTimeout())
3248 if ( !m_program_ids.empty())
3250 // Titles table has been read, there are summaries to read.
3251 // Start reading summaries, store corresponding titles on the fly.
3252 startMHWReader(0xD3, 0x90);
3253 eDebug("[EPGC] mhw %d titles(%d with summary) found",
3255 m_program_ids.size());
3260 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3263 mhw_summary_t *summary = (mhw_summary_t*) data;
3265 // Create unique key per record
3266 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3267 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3268 int len = ((data[1]&0xf)<<8) + data[2];
3270 // ugly workaround to convert const __u8* to char*
3272 memcpy(&tmp, &data, sizeof(void*));
3273 tmp[len+3] = 0; // Terminate as a string.
3275 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3276 if ( itProgid == m_program_ids.end() )
3277 { /* This part is to prevent to looping forever if some summaries are not received yet.
3278 There is a timeout of 4 sec. after the last successfully read summary. */
3279 if (!m_program_ids.empty() && !checkTimeout())
3280 return; // Continue reading of the current table.
3284 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3287 while((pos = the_text.find("\r\n")) != std::string::npos)
3288 the_text.replace(pos, 2, " ");
3290 // Find corresponding title, store title and summary in epgcache.
3291 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3292 if ( itTitle != m_titles.end() )
3295 storeTitle( itTitle, the_text, data );
3296 m_titles.erase( itTitle );
3298 m_program_ids.erase( itProgid );
3299 if ( !m_program_ids.empty() )
3300 return; // Continue reading of the current table.
3303 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3305 m_program_ids.size());
3306 // Summaries have been read, titles that have summaries have been stored.
3307 // Now store titles that do not have summaries.
3308 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3309 storeTitle( itTitle, "", data );
3313 m_MHWReader->stop();
3318 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3320 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3323 m_MHWReader->stop();
3325 if ( state > 1 || // aborted
3326 // have si data.. so we dont read mhw data
3327 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3329 eDebug("[EPGC] mhw2 aborted %d", state);
3331 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3334 int num_channels = data[120];
3335 m_channels.resize(num_channels);
3338 int ptr = 121 + 8 * num_channels;
3341 for( int chid = 0; chid < num_channels; ++chid )
3343 ptr += ( data[ptr] & 0x0f ) + 1;
3353 // data seems consistent...
3354 const __u8 *tmp = data+121;
3355 for (int i=0; i < num_channels; ++i)
3357 mhw_channel_name_t channel;
3358 channel.network_id_hi = *(tmp++);
3359 channel.network_id_lo = *(tmp++);
3360 channel.transport_stream_id_hi = *(tmp++);
3361 channel.transport_stream_id_lo = *(tmp++);
3362 channel.channel_id_hi = *(tmp++);
3363 channel.channel_id_lo = *(tmp++);
3364 m_channels[i]=channel;
3365 // eDebug("%d(%02x) %04x: %02x %02x", i, i, (channel.channel_id_hi << 8) | channel.channel_id_lo, *tmp, *(tmp+1));
3368 for (int i=0; i < num_channels; ++i)
3370 mhw_channel_name_t &channel = m_channels[i];
3371 int channel_name_len=*(tmp++)&0x0f;
3373 for (; x < channel_name_len; ++x)
3374 channel.name[x]=*(tmp++);
3375 channel.name[x+1]=0;
3376 // eDebug("%d(%02x) %s", i, i, channel.name);
3379 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3381 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3384 eDebug("[EPGC] mhw2 themes nyi");
3386 else if (m_MHWFilterMask2.pid == m_mhw2_title_pid && m_MHWFilterMask2.data[0] == 0xe6)
3393 // eDebug("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
3394 // data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10],
3395 // data[11], data[12], data[13], data[14], data[15], data[16], data[17] );
3397 while( pos < dataLen && !valid)
3400 pos += (data[pos] & 0x3F) + 4;
3401 if( pos == dataLen )
3408 eDebug("mhw2 title table invalid!!");
3411 if (!m_MHWTimeoutTimer->isActive())
3413 return; // continue reading
3416 // data seems consistent...
3419 while (pos < dataLen)
3421 // eDebugNoNewLine(" [%02x] %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x [%02x %02x %02x %02x %02x %02x %02x] LL - DESCR - ",
3422 // data[pos], data[pos+1], data[pos+2], data[pos+3], data[pos+4], data[pos+5], data[pos+6], data[pos+7],
3423 // 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]);
3424 title.channel_id = data[pos]+1;
3425 title.mhw2_mjd_hi = data[pos+11];
3426 title.mhw2_mjd_lo = data[pos+12];
3427 title.mhw2_hours = data[pos+13];
3428 title.mhw2_minutes = data[pos+14];
3429 title.mhw2_seconds = data[pos+15];
3430 int duration = ((data[pos+16] << 8)|data[pos+17]) >> 4;
3431 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3432 title.mhw2_duration_lo = duration&0xFF;
3434 // Create unique key per title
3435 __u32 title_id = (data[pos+7] << 24) | (data[pos+8] << 16) | (data[pos+9] << 8) | data[pos+10];
3437 __u8 slen = data[pos+18] & 0x3f;
3438 __u8 *dest = ((__u8*)title.title)-4;
3439 memcpy(dest, &data[pos+19], slen>35 ? 35 : slen);
3440 memset(dest+slen, 0, 35-slen);
3442 // eDebug("%02x [%02x %02x]: %s", data[pos], data[pos+1], data[pos+2], dest);
3444 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3445 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3447 // if (title.channel_id > m_channels.size())
3448 // eDebug("channel_id(%d %02x) to big!!", title.channel_id);
3450 // eDebug("pos %d prog_id %02x %02x chid %02x summary_id %04x dest %p len %d\n",
3451 // pos, title.program_id_ml, title.program_id_lo, title.channel_id, summary_id, dest, slen);
3453 // eDebug("title_id %08x -> summary_id %04x\n", title_id, summary_id);
3457 std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3458 if ( it == m_titles.end() )
3461 m_titles[ title_id ] = title;
3462 if (summary_id != 0xFFFF)
3465 std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3466 while (it != m_program_ids.end() && it->first == summary_id)
3468 if (it->second == title_id) {
3475 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3480 if ( !checkTimeout() )
3481 continue; // Continue reading of the current table.
3489 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3490 if (!m_program_ids.empty())
3492 // Titles table has been read, there are summaries to read.
3493 // Start reading summaries, store corresponding titles on the fly.
3494 startMHWReader2(m_mhw2_summary_pid, 0x96);
3495 startTimeout(15000);
3502 else if (m_MHWFilterMask2.pid == m_mhw2_summary_pid && m_MHWFilterMask2.data[0] == 0x96)
3505 if (!checkTimeout())
3507 int len, loop, pos, lenline;
3516 loop = data[pos] & 0x0f;
3521 for( ; loop > 0; --loop )
3523 if( dataLen > (pos+len) )
3525 lenline = data[pos+len];
3535 return; // continue reading
3539 // data seems consistent...
3540 __u32 summary_id = (data[3]<<8)|data[4];
3541 // eDebug ("summary id %04x\n", summary_id);
3542 // 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] );
3544 // ugly workaround to convert const __u8* to char*
3546 memcpy(&tmp, &data, sizeof(void*));
3551 loop = tmp[pos] & 0x0f;
3553 for( ; loop > 0; loop -- )
3555 lenline = tmp[pos+len];
3564 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3565 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3566 { /* This part is to prevent to looping forever if some summaries are not received yet.
3567 There is a timeout of 4 sec. after the last successfully read summary. */
3568 if ( !m_program_ids.empty() )
3569 return; // Continue reading of the current table.
3573 startTimeout(15000);
3574 std::string the_text = (char *) (data + pos + 1);
3576 // eDebug ("summary id %04x : %s\n", summary_id, data+pos+1);
3578 while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3581 // Find corresponding title, store title and summary in epgcache.
3582 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3583 if ( itTitle != m_titles.end() )
3585 storeTitle( itTitle, the_text, data );
3586 m_titles.erase( itTitle );
3588 m_program_ids.erase( itProgId++ );
3590 if ( !m_program_ids.empty() )
3591 return; // Continue reading of the current table.
3595 return; // continue reading
3598 if (isRunning & eEPGCache::MHW)
3600 if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3602 // Channels table has been read, start reading the themes table.
3603 startMHWReader2(m_mhw2_channel_pid, 0xC8, 1);
3606 else if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3608 // Themes table has been read, start reading the titles table.
3609 startMHWReader2(m_mhw2_title_pid, 0xe6);
3614 // Summaries have been read, titles that have summaries have been stored.
3615 // Now store titles that do not have summaries.
3616 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3617 storeTitle( itTitle, "", data );
3618 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3620 m_program_ids.size());
3627 m_MHWReader2->stop();