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 if (!strlen(m_filename))
239 strncpy(m_filename, path, 1024);
240 eDebug("[EPGC] setCacheFile read/write epg data from/to '%s'", m_filename);
241 if (eDVBLocalTimeHandler::getInstance()->ready())
245 eDebug("[EPGC] setCacheFile already called... ignore '%s'", path);
248 void eEPGCache::timeUpdated()
250 if (strlen(m_filename))
254 eDebug("[EPGC] time updated.. start EPG Mainloop");
256 singleLock s(channel_map_lock);
257 channelMapIterator it = m_knownChannels.begin();
258 for (; it != m_knownChannels.end(); ++it)
260 if (it->second->state == -1) {
262 messages.send(Message(Message::startChannel, it->second));
266 messages.send(Message(Message::timeChanged));
269 eDebug("[EPGC] time updated.. but cache file not set yet.. dont start epg!!");
272 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
276 // eDebug("[eEPGCache] add channel %p", chan);
277 channel_data *data = new channel_data(this);
278 data->channel = chan;
279 data->prevChannelState = -1;
280 #ifdef ENABLE_PRIVATE_EPG
281 data->m_PrivatePid = -1;
283 #ifdef ENABLE_MHW_EPG
284 data->m_mhw2_channel_pid = 0x231; // defaults for astra 19.2 D+
285 data->m_mhw2_title_pid = 0x234; // defaults for astra 19.2 D+
286 data->m_mhw2_summary_pid = 0x236; // defaults for astra 19.2 D+
288 singleLock s(channel_map_lock);
289 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
290 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
294 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
296 channelMapIterator it =
297 m_knownChannels.find(chan);
298 if ( it == m_knownChannels.end() )
299 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
302 channel_data &data = *it->second;
303 ePtr<eDVBResourceManager> res_mgr;
304 if ( eDVBResourceManager::getInstance( res_mgr ) )
305 eDebug("[eEPGCache] no res manager!!");
308 ePtr<iDVBDemux> demux;
309 if ( data.channel->getDemux(demux, 0) )
311 eDebug("[eEPGCache] no demux!!");
316 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
319 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
323 res = demux->createSectionReader( this, data.m_ScheduleReader );
326 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
330 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
333 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
337 res = demux->createSectionReader( this, data.m_ViasatReader );
340 eDebug("[eEPGCache] couldnt initialize viasat reader!!");
343 #ifdef ENABLE_PRIVATE_EPG
344 res = demux->createSectionReader( this, data.m_PrivateReader );
347 eDebug("[eEPGCache] couldnt initialize private reader!!");
351 #ifdef ENABLE_MHW_EPG
352 res = demux->createSectionReader( this, data.m_MHWReader );
355 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
358 res = demux->createSectionReader( this, data.m_MHWReader2 );
361 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
367 messages.send(Message(Message::startChannel, chan));
368 // -> gotMessage -> changedService
375 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
377 channelMapIterator it =
378 m_knownChannels.find(chan);
379 if ( it != m_knownChannels.end() )
382 chan->getState(state);
383 if ( it->second->prevChannelState != state )
387 case iDVBChannel::state_ok:
389 eDebug("[eEPGCache] channel %p running", chan);
390 DVBChannelRunning(chan);
393 case iDVBChannel::state_release:
395 eDebug("[eEPGCache] remove channel %p", chan);
396 if (it->second->state >= 0)
397 messages.send(Message(Message::leaveChannel, chan));
398 pthread_mutex_lock(&it->second->channel_active);
399 singleLock s(channel_map_lock);
400 m_knownChannels.erase(it);
401 pthread_mutex_unlock(&it->second->channel_active);
404 // -> gotMessage -> abortEPG
407 default: // ignore all other events
411 it->second->prevChannelState = state;
416 bool eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
419 timeMap::iterator tmp = tm_it;
420 while ((tmp->first+tmp->second->getDuration()-300) > TM)
423 #ifdef ENABLE_PRIVATE_EPG
424 && tmp->second->type != PRIVATE
427 && tmp->second->type != MHW
431 __u16 event_id = tmp->second->getEventID();
432 servicemap.first.erase(event_id);
434 Event evt((uint8_t*)tmp->second->get());
436 event.parseFrom(&evt, service.sid<<16|service.onid);
437 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
438 service.sid, event_id,
439 event.getBeginTimeString().c_str(),
440 event.getEventName().c_str(),
441 event.getExtendedDescription().c_str());
444 if (tmp == servicemap.second.begin())
446 servicemap.second.erase(tmp);
450 servicemap.second.erase(tmp--);
455 if (tmp == servicemap.second.begin())
462 while(tmp->first < (TM+duration-300))
464 if (tmp->first != TM && tmp->second->type != PRIVATE)
466 __u16 event_id = tmp->second->getEventID();
467 servicemap.first.erase(event_id);
469 Event evt((uint8_t*)tmp->second->get());
471 event.parseFrom(&evt, service.sid<<16|service.onid);
472 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
473 service.sid, event_id,
474 event.getBeginTimeString().c_str(),
475 event.getEventName().c_str(),
476 event.getExtendedDescription().c_str());
479 servicemap.second.erase(tmp++);
484 if (tmp == servicemap.second.end())
490 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
492 eit_t *eit = (eit_t*) data;
494 int len=HILO(eit->section_length)-1;//+3-4;
499 // This fixed the EPG on the Multichoice irdeto systems
500 // the EIT packet is non-compliant.. their EIT packet stinks
501 if ( data[ptr-1] < 0x40 )
504 // Cablecom HACK .. tsid / onid in eit data are incorrect.. so we use
505 // it from running channel (just for current transport stream eit data)
506 bool use_transponder_chid = source == SCHEDULE || (source == NOWNEXT && data[0] == 0x4E);
507 eDVBChannelID chid = channel->channel->getChannelID();
508 uniqueEPGKey service( HILO(eit->service_id),
509 use_transponder_chid ? chid.original_network_id.get() : HILO(eit->original_network_id),
510 use_transponder_chid ? chid.transport_stream_id.get() : HILO(eit->transport_stream_id));
512 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
516 time_t TM = parseDVBtime(
517 eit_event->start_time_1,
518 eit_event->start_time_2,
519 eit_event->start_time_3,
520 eit_event->start_time_4,
521 eit_event->start_time_5);
522 time_t now = ::time(0);
524 if ( TM != 3599 && TM > -1)
525 channel->haveData |= source;
527 singleLock s(cache_lock);
528 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
529 // oder eine durch [] erzeugte
530 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
531 eventMap::iterator prevEventIt = servicemap.first.end();
532 timeMap::iterator prevTimeIt = servicemap.second.end();
537 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
539 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
541 eit_event->start_time_1,
542 eit_event->start_time_2,
543 eit_event->start_time_3,
544 eit_event->start_time_4,
545 eit_event->start_time_5,
551 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
554 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
556 __u16 event_id = HILO(eit_event->event_id);
558 int ev_erase_count = 0;
559 int tm_erase_count = 0;
562 // hack for some polsat services on 13.0E..... but this also replaces other valid event_ids with value 0..
563 // but we dont care about it...
564 event_id = event_hash;
565 eit_event->event_id_hi = event_hash >> 8;
566 eit_event->event_id_lo = event_hash & 0xFF;
569 // search in eventmap
570 eventMap::iterator ev_it =
571 servicemap.first.find(event_id);
573 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
575 // entry with this event_id is already exist ?
576 if ( ev_it != servicemap.first.end() )
578 if ( source > ev_it->second->type ) // update needed ?
579 goto next; // when not.. then skip this entry
581 // search this event in timemap
582 timeMap::iterator tm_it_tmp =
583 servicemap.second.find(ev_it->second->getStartTime());
585 if ( tm_it_tmp != servicemap.second.end() )
587 if ( tm_it_tmp->first == TM ) // just update eventdata
590 eventData *tmp = ev_it->second;
591 ev_it->second = tm_it_tmp->second =
592 new eventData(eit_event, eit_event_size, source);
593 if (FixOverlapping(servicemap, TM, duration, tm_it_tmp, service))
595 prevEventIt = servicemap.first.end();
596 prevTimeIt = servicemap.second.end();
601 else // event has new event begin time
604 // delete the found record from timemap
605 servicemap.second.erase(tm_it_tmp);
606 prevTimeIt=servicemap.second.end();
611 // search in timemap, for check of a case if new time has coincided with time of other event
612 // or event was is not found in eventmap
613 timeMap::iterator tm_it =
614 servicemap.second.find(TM);
616 if ( tm_it != servicemap.second.end() )
618 // event with same start time but another event_id...
619 if ( source > tm_it->second->type &&
620 ev_it == servicemap.first.end() )
621 goto next; // when not.. then skip this entry
623 // search this time in eventmap
624 eventMap::iterator ev_it_tmp =
625 servicemap.first.find(tm_it->second->getEventID());
627 if ( ev_it_tmp != servicemap.first.end() )
630 // delete the found record from eventmap
631 servicemap.first.erase(ev_it_tmp);
632 prevEventIt=servicemap.first.end();
635 evt = new eventData(eit_event, eit_event_size, source);
637 bool consistencyCheck=true;
639 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
642 delete ev_it->second;
643 delete tm_it->second;
647 else if (ev_erase_count == 0 && tm_erase_count > 0)
650 delete ev_it->second;
651 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
654 else if (ev_erase_count > 0 && tm_erase_count == 0)
657 delete tm_it->second;
658 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
661 else // added new eventData
664 consistencyCheck=false;
666 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
667 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
671 if ( consistencyCheck )
673 if ( tm_it->second != evt || ev_it->second != evt )
674 eFatal("tm_it->second != ev_it->second");
675 else if ( tm_it->second->getStartTime() != tm_it->first )
676 eFatal("event start_time(%d) non equal timemap key(%d)",
677 tm_it->second->getStartTime(), tm_it->first );
678 else if ( tm_it->first != TM )
679 eFatal("timemap key(%d) non equal TM(%d)",
681 else if ( ev_it->second->getEventID() != ev_it->first )
682 eFatal("event_id (%d) non equal event_map key(%d)",
683 ev_it->second->getEventID(), ev_it->first);
684 else if ( ev_it->first != event_id )
685 eFatal("eventmap key(%d) non equal event_id(%d)",
686 ev_it->first, event_id );
689 if (FixOverlapping(servicemap, TM, duration, tm_it, service))
691 prevEventIt = servicemap.first.end();
692 prevTimeIt = servicemap.second.end();
697 if ( servicemap.first.size() != servicemap.second.size() )
699 FILE *f = fopen("/hdd/event_map.txt", "w+");
701 for (eventMap::iterator it(servicemap.first.begin())
702 ; it != servicemap.first.end(); ++it )
703 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
704 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
706 f = fopen("/hdd/time_map.txt", "w+");
708 for (timeMap::iterator it(servicemap.second.begin())
709 ; it != servicemap.second.end(); ++it )
710 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
711 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
714 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
715 service.sid, service.tsid, service.onid,
716 servicemap.first.size(), servicemap.second.size() );
719 ptr += eit_event_size;
720 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
724 void eEPGCache::flushEPG(const uniqueEPGKey & s)
726 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
727 singleLock l(cache_lock);
728 if (s) // clear only this service
730 eventCache::iterator it = eventDB.find(s);
731 if ( it != eventDB.end() )
733 eventMap &evMap = it->second.first;
734 timeMap &tmMap = it->second.second;
736 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
741 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
742 #ifdef ENABLE_PRIVATE_EPG
743 contentMaps::iterator it =
744 content_time_tables.find(s);
745 if ( it != content_time_tables.end() )
748 content_time_tables.erase(it);
753 else // clear complete EPG Cache
755 for (eventCache::iterator it(eventDB.begin());
756 it != eventDB.end(); ++it)
758 eventMap &evMap = it->second.first;
759 timeMap &tmMap = it->second.second;
760 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
766 #ifdef ENABLE_PRIVATE_EPG
767 content_time_tables.clear();
769 channelLastUpdated.clear();
770 singleLock m(channel_map_lock);
771 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
772 it->second->startEPG();
774 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
777 void eEPGCache::cleanLoop()
779 singleLock s(cache_lock);
780 if (!eventDB.empty())
782 eDebug("[EPGC] start cleanloop");
784 time_t now = ::time(0);
786 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
788 bool updated = false;
789 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
791 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
793 // remove entry from eventMap
794 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
795 if ( b != DBIt->second.first.end() )
797 // release Heap Memory for this entry (new ....)
798 // eDebug("[EPGC] delete old event (evmap)");
799 DBIt->second.first.erase(b);
802 // remove entry from timeMap
803 // eDebug("[EPGC] release heap mem");
805 DBIt->second.second.erase(It++);
806 // eDebug("[EPGC] delete old event (timeMap)");
812 #ifdef ENABLE_PRIVATE_EPG
815 contentMaps::iterator x =
816 content_time_tables.find( DBIt->first );
817 if ( x != content_time_tables.end() )
819 timeMap &tmMap = DBIt->second.second;
820 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
822 for ( contentTimeMap::iterator it(i->second.begin());
823 it != i->second.end(); )
825 if ( tmMap.find(it->second.first) == tmMap.end() )
826 i->second.erase(it++);
830 if ( i->second.size() )
833 x->second.erase(i++);
839 eDebug("[EPGC] stop cleanloop");
840 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
842 cleanTimer->start(CLEAN_INTERVAL,true);
845 eEPGCache::~eEPGCache()
847 messages.send(Message::quit);
848 kill(); // waiting for thread shutdown
849 singleLock s(cache_lock);
850 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
851 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
855 void eEPGCache::gotMessage( const Message &msg )
860 flushEPG(msg.service);
862 case Message::startChannel:
864 singleLock s(channel_map_lock);
865 channelMapIterator channel =
866 m_knownChannels.find(msg.channel);
867 if ( channel != m_knownChannels.end() )
868 channel->second->startChannel();
871 case Message::leaveChannel:
873 singleLock s(channel_map_lock);
874 channelMapIterator channel =
875 m_knownChannels.find(msg.channel);
876 if ( channel != m_knownChannels.end() )
877 channel->second->abortEPG();
883 #ifdef ENABLE_PRIVATE_EPG
884 case Message::got_private_pid:
886 singleLock s(channel_map_lock);
887 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
889 eDVBChannel *channel = (eDVBChannel*) it->first;
890 channel_data *data = it->second;
891 eDVBChannelID chid = channel->getChannelID();
892 if ( chid.transport_stream_id.get() == msg.service.tsid &&
893 chid.original_network_id.get() == msg.service.onid &&
894 data->m_PrivatePid == -1 )
896 data->m_PrevVersion = -1;
897 data->m_PrivatePid = msg.pid;
898 data->m_PrivateService = msg.service;
899 int onid = chid.original_network_id.get();
900 onid |= 0x80000000; // we use highest bit as private epg indicator
901 chid.original_network_id = onid;
902 updateMap::iterator It = channelLastUpdated.find( chid );
903 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
904 if (update < ZAP_DELAY)
906 data->startPrivateTimer->start(update, 1);
908 eDebug("[EPGC] next private update in %i min", update/60000);
909 else if (update >= 1000)
910 eDebug("[EPGC] next private update in %i sec", update/1000);
917 #ifdef ENABLE_MHW_EPG
918 case Message::got_mhw2_channel_pid:
920 singleLock s(channel_map_lock);
921 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
923 eDVBChannel *channel = (eDVBChannel*) it->first;
924 channel_data *data = it->second;
925 eDVBChannelID chid = channel->getChannelID();
926 if ( chid.transport_stream_id.get() == msg.service.tsid &&
927 chid.original_network_id.get() == msg.service.onid )
929 data->m_mhw2_channel_pid = msg.pid;
930 eDebug("[EPGC] got mhw2 channel pid %04x", msg.pid);
936 case Message::got_mhw2_title_pid:
938 singleLock s(channel_map_lock);
939 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
941 eDVBChannel *channel = (eDVBChannel*) it->first;
942 channel_data *data = it->second;
943 eDVBChannelID chid = channel->getChannelID();
944 if ( chid.transport_stream_id.get() == msg.service.tsid &&
945 chid.original_network_id.get() == msg.service.onid )
947 data->m_mhw2_title_pid = msg.pid;
948 eDebug("[EPGC] got mhw2 title pid %04x", msg.pid);
954 case Message::got_mhw2_summary_pid:
956 singleLock s(channel_map_lock);
957 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
959 eDVBChannel *channel = (eDVBChannel*) it->first;
960 channel_data *data = it->second;
961 eDVBChannelID chid = channel->getChannelID();
962 if ( chid.transport_stream_id.get() == msg.service.tsid &&
963 chid.original_network_id.get() == msg.service.onid )
965 data->m_mhw2_summary_pid = msg.pid;
966 eDebug("[EPGC] got mhw2 summary pid %04x", msg.pid);
973 case Message::timeChanged:
977 eDebug("unhandled EPGCache Message!!");
982 void eEPGCache::thread()
994 void eEPGCache::load()
996 FILE *f = fopen(m_filename, "r");
1004 unsigned int magic=0;
1005 fread( &magic, sizeof(int), 1, f);
1006 if (magic != 0x98765432)
1008 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
1013 fread( text1, 13, 1, f);
1014 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
1016 singleLock s(cache_lock);
1017 fread( &size, sizeof(int), 1, f);
1024 fread( &key, sizeof(uniqueEPGKey), 1, f);
1025 fread( &size, sizeof(int), 1, f);
1031 fread( &type, sizeof(__u8), 1, f);
1032 fread( &len, sizeof(__u8), 1, f);
1033 event = new eventData(0, len, type);
1034 event->EITdata = new __u8[len];
1035 eventData::CacheSize+=len;
1036 fread( event->EITdata, len, 1, f);
1037 evMap[ event->getEventID() ]=event;
1038 tmMap[ event->getStartTime() ]=event;
1041 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
1044 eDebug("[EPGC] %d events read from %s", cnt, m_filename);
1045 #ifdef ENABLE_PRIVATE_EPG
1047 fread( text2, 11, 1, f);
1048 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
1051 fread( &size, sizeof(int), 1, f);
1056 fread( &key, sizeof(uniqueEPGKey), 1, f);
1057 eventMap &evMap=eventDB[key].first;
1058 fread( &size, sizeof(int), 1, f);
1063 fread( &content_id, sizeof(int), 1, f);
1064 fread( &size, sizeof(int), 1, f);
1067 time_t time1, time2;
1069 fread( &time1, sizeof(time_t), 1, f);
1070 fread( &time2, sizeof(time_t), 1, f);
1071 fread( &event_id, sizeof(__u16), 1, f);
1072 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
1073 eventMap::iterator it =
1074 evMap.find(event_id);
1075 if (it != evMap.end())
1076 it->second->type = PRIVATE;
1081 #endif // ENABLE_PRIVATE_EPG
1084 eDebug("[EPGC] don't read old epg database");
1090 void eEPGCache::save()
1092 /* create empty file */
1093 FILE *f = fopen(m_filename, "w");
1097 eDebug("[EPGC] couldn't save epg data to '%s'(%m)", m_filename);
1101 char *buf = realpath(m_filename, NULL);
1104 eDebug("[EPGC] realpath to '%s' failed in save (%m)", m_filename);
1109 eDebug("[EPGC] store epg to realpath '%s'", buf);
1113 if (statfs(buf, &s) < 0) {
1114 eDebug("[EPGC] statfs '%s' failed in save (%m)", buf);
1121 // check for enough free space on storage
1124 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
1126 eDebug("[EPGC] not enough free space at path '%s' %lld bytes availd but %d needed", buf, tmp, (eventData::CacheSize*12)/10);
1132 unsigned int magic = 0x98765432;
1133 fwrite( &magic, sizeof(int), 1, f);
1134 const char *text = "UNFINISHED_V7";
1135 fwrite( text, 13, 1, f );
1136 int size = eventDB.size();
1137 fwrite( &size, sizeof(int), 1, f );
1138 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1140 timeMap &timemap = service_it->second.second;
1141 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1142 size = timemap.size();
1143 fwrite( &size, sizeof(int), 1, f);
1144 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1146 __u8 len = time_it->second->ByteSize;
1147 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1148 fwrite( &len, sizeof(__u8), 1, f);
1149 fwrite( time_it->second->EITdata, len, 1, f);
1153 eDebug("[EPGC] %d events written to %s", cnt, m_filename);
1155 #ifdef ENABLE_PRIVATE_EPG
1156 const char* text3 = "PRIVATE_EPG";
1157 fwrite( text3, 11, 1, f );
1158 size = content_time_tables.size();
1159 fwrite( &size, sizeof(int), 1, f);
1160 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1162 contentMap &content_time_table = a->second;
1163 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1164 int size = content_time_table.size();
1165 fwrite( &size, sizeof(int), 1, f);
1166 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1168 int size = i->second.size();
1169 fwrite( &i->first, sizeof(int), 1, f);
1170 fwrite( &size, sizeof(int), 1, f);
1171 for ( contentTimeMap::iterator it(i->second.begin());
1172 it != i->second.end(); ++it )
1174 fwrite( &it->first, sizeof(time_t), 1, f);
1175 fwrite( &it->second.first, sizeof(time_t), 1, f);
1176 fwrite( &it->second.second, sizeof(__u16), 1, f);
1181 // write version string after binary data
1182 // has been written to disk.
1184 fseek(f, sizeof(int), SEEK_SET);
1185 fwrite("ENIGMA_EPG_V7", 13, 1, f);
1189 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1191 ,abortTimer(eTimer::create(ml)), zapTimer(eTimer::create(ml)), state(-1)
1192 ,isRunning(0), haveData(0)
1193 #ifdef ENABLE_PRIVATE_EPG
1194 ,startPrivateTimer(eTimer::create(ml))
1196 #ifdef ENABLE_MHW_EPG
1197 ,m_MHWTimeoutTimer(eTimer::create(ml))
1200 #ifdef ENABLE_MHW_EPG
1201 CONNECT(m_MHWTimeoutTimer->timeout, eEPGCache::channel_data::MHWTimeout);
1203 CONNECT(zapTimer->timeout, eEPGCache::channel_data::startEPG);
1204 CONNECT(abortTimer->timeout, eEPGCache::channel_data::abortNonAvail);
1205 #ifdef ENABLE_PRIVATE_EPG
1206 CONNECT(startPrivateTimer->timeout, eEPGCache::channel_data::startPrivateReader);
1208 pthread_mutex_init(&channel_active, 0);
1211 bool eEPGCache::channel_data::finishEPG()
1213 if (!isRunning) // epg ready
1215 eDebug("[EPGC] stop caching events(%ld)", ::time(0));
1216 zapTimer->start(UPDATE_INTERVAL, 1);
1217 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1218 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1220 seenSections[i].clear();
1221 calcedSections[i].clear();
1223 singleLock l(cache->cache_lock);
1224 cache->channelLastUpdated[channel->getChannelID()] = ::time(0);
1225 #ifdef ENABLE_MHW_EPG
1233 void eEPGCache::channel_data::startEPG()
1235 eDebug("[EPGC] start caching events(%ld)", ::time(0));
1238 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1240 seenSections[i].clear();
1241 calcedSections[i].clear();
1244 eDVBSectionFilterMask mask;
1245 memset(&mask, 0, sizeof(mask));
1247 #ifdef ENABLE_MHW_EPG
1249 mask.data[0] = 0x91;
1250 mask.mask[0] = 0xFF;
1251 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1252 m_MHWReader->start(mask);
1254 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1256 mask.pid = m_mhw2_channel_pid;
1257 mask.data[0] = 0xC8;
1258 mask.mask[0] = 0xFF;
1260 mask.mask[1] = 0xFF;
1261 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1262 m_MHWReader2->start(mask);
1264 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1267 m_MHWTimeoutet=false;
1271 mask.flags = eDVBSectionFilterMask::rfCRC;
1273 mask.data[0] = 0x4E;
1274 mask.mask[0] = 0xFE;
1275 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1276 m_NowNextReader->start(mask);
1277 isRunning |= NOWNEXT;
1279 mask.data[0] = 0x50;
1280 mask.mask[0] = 0xF0;
1281 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1282 m_ScheduleReader->start(mask);
1283 isRunning |= SCHEDULE;
1285 mask.data[0] = 0x60;
1286 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1287 m_ScheduleOtherReader->start(mask);
1288 isRunning |= SCHEDULE_OTHER;
1292 mask.data[0] = 0x40;
1293 mask.mask[0] = 0x40;
1294 m_ViasatReader->connectRead(slot(*this, &eEPGCache::channel_data::readDataViasat), m_ViasatConn);
1295 m_ViasatReader->start(mask);
1296 isRunning |= VIASAT;
1298 abortTimer->start(7000,true);
1301 void eEPGCache::channel_data::abortNonAvail()
1305 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1307 eDebug("[EPGC] abort non avail nownext reading");
1308 isRunning &= ~NOWNEXT;
1309 m_NowNextReader->stop();
1312 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1314 eDebug("[EPGC] abort non avail schedule reading");
1315 isRunning &= ~SCHEDULE;
1316 m_ScheduleReader->stop();
1319 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1321 eDebug("[EPGC] abort non avail schedule other reading");
1322 isRunning &= ~SCHEDULE_OTHER;
1323 m_ScheduleOtherReader->stop();
1324 m_ScheduleOtherConn=0;
1326 if ( !(haveData&VIASAT) && (isRunning&VIASAT) )
1328 eDebug("[EPGC] abort non avail viasat reading");
1329 isRunning &= ~VIASAT;
1330 m_ViasatReader->stop();
1333 #ifdef ENABLE_MHW_EPG
1334 if ( !(haveData&MHW) && (isRunning&MHW) )
1336 eDebug("[EPGC] abort non avail mhw reading");
1338 m_MHWReader->stop();
1340 m_MHWReader2->stop();
1344 if ( isRunning & VIASAT )
1345 abortTimer->start(300000, true);
1346 else if ( isRunning )
1347 abortTimer->start(90000, true);
1351 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1353 seenSections[i].clear();
1354 calcedSections[i].clear();
1361 void eEPGCache::channel_data::startChannel()
1363 pthread_mutex_lock(&channel_active);
1364 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1366 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (::time(0)-It->second) * 1000 ) ) : ZAP_DELAY );
1368 if (update < ZAP_DELAY)
1371 zapTimer->start(update, 1);
1372 if (update >= 60000)
1373 eDebug("[EPGC] next update in %i min", update/60000);
1374 else if (update >= 1000)
1375 eDebug("[EPGC] next update in %i sec", update/1000);
1378 void eEPGCache::channel_data::abortEPG()
1380 for (unsigned int i=0; i < sizeof(seenSections)/sizeof(tidMap); ++i)
1382 seenSections[i].clear();
1383 calcedSections[i].clear();
1389 eDebug("[EPGC] abort caching events !!");
1390 if (isRunning & SCHEDULE)
1392 isRunning &= ~SCHEDULE;
1393 m_ScheduleReader->stop();
1396 if (isRunning & NOWNEXT)
1398 isRunning &= ~NOWNEXT;
1399 m_NowNextReader->stop();
1402 if (isRunning & SCHEDULE_OTHER)
1404 isRunning &= ~SCHEDULE_OTHER;
1405 m_ScheduleOtherReader->stop();
1406 m_ScheduleOtherConn=0;
1408 if (isRunning & VIASAT)
1410 isRunning &= ~VIASAT;
1411 m_ViasatReader->stop();
1414 #ifdef ENABLE_MHW_EPG
1415 if (isRunning & MHW)
1418 m_MHWReader->stop();
1420 m_MHWReader2->stop();
1425 #ifdef ENABLE_PRIVATE_EPG
1426 if (m_PrivateReader)
1427 m_PrivateReader->stop();
1431 pthread_mutex_unlock(&channel_active);
1435 void eEPGCache::channel_data::readDataViasat( const __u8 *data)
1438 memcpy(&d, &data, sizeof(__u8*));
1443 void eEPGCache::channel_data::readData( const __u8 *data)
1447 iDVBSectionReader *reader=NULL;
1451 reader=m_NowNextReader;
1456 reader=m_ScheduleReader;
1461 reader=m_ScheduleOtherReader;
1462 source=SCHEDULE_OTHER;
1467 reader=m_ViasatReader;
1472 eDebug("[EPGC] unknown table_id !!!");
1475 tidMap &seenSections = this->seenSections[map];
1476 tidMap &calcedSections = this->calcedSections[map];
1477 if ( (state == 1 && calcedSections == seenSections) || state > 1 )
1479 eDebugNoNewLine("[EPGC] ");
1484 eDebugNoNewLine("nownext");
1488 eDebugNoNewLine("schedule");
1490 case SCHEDULE_OTHER:
1491 m_ScheduleOtherConn=0;
1492 eDebugNoNewLine("schedule other");
1496 eDebugNoNewLine("viasat");
1498 default: eDebugNoNewLine("unknown");break;
1500 eDebug(" finished(%ld)", ::time(0));
1503 isRunning &= ~source;
1509 eit_t *eit = (eit_t*) data;
1510 __u32 sectionNo = data[0] << 24;
1511 sectionNo |= data[3] << 16;
1512 sectionNo |= data[4] << 8;
1513 sectionNo |= eit->section_number;
1515 tidMap::iterator it =
1516 seenSections.find(sectionNo);
1518 if ( it == seenSections.end() )
1520 seenSections.insert(sectionNo);
1521 calcedSections.insert(sectionNo);
1522 __u32 tmpval = sectionNo & 0xFFFFFF00;
1523 __u8 incr = source == NOWNEXT ? 1 : 8;
1524 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1526 if ( i == eit->section_number )
1528 for (int x=i; x <= eit->segment_last_section_number; ++x)
1529 calcedSections.insert(tmpval|(x&0xFF));
1532 calcedSections.insert(tmpval|(i&0xFF));
1534 cache->sectionRead(data, source, this);
1539 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1540 // if t == -1 we search the current event...
1542 singleLock s(cache_lock);
1543 uniqueEPGKey key(handleGroup(service));
1545 // check if EPG for this service is ready...
1546 eventCache::iterator It = eventDB.find( key );
1547 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1551 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1552 It->second.second.upper_bound(t); // just >
1553 if ( i != It->second.second.end() )
1555 if ( direction < 0 || (direction == 0 && i->first > t) )
1557 timeMap::iterator x = i;
1559 if ( x != It->second.second.end() )
1561 time_t start_time = x->first;
1566 if (t > (start_time+x->second->getDuration()))
1581 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1583 singleLock s(cache_lock);
1584 const eventData *data=0;
1585 RESULT ret = lookupEventTime(service, t, data, direction);
1587 result = data->get();
1591 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1593 singleLock s(cache_lock);
1594 const eventData *data=0;
1595 RESULT ret = lookupEventTime(service, t, data, direction);
1597 result = new Event((uint8_t*)data->get());
1601 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1603 singleLock s(cache_lock);
1604 const eventData *data=0;
1605 RESULT ret = lookupEventTime(service, t, data, direction);
1608 Event ev((uint8_t*)data->get());
1609 result = new eServiceEvent();
1610 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1611 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1616 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1618 singleLock s(cache_lock);
1619 uniqueEPGKey key(handleGroup(service));
1621 eventCache::iterator It = eventDB.find( key );
1622 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1624 eventMap::iterator i( It->second.first.find( event_id ));
1625 if ( i != It->second.first.end() )
1633 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1639 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1641 singleLock s(cache_lock);
1642 const eventData *data=0;
1643 RESULT ret = lookupEventId(service, event_id, data);
1645 result = data->get();
1649 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1651 singleLock s(cache_lock);
1652 const eventData *data=0;
1653 RESULT ret = lookupEventId(service, event_id, data);
1655 result = new Event((uint8_t*)data->get());
1659 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1661 singleLock s(cache_lock);
1662 const eventData *data=0;
1663 RESULT ret = lookupEventId(service, event_id, data);
1666 Event ev((uint8_t*)data->get());
1667 result = new eServiceEvent();
1668 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1669 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1674 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1676 singleLock s(cache_lock);
1677 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1680 eventCache::iterator It = eventDB.find(ref);
1681 if ( It != eventDB.end() && It->second.second.size() )
1683 m_timemap_cursor = It->second.second.lower_bound(begin);
1684 if ( m_timemap_cursor != It->second.second.end() )
1686 if ( m_timemap_cursor->first != begin )
1688 timeMap::iterator x = m_timemap_cursor;
1690 if ( x != It->second.second.end() )
1692 time_t start_time = x->first;
1693 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1694 m_timemap_cursor = x;
1700 m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1702 m_timemap_end = It->second.second.end();
1704 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1705 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1710 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1712 if ( m_timemap_cursor != m_timemap_end )
1714 result = m_timemap_cursor++->second;
1720 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1722 if ( m_timemap_cursor != m_timemap_end )
1724 result = m_timemap_cursor++->second->get();
1730 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1732 if ( m_timemap_cursor != m_timemap_end )
1734 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1740 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1742 if ( m_timemap_cursor != m_timemap_end )
1744 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1745 result = new eServiceEvent();
1746 return result->parseFrom(&ev, currentQueryTsidOnid);
1751 void fillTuple(ePyObject tuple, const char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1756 while(spos < argcount)
1758 bool inc_refcount=false;
1759 switch((c=argstring[spos++]))
1761 case '0': // PyLong 0
1762 tmp = PyLong_FromLong(0);
1764 case 'I': // Event Id
1765 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1767 case 'B': // Event Begin Time
1768 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1770 case 'D': // Event Duration
1771 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1773 case 'T': // Event Title
1774 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1776 case 'S': // Event Short Description
1777 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1779 case 'E': // Event Extended Description
1780 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1782 case 'C': // Current Time
1784 inc_refcount = true;
1786 case 'R': // service reference string
1788 inc_refcount = true;
1790 case 'n': // short service name
1791 case 'N': // service name
1793 inc_refcount = true;
1798 default: // ignore unknown
1800 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1805 inc_refcount = true;
1809 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1813 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1817 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1818 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1822 Py_DECREF(service_name);
1825 Py_DECREF(convertFuncArgs);
1826 Py_DECREF(dest_list);
1827 PyErr_SetString(PyExc_StandardError,
1828 "error in convertFunc execute");
1829 eDebug("error in convertFunc execute");
1832 PyList_Append(dest_list, result);
1837 ePyObject tuple = PyTuple_New(argcount);
1838 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1839 PyList_Append(dest_list, tuple);
1845 // here we get a python list
1846 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1849 // B = Event Begin Time
1850 // D = Event Duration
1852 // S = Event Short Description
1853 // E = Event Extended Description
1855 // R = Service Reference
1857 // n = Short Service Name
1858 // X = Return a minimum of one tuple per service in the result list... even when no event was found.
1859 // The returned tuple is filled with all available infos... non avail is filled as None
1860 // The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1861 // then for each service follows a tuple
1862 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1863 // the second is the type of query
1865 // -1 = event before given start_time
1866 // 0 = event intersects given start_time
1867 // +1 = event after given start_time
1869 // when type is eventid it is the event_id
1870 // when type is time then it is the start_time ( -1 for now_time )
1871 // the fourth is the end_time .. ( optional .. for query all events in time range)
1873 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1875 ePyObject convertFuncArgs;
1877 const char *argstring=NULL;
1878 if (!PyList_Check(list))
1880 PyErr_SetString(PyExc_StandardError,
1886 int listSize=PyList_Size(list);
1889 PyErr_SetString(PyExc_StandardError,
1890 "not params given");
1891 eDebug("not params given");
1896 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1897 if (PyString_Check(argv))
1899 argstring = PyString_AS_STRING(argv);
1903 argstring = "I"; // just event id as default
1904 argcount = strlen(argstring);
1905 // eDebug("have %d args('%s')", argcount, argstring);
1908 bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1914 if (!PyCallable_Check(convertFunc))
1916 PyErr_SetString(PyExc_StandardError,
1917 "convertFunc must be callable");
1918 eDebug("convertFunc is not callable");
1921 convertFuncArgs = PyTuple_New(argcount);
1924 ePyObject nowTime = strchr(argstring, 'C') ?
1925 PyLong_FromLong(::time(0)) :
1928 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1931 ePyObject dest_list=PyList_New(0);
1932 while(listSize > listIt)
1934 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1935 if (PyTuple_Check(item))
1937 bool service_changed=false;
1942 int tupleSize=PyTuple_Size(item);
1945 while(tupleSize > tupleIt) // parse query args
1947 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1952 if (!PyString_Check(entry))
1954 eDebug("tuple entry 0 is no a string");
1961 type=PyInt_AsLong(entry);
1962 if (type < -1 || type > 2)
1964 eDebug("unknown type %d", type);
1969 event_id=stime=PyInt_AsLong(entry);
1972 minutes=PyInt_AsLong(entry);
1975 eDebug("unneeded extra argument");
1980 if (minutes && stime == -1)
1983 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1984 if (ref.type != eServiceReference::idDVB)
1986 eDebug("service reference for epg query is not valid");
1990 // redirect subservice querys to parent service
1991 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1992 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1994 eServiceCenterPtr service_center;
1995 if (!eServiceCenter::getPrivInstance(service_center))
1997 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1998 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1999 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
2000 dvb_ref.setParentServiceID(eServiceID(0));
2002 service = PyString_FromString(dvb_ref.toString().c_str());
2003 service_changed = true;
2007 ePyObject service_name;
2008 if (must_get_service_name)
2010 ePtr<iStaticServiceInformation> sptr;
2011 eServiceCenterPtr service_center;
2012 eServiceCenter::getPrivInstance(service_center);
2015 service_center->info(ref, sptr);
2019 sptr->getName(ref, name);
2021 if (must_get_service_name == 1)
2024 // filter short name brakets
2025 while((pos = name.find("\xc2\x86")) != std::string::npos)
2027 while((pos = name.find("\xc2\x87")) != std::string::npos)
2031 name = buildShortName(name);
2034 service_name = PyString_FromString(name.c_str());
2038 service_name = PyString_FromString("<n/a>");
2042 singleLock s(cache_lock);
2043 if (!startTimeQuery(ref, stime, minutes))
2045 while ( m_timemap_cursor != m_timemap_end )
2047 Event ev((uint8_t*)m_timemap_cursor++->second->get());
2049 evt.parseFrom(&ev, currentQueryTsidOnid);
2050 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2054 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2060 const eventData *ev_data=0;
2063 singleLock s(cache_lock);
2065 lookupEventId(ref, event_id, ev_data);
2067 lookupEventTime(ref, stime, ev_data, type);
2070 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2071 Event ev((uint8_t*)ev_data->get());
2072 evt.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2077 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2080 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
2083 if (service_changed)
2086 Py_DECREF(service_name);
2091 if (convertFuncArgs)
2092 Py_DECREF(convertFuncArgs);
2098 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2102 while(pos < argcount)
2104 bool inc_refcount=false;
2105 switch(argstring[pos])
2107 case '0': // PyLong 0
2108 tmp = PyLong_FromLong(0);
2110 case 'I': // Event Id
2111 tmp = PyLong_FromLong(evData->getEventID());
2113 case 'B': // Event Begin Time
2115 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2117 tmp = PyLong_FromLong(evData->getStartTime());
2119 case 'D': // Event Duration
2121 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2123 tmp = PyLong_FromLong(evData->getDuration());
2125 case 'T': // Event Title
2126 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2128 case 'S': // Event Short Description
2129 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2131 case 'E': // Event Extended Description
2132 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2134 case 'R': // service reference string
2135 tmp = service_reference;
2136 inc_refcount = true;
2138 case 'n': // short service name
2139 case 'N': // service name
2141 inc_refcount = true;
2143 default: // ignore unknown
2145 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2150 inc_refcount = true;
2154 PyTuple_SET_ITEM(tuple, pos++, tmp);
2158 // here we get a python tuple
2159 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2161 // B = Event Begin Time
2162 // D = Event Duration
2164 // S = Event Short Description
2165 // E = Event Extended Description
2166 // R = Service Reference
2168 // n = Short Service Name
2169 // the second tuple entry is the MAX matches value
2170 // the third tuple entry is the type of query
2171 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2172 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2173 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2174 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2175 // the fourth is the servicereference string
2176 // the fifth is the eventid
2177 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2178 // the fourth is the search text
2180 // 0 = case sensitive (CASE_CHECK)
2181 // 1 = case insensitive (NO_CASECHECK)
2183 PyObject *eEPGCache::search(ePyObject arg)
2189 const char *argstring=0;
2193 bool needServiceEvent=false;
2195 int must_get_service_name = 0;
2196 bool must_get_service_reference = false;
2198 if (PyTuple_Check(arg))
2200 int tuplesize=PyTuple_Size(arg);
2203 ePyObject obj = PyTuple_GET_ITEM(arg,0);
2204 if (PyString_Check(obj))
2206 #if PY_VERSION_HEX < 0x02060000
2207 argcount = PyString_GET_SIZE(obj);
2209 argcount = PyString_Size(obj);
2211 argstring = PyString_AS_STRING(obj);
2212 for (int i=0; i < argcount; ++i)
2213 switch(argstring[i])
2218 needServiceEvent=true;
2221 must_get_service_name = 1;
2224 must_get_service_name = 2;
2227 must_get_service_reference = true;
2235 PyErr_SetString(PyExc_StandardError,
2237 eDebug("tuple arg 0 is not a string");
2242 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2245 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2246 if (tuplesize > 4 && querytype == 0)
2248 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2249 if (PyString_Check(obj))
2251 refstr = PyString_AS_STRING(obj);
2252 eServiceReferenceDVB ref(refstr);
2255 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2256 singleLock s(cache_lock);
2257 const eventData *evData = 0;
2258 lookupEventId(ref, eventid, evData);
2261 __u8 *data = evData->EITdata;
2262 int tmp = evData->ByteSize-10;
2263 __u32 *p = (__u32*)(data+10);
2264 // search short and extended event descriptors
2268 descriptorMap::iterator it =
2269 eventData::descriptors.find(crc);
2270 if (it != eventData::descriptors.end())
2272 __u8 *descr_data = it->second.second;
2273 switch(descr_data[0])
2276 descr[++descridx]=crc;
2285 eDebug("event not found");
2289 PyErr_SetString(PyExc_StandardError, "type error");
2290 eDebug("tuple arg 4 is not a valid service reference string");
2296 PyErr_SetString(PyExc_StandardError, "type error");
2297 eDebug("tuple arg 4 is not a string");
2301 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2303 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2304 if (PyString_Check(obj))
2306 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2307 const char *str = PyString_AS_STRING(obj);
2308 #if PY_VERSION_HEX < 0x02060000
2309 int textlen = PyString_GET_SIZE(obj);
2311 int textlen = PyString_Size(obj);
2314 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2316 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2317 singleLock s(cache_lock);
2318 for (descriptorMap::iterator it(eventData::descriptors.begin());
2319 it != eventData::descriptors.end() && descridx < 511; ++it)
2321 __u8 *data = it->second.second;
2322 if ( data[0] == 0x4D ) // short event descriptor
2324 int title_len = data[5];
2325 if ( querytype == 1 )
2328 // skip DVB-Text Encoding!
2329 if (data[6] == 0x10)
2334 else if(data[6] > 0 && data[6] < 0x20)
2339 if (title_len != textlen)
2343 if ( !strncasecmp((const char*)data+offs, str, title_len) )
2345 // std::string s((const char*)data+offs, title_len);
2346 // eDebug("match1 %s %s", str, s.c_str() );
2347 descr[++descridx] = it->first;
2350 else if ( !strncmp((const char*)data+offs, str, title_len) )
2352 // std::string s((const char*)data+offs, title_len);
2353 // eDebug("match2 %s %s", str, s.c_str() );
2354 descr[++descridx] = it->first;
2360 while((title_len-idx) >= textlen)
2364 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2366 descr[++descridx] = it->first;
2367 // std::string s((const char*)data+6, title_len);
2368 // eDebug("match 3 %s %s", str, s.c_str() );
2372 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2374 descr[++descridx] = it->first;
2375 // std::string s((const char*)data+6, title_len);
2376 // eDebug("match 4 %s %s", str, s.c_str() );
2387 PyErr_SetString(PyExc_StandardError,
2389 eDebug("tuple arg 4 is not a string");
2395 PyErr_SetString(PyExc_StandardError,
2397 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2403 PyErr_SetString(PyExc_StandardError,
2405 eDebug("not enough args in tuple");
2411 PyErr_SetString(PyExc_StandardError,
2413 eDebug("arg 0 is not a tuple");
2419 int maxcount=maxmatches;
2420 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2421 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2422 // in this case we start searching with the base service
2423 bool first = ref.valid() ? true : false;
2424 singleLock s(cache_lock);
2425 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2426 while(cit != eventDB.end() && maxcount)
2428 if ( ref.valid() && !first && cit->first == ref )
2430 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2434 ePyObject service_name;
2435 ePyObject service_reference;
2436 timeMap &evmap = cit->second.second;
2438 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2440 int evid = evit->second->getEventID();
2441 if ( evid == eventid)
2443 __u8 *data = evit->second->EITdata;
2444 int tmp = evit->second->ByteSize-10;
2445 __u32 *p = (__u32*)(data+10);
2446 // check if any of our descriptor used by this event
2451 for ( int i=0; i <= descridx; ++i)
2453 if (descr[i] == crc32) // found...
2458 if ( (querytype == 0 && cnt == descridx) ||
2459 ((querytype == 1 || querytype == 2) && cnt != -1) )
2461 const uniqueEPGKey &service = cit->first;
2462 eServiceReference ref =
2463 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2466 // create servive event
2468 const eventData *ev_data=0;
2469 if (needServiceEvent)
2471 if (lookupEventId(ref, evid, ev_data))
2472 eDebug("event not found !!!!!!!!!!!");
2475 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2476 Event ev((uint8_t*)ev_data->get());
2477 ptr.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2480 // create service name
2481 if (must_get_service_name && !service_name)
2483 ePtr<iStaticServiceInformation> sptr;
2484 eServiceCenterPtr service_center;
2485 eServiceCenter::getPrivInstance(service_center);
2488 service_center->info(ref, sptr);
2492 sptr->getName(ref, name);
2494 if (must_get_service_name == 1)
2497 // filter short name brakets
2498 while((pos = name.find("\xc2\x86")) != std::string::npos)
2500 while((pos = name.find("\xc2\x87")) != std::string::npos)
2504 name = buildShortName(name);
2507 service_name = PyString_FromString(name.c_str());
2511 service_name = PyString_FromString("<n/a>");
2513 // create servicereference string
2514 if (must_get_service_reference && !service_reference)
2515 service_reference = PyString_FromString(ref.toString().c_str());
2518 ret = PyList_New(0);
2520 ePyObject tuple = PyTuple_New(argcount);
2522 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2523 PyList_Append(ret, tuple);
2530 Py_DECREF(service_name);
2531 if (service_reference)
2532 Py_DECREF(service_reference);
2535 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2537 cit=eventDB.begin();
2550 #ifdef ENABLE_PRIVATE_EPG
2551 #include <dvbsi++/descriptor_tag.h>
2552 #include <dvbsi++/unknown_descriptor.h>
2553 #include <dvbsi++/private_data_specifier_descriptor.h>
2555 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2557 ePtr<eTable<ProgramMapSection> > ptr;
2558 if (!pmthandler->getPMT(ptr) && ptr)
2560 std::vector<ProgramMapSection*>::const_iterator i;
2561 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2563 const ProgramMapSection &pmt = **i;
2565 ElementaryStreamInfoConstIterator es;
2566 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2569 switch ((*es)->getType())
2571 case 0xC1: // user private
2572 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2573 desc != (*es)->getDescriptors()->end(); ++desc)
2575 switch ((*desc)->getTag())
2577 case 0xC2: // user defined
2578 if ((*desc)->getLength() == 8)
2581 (*desc)->writeToBuffer(buffer);
2582 if (!strncmp((const char *)buffer+2, "EPGDATA", 7))
2584 eServiceReferenceDVB ref;
2585 if (!pmthandler->getServiceReference(ref))
2587 int pid = (*es)->getPid();
2588 messages.send(Message(Message::got_mhw2_channel_pid, ref, pid));
2591 else if(!strncmp((const char *)buffer+2, "FICHAS", 6))
2593 eServiceReferenceDVB ref;
2594 if (!pmthandler->getServiceReference(ref))
2596 int pid = (*es)->getPid();
2597 messages.send(Message(Message::got_mhw2_summary_pid, ref, pid));
2600 else if(!strncmp((const char *)buffer+2, "GENEROS", 7))
2602 eServiceReferenceDVB ref;
2603 if (!pmthandler->getServiceReference(ref))
2605 int pid = (*es)->getPid();
2606 messages.send(Message(Message::got_mhw2_title_pid, ref, pid));
2615 case 0x05: // private
2616 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2617 desc != (*es)->getDescriptors()->end(); ++desc)
2619 switch ((*desc)->getTag())
2621 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2622 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2627 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2628 int descr_len = descr->getLength();
2631 uint8_t data[descr_len+2];
2632 descr->writeToBuffer(data);
2633 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2647 eServiceReferenceDVB ref;
2648 if (!pmthandler->getServiceReference(ref))
2650 int pid = (*es)->getPid();
2651 messages.send(Message(Message::got_private_pid, ref, pid));
2659 eDebug("PMTready but no pmt!!");
2666 date_time( const date_time &a )
2668 memcpy(data, a.data, 5);
2671 date_time( const __u8 data[5])
2673 memcpy(this->data, data, 5);
2674 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2679 const __u8& operator[](int pos) const
2685 struct less_datetime
2687 bool operator()( const date_time &a, const date_time &b ) const
2689 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2693 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2695 contentMap &content_time_table = content_time_tables[current_service];
2696 singleLock s(cache_lock);
2697 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2698 eventMap &evMap = eventDB[current_service].first;
2699 timeMap &tmMap = eventDB[current_service].second;
2701 int content_id = data[ptr++] << 24;
2702 content_id |= data[ptr++] << 16;
2703 content_id |= data[ptr++] << 8;
2704 content_id |= data[ptr++];
2706 contentTimeMap &time_event_map =
2707 content_time_table[content_id];
2708 for ( contentTimeMap::iterator it( time_event_map.begin() );
2709 it != time_event_map.end(); ++it )
2711 eventMap::iterator evIt( evMap.find(it->second.second) );
2712 if ( evIt != evMap.end() )
2714 delete evIt->second;
2717 tmMap.erase(it->second.first);
2719 time_event_map.clear();
2722 memcpy(duration, data+ptr, 3);
2725 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2727 const __u8 *descriptors[65];
2728 const __u8 **pdescr = descriptors;
2730 int descriptors_length = (data[ptr++]&0x0F) << 8;
2731 descriptors_length |= data[ptr++];
2732 while ( descriptors_length > 1 )
2734 int descr_type = data[ptr];
2735 int descr_len = data[ptr+1];
2736 descriptors_length -= 2;
2737 if (descriptors_length >= descr_len)
2739 descriptors_length -= descr_len;
2740 if ( descr_type == 0xf2 && descr_len > 5)
2743 int tsid = data[ptr++] << 8;
2744 tsid |= data[ptr++];
2745 int onid = data[ptr++] << 8;
2746 onid |= data[ptr++];
2747 int sid = data[ptr++] << 8;
2750 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2753 switch( (tsid << 16) | sid )
2755 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2756 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2757 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2758 case 0x0300f5: sid = 0xdc; break;
2759 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2760 case 0x1100d3: sid = 0xe3; break;
2761 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2764 ////////////////////////////////////////////
2766 uniqueEPGKey service( sid, onid, tsid );
2768 while( descr_len > 2 )
2771 datetime[0] = data[ptr++];
2772 datetime[1] = data[ptr++];
2773 int tmp_len = data[ptr++];
2775 if (descr_len >= tmp_len)
2777 descr_len -= tmp_len;
2778 while( tmp_len > 2 )
2780 memcpy(datetime+2, data+ptr, 3);
2783 start_times[datetime].push_back(service);
2796 ASSERT(pdescr <= &descriptors[65]);
2798 eit_event_struct *ev_struct = (eit_event_struct*) event;
2799 ev_struct->running_status = 0;
2800 ev_struct->free_CA_mode = 1;
2801 memcpy(event+7, duration, 3);
2803 const __u8 **d=descriptors;
2804 while ( d < pdescr )
2806 memcpy(event+ptr, *d, ((*d)[1])+2);
2810 ASSERT(ptr <= 4098);
2811 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2813 time_t now = ::time(0);
2814 if ( (it->first.tm + duration_sec) < now )
2816 memcpy(event+2, it->first.data, 5);
2819 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2821 event[bptr++] = 0x4A;
2822 __u8 *len = event+(bptr++);
2823 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2824 event[bptr++] = (i->tsid & 0xFF);
2825 event[bptr++] = (i->onid & 0xFF00) >> 8;
2826 event[bptr++] = (i->onid & 0xFF);
2827 event[bptr++] = (i->sid & 0xFF00) >> 8;
2828 event[bptr++] = (i->sid & 0xFF);
2829 event[bptr++] = 0xB0;
2830 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2831 *len = ((event+bptr) - len)-1;
2833 int llen = bptr - 12;
2834 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2835 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2837 time_t stime = it->first.tm;
2838 while( tmMap.find(stime) != tmMap.end() )
2840 event[6] += (stime - it->first.tm);
2842 while( evMap.find(event_id) != evMap.end() )
2844 event[0] = (event_id & 0xFF00) >> 8;
2845 event[1] = (event_id & 0xFF);
2846 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2847 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2848 evMap[event_id] = d;
2850 ASSERT(bptr <= 4098);
2854 void eEPGCache::channel_data::startPrivateReader()
2856 eDVBSectionFilterMask mask;
2857 memset(&mask, 0, sizeof(mask));
2858 mask.pid = m_PrivatePid;
2859 mask.flags = eDVBSectionFilterMask::rfCRC;
2860 mask.data[0] = 0xA0;
2861 mask.mask[0] = 0xFF;
2862 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2863 if (m_PrevVersion != -1)
2865 mask.data[3] = m_PrevVersion << 1;
2866 mask.mask[3] = 0x3E;
2867 mask.mode[3] = 0x3E;
2869 seenPrivateSections.clear();
2871 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2872 m_PrivateReader->start(mask);
2875 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2877 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2879 cache->privateSectionRead(m_PrivateService, data);
2880 seenPrivateSections.insert(data[6]);
2882 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2884 eDebug("[EPGC] private finished");
2885 eDVBChannelID chid = channel->getChannelID();
2886 int tmp = chid.original_network_id.get();
2887 tmp |= 0x80000000; // we use highest bit as private epg indicator
2888 chid.original_network_id = tmp;
2889 cache->channelLastUpdated[chid] = ::time(0);
2890 m_PrevVersion = (data[5] & 0x3E) >> 1;
2891 startPrivateReader();
2895 #endif // ENABLE_PRIVATE_EPG
2897 #ifdef ENABLE_MHW_EPG
2898 void eEPGCache::channel_data::cleanup()
2903 m_program_ids.clear();
2906 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2908 // Names in mhw structs are not strings as they are not '\0' terminated.
2909 // This function converts the mhw name into a string.
2910 // Constraint: "length of out" = "length of in" + 1.
2912 for ( i=0; i < len_in; i++ )
2916 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2923 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2926 return_time[0] = toBCD( hours );
2927 return_time[1] = toBCD( minutes );
2931 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2933 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2936 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2937 // For date plus time of day
2939 char tz_saved[1024];
2940 // Remove offset in mhw time.
2941 __u8 local_hours = hours;
2944 else if ( hours >= 8 )
2947 // As far as we know all mhw time data is sent in central Europe time zone.
2948 // So, temporarily set timezone to western europe
2949 time_t dt = ::time(0);
2951 char *old_tz = getenv( "TZ" );
2953 strcpy(tz_saved, old_tz);
2954 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2958 localtime_r(&dt, &localnow);
2962 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2964 if (local_hours <= 5)
2967 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2968 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2971 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2973 if ( old_tz == NULL )
2976 setenv("TZ", tz_saved, 1);
2979 // Calculate MJD according to annex in ETSI EN 300 468
2981 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2983 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2984 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2986 return_time[0] = (mjd & 0xFF00)>>8;
2987 return_time[1] = mjd & 0xFF;
2989 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2992 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2993 // data is borrowed from calling proc to save memory space.
2997 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2998 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2999 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
3001 eit_t *packet = (eit_t *) data;
3002 packet->table_id = 0x50;
3003 packet->section_syntax_indicator = 1;
3005 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
3006 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
3007 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3008 packet->current_next_indicator = 0;
3009 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3010 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3011 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
3012 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
3013 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
3014 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
3015 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
3016 packet->segment_last_table_id = 0x50;
3018 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
3019 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 35 : 23 );
3020 int prog_title_length = prog_title.length();
3022 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3023 prog_title_length + 1;
3025 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
3026 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
3027 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
3031 u_char *data = (u_char*) event_data;
3032 data[2] = itTitle->second.mhw2_mjd_hi;
3033 data[3] = itTitle->second.mhw2_mjd_lo;
3034 data[4] = itTitle->second.mhw2_hours;
3035 data[5] = itTitle->second.mhw2_minutes;
3036 data[6] = itTitle->second.mhw2_seconds;
3037 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
3041 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
3042 (u_char *) event_data + 2 );
3043 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
3046 event_data->running_status = 0;
3047 event_data->free_CA_mode = 0;
3048 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
3050 eit_short_event_descriptor_struct *short_event_descriptor =
3051 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
3052 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
3053 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
3054 prog_title_length - 1;
3055 short_event_descriptor->language_code_1 = 'e';
3056 short_event_descriptor->language_code_2 = 'n';
3057 short_event_descriptor->language_code_3 = 'g';
3058 short_event_descriptor->event_name_length = prog_title_length;
3059 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
3060 memcpy(event_name, prog_title.c_str(), prog_title_length);
3063 event_name[prog_title_length] = 0;
3065 if ( sumText.length() > 0 )
3066 // There is summary info
3068 unsigned int sum_length = sumText.length();
3069 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
3070 // Store summary in short event descriptor
3072 // Increase all relevant lengths
3073 event_name[prog_title_length] = sum_length;
3074 short_event_descriptor->descriptor_length += sum_length;
3075 packet_length += sum_length;
3076 descr_ll += sum_length;
3077 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
3080 // Store summary in extended event descriptors
3082 int remaining_sum_length = sumText.length();
3083 int nbr_descr = int(remaining_sum_length/247) + 1;
3084 for ( int i=0; i < nbr_descr; i++)
3085 // Loop once per extended event descriptor
3087 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
3088 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
3089 remaining_sum_length -= sum_length;
3090 packet_length += 8 + sum_length;
3091 descr_ll += 8 + sum_length;
3093 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
3094 ext_event_descriptor->descriptor_length = sum_length + 6;
3095 ext_event_descriptor->descriptor_number = i;
3096 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
3097 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
3098 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
3099 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
3100 u_char *the_text = (u_char *) ext_event_descriptor + 8;
3102 the_text[-1] = sum_length;
3103 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
3110 // Add content descriptor
3111 u_char *descriptor = (u_char *) data + packet_length;
3116 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
3117 if ( content_descr.find( "FILM" ) != std::string::npos )
3119 else if ( content_descr.find( "SPORT" ) != std::string::npos )
3122 descriptor[0] = 0x54;
3124 descriptor[2] = content_id;
3128 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
3129 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
3131 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
3132 packet->section_length_lo = (packet_length - 3)&0xff;
3134 // Feed the data to eEPGCache::sectionRead()
3135 cache->sectionRead( data, MHW, this );
3138 void eEPGCache::channel_data::startTimeout(int msec)
3140 m_MHWTimeoutTimer->start(msec,true);
3141 m_MHWTimeoutet=false;
3144 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
3146 m_MHWFilterMask.pid = pid;
3147 m_MHWFilterMask.data[0] = tid;
3148 m_MHWReader->start(m_MHWFilterMask);
3149 // eDebug("start 0x%02x 0x%02x", pid, tid);
3152 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
3154 m_MHWFilterMask2.pid = pid;
3155 m_MHWFilterMask2.data[0] = tid;
3158 m_MHWFilterMask2.data[1] = ext;
3159 m_MHWFilterMask2.mask[1] = 0xFF;
3160 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
3164 m_MHWFilterMask2.data[1] = 0;
3165 m_MHWFilterMask2.mask[1] = 0;
3166 // eDebug("start 0x%02x 0x%02x", pid, tid);
3168 m_MHWReader2->start(m_MHWFilterMask2);
3171 void eEPGCache::channel_data::readMHWData(const __u8 *data)
3174 m_MHWReader2->stop();
3176 if ( state > 1 || // aborted
3177 // have si data.. so we dont read mhw data
3178 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3180 eDebug("[EPGC] mhw aborted %d", state);
3182 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
3185 int len = ((data[1]&0xf)<<8) + data[2] - 1;
3186 int record_size = sizeof( mhw_channel_name_t );
3187 int nbr_records = int (len/record_size);
3189 m_channels.resize(nbr_records);
3190 for ( int i = 0; i < nbr_records; i++ )
3192 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
3193 m_channels[i]=*channel;
3197 eDebug("[EPGC] mhw %d channels found", m_channels.size());
3199 // Channels table has been read, start reading the themes table.
3200 startMHWReader(0xD3, 0x92);
3203 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
3206 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3207 int record_size = sizeof( mhw_theme_name_t );
3208 int nbr_records = int (len/record_size);
3210 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
3213 for ( int i = 0; i < nbr_records; i++ )
3215 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
3216 if ( i >= next_idx )
3220 next_idx = (__u8) *(data + 3 + idx_ptr);
3226 m_themes[idx+sub_idx] = *theme;
3228 eDebug("[EPGC] mhw %d themes found", m_themes.size());
3229 // Themes table has been read, start reading the titles table.
3230 startMHWReader(0xD2, 0x90);
3234 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3237 mhw_title_t *title = (mhw_title_t*) data;
3239 if ( title->channel_id == 0xFF ) // Separator
3240 return; // Continue reading of the current table.
3243 // Create unique key per title
3244 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
3245 (title->ms.minutes);
3246 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
3247 ((title->program_id_ml)<<8)|(title->program_id_lo);
3249 if ( m_titles.find( title_id ) == m_titles.end() )
3252 title->mhw2_mjd_hi = 0;
3253 title->mhw2_mjd_lo = 0;
3254 title->mhw2_duration_hi = 0;
3255 title->mhw2_duration_lo = 0;
3256 m_titles[ title_id ] = *title;
3257 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3258 // program_ids will be used to gather summaries.
3259 m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3260 return; // Continue reading of the current table.
3262 else if (!checkTimeout())
3265 if ( !m_program_ids.empty())
3267 // Titles table has been read, there are summaries to read.
3268 // Start reading summaries, store corresponding titles on the fly.
3269 startMHWReader(0xD3, 0x90);
3270 eDebug("[EPGC] mhw %d titles(%d with summary) found",
3272 m_program_ids.size());
3277 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3280 mhw_summary_t *summary = (mhw_summary_t*) data;
3282 // Create unique key per record
3283 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3284 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3285 int len = ((data[1]&0xf)<<8) + data[2];
3287 // ugly workaround to convert const __u8* to char*
3289 memcpy(&tmp, &data, sizeof(void*));
3290 tmp[len+3] = 0; // Terminate as a string.
3292 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3293 if ( itProgid == m_program_ids.end() )
3294 { /* This part is to prevent to looping forever if some summaries are not received yet.
3295 There is a timeout of 4 sec. after the last successfully read summary. */
3296 if (!m_program_ids.empty() && !checkTimeout())
3297 return; // Continue reading of the current table.
3301 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3304 while((pos = the_text.find("\r\n")) != std::string::npos)
3305 the_text.replace(pos, 2, " ");
3307 // Find corresponding title, store title and summary in epgcache.
3308 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3309 if ( itTitle != m_titles.end() )
3312 storeTitle( itTitle, the_text, data );
3313 m_titles.erase( itTitle );
3315 m_program_ids.erase( itProgid );
3316 if ( !m_program_ids.empty() )
3317 return; // Continue reading of the current table.
3320 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3322 m_program_ids.size());
3323 // Summaries have been read, titles that have summaries have been stored.
3324 // Now store titles that do not have summaries.
3325 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3326 storeTitle( itTitle, "", data );
3330 m_MHWReader->stop();
3335 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3337 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3340 m_MHWReader->stop();
3342 if ( state > 1 || // aborted
3343 // have si data.. so we dont read mhw data
3344 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3346 eDebug("[EPGC] mhw2 aborted %d", state);
3348 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3351 int num_channels = data[120];
3352 m_channels.resize(num_channels);
3355 int ptr = 121 + 8 * num_channels;
3358 for( int chid = 0; chid < num_channels; ++chid )
3360 ptr += ( data[ptr] & 0x0f ) + 1;
3370 // data seems consistent...
3371 const __u8 *tmp = data+121;
3372 for (int i=0; i < num_channels; ++i)
3374 mhw_channel_name_t channel;
3375 channel.network_id_hi = *(tmp++);
3376 channel.network_id_lo = *(tmp++);
3377 channel.transport_stream_id_hi = *(tmp++);
3378 channel.transport_stream_id_lo = *(tmp++);
3379 channel.channel_id_hi = *(tmp++);
3380 channel.channel_id_lo = *(tmp++);
3381 m_channels[i]=channel;
3382 // eDebug("%d(%02x) %04x: %02x %02x", i, i, (channel.channel_id_hi << 8) | channel.channel_id_lo, *tmp, *(tmp+1));
3385 for (int i=0; i < num_channels; ++i)
3387 mhw_channel_name_t &channel = m_channels[i];
3388 int channel_name_len=*(tmp++)&0x0f;
3390 for (; x < channel_name_len; ++x)
3391 channel.name[x]=*(tmp++);
3392 channel.name[x+1]=0;
3393 // eDebug("%d(%02x) %s", i, i, channel.name);
3396 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3398 else if (m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3401 eDebug("[EPGC] mhw2 themes nyi");
3403 else if (m_MHWFilterMask2.pid == m_mhw2_title_pid && m_MHWFilterMask2.data[0] == 0xe6)
3410 // eDebug("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
3411 // data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10],
3412 // data[11], data[12], data[13], data[14], data[15], data[16], data[17] );
3414 while( pos < dataLen && !valid)
3417 pos += (data[pos] & 0x3F) + 4;
3418 if( pos == dataLen )
3425 eDebug("mhw2 title table invalid!!");
3428 if (!m_MHWTimeoutTimer->isActive())
3430 return; // continue reading
3433 // data seems consistent...
3436 while (pos < dataLen)
3438 // eDebugNoNewLine(" [%02x] %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x [%02x %02x %02x %02x %02x %02x %02x] LL - DESCR - ",
3439 // data[pos], data[pos+1], data[pos+2], data[pos+3], data[pos+4], data[pos+5], data[pos+6], data[pos+7],
3440 // 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]);
3441 title.channel_id = data[pos]+1;
3442 title.mhw2_mjd_hi = data[pos+11];
3443 title.mhw2_mjd_lo = data[pos+12];
3444 title.mhw2_hours = data[pos+13];
3445 title.mhw2_minutes = data[pos+14];
3446 title.mhw2_seconds = data[pos+15];
3447 int duration = ((data[pos+16] << 8)|data[pos+17]) >> 4;
3448 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3449 title.mhw2_duration_lo = duration&0xFF;
3451 // Create unique key per title
3452 __u32 title_id = (data[pos+7] << 24) | (data[pos+8] << 16) | (data[pos+9] << 8) | data[pos+10];
3454 __u8 slen = data[pos+18] & 0x3f;
3455 __u8 *dest = ((__u8*)title.title)-4;
3456 memcpy(dest, &data[pos+19], slen>35 ? 35 : slen);
3457 memset(dest+slen, 0, 35-slen);
3459 // eDebug("%02x [%02x %02x]: %s", data[pos], data[pos+1], data[pos+2], dest);
3461 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3462 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3464 // if (title.channel_id > m_channels.size())
3465 // eDebug("channel_id(%d %02x) to big!!", title.channel_id);
3467 // eDebug("pos %d prog_id %02x %02x chid %02x summary_id %04x dest %p len %d\n",
3468 // pos, title.program_id_ml, title.program_id_lo, title.channel_id, summary_id, dest, slen);
3470 // eDebug("title_id %08x -> summary_id %04x\n", title_id, summary_id);
3474 std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3475 if ( it == m_titles.end() )
3478 m_titles[ title_id ] = title;
3479 if (summary_id != 0xFFFF)
3482 std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3483 while (it != m_program_ids.end() && it->first == summary_id)
3485 if (it->second == title_id) {
3492 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3497 if ( !checkTimeout() )
3498 continue; // Continue reading of the current table.
3506 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3507 if (!m_program_ids.empty())
3509 // Titles table has been read, there are summaries to read.
3510 // Start reading summaries, store corresponding titles on the fly.
3511 startMHWReader2(m_mhw2_summary_pid, 0x96);
3512 startTimeout(15000);
3519 else if (m_MHWFilterMask2.pid == m_mhw2_summary_pid && m_MHWFilterMask2.data[0] == 0x96)
3522 if (!checkTimeout())
3524 int len, loop, pos, lenline;
3533 loop = data[pos] & 0x0f;
3538 for( ; loop > 0; --loop )
3540 if( dataLen > (pos+len) )
3542 lenline = data[pos+len];
3552 return; // continue reading
3556 // data seems consistent...
3557 __u32 summary_id = (data[3]<<8)|data[4];
3558 // eDebug ("summary id %04x\n", summary_id);
3559 // 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] );
3561 // ugly workaround to convert const __u8* to char*
3563 memcpy(&tmp, &data, sizeof(void*));
3568 loop = tmp[pos] & 0x0f;
3570 for( ; loop > 0; loop -- )
3572 lenline = tmp[pos+len];
3581 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3582 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3583 { /* This part is to prevent to looping forever if some summaries are not received yet.
3584 There is a timeout of 4 sec. after the last successfully read summary. */
3585 if ( !m_program_ids.empty() )
3586 return; // Continue reading of the current table.
3590 startTimeout(15000);
3591 std::string the_text = (char *) (data + pos + 1);
3593 // eDebug ("summary id %04x : %s\n", summary_id, data+pos+1);
3595 while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3598 // Find corresponding title, store title and summary in epgcache.
3599 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3600 if ( itTitle != m_titles.end() )
3602 storeTitle( itTitle, the_text, data );
3603 m_titles.erase( itTitle );
3605 m_program_ids.erase( itProgId++ );
3607 if ( !m_program_ids.empty() )
3608 return; // Continue reading of the current table.
3612 return; // continue reading
3615 if (isRunning & eEPGCache::MHW)
3617 if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3619 // Channels table has been read, start reading the themes table.
3620 startMHWReader2(m_mhw2_channel_pid, 0xC8, 1);
3623 else if ( m_MHWFilterMask2.pid == m_mhw2_channel_pid && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3625 // Themes table has been read, start reading the titles table.
3626 startMHWReader2(m_mhw2_title_pid, 0xe6);
3631 // Summaries have been read, titles that have summaries have been stored.
3632 // Now store titles that do not have summaries.
3633 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3634 storeTitle( itTitle, "", data );
3635 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3637 m_program_ids.size());
3644 m_MHWReader2->stop();