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/dvb/pmt.h>
16 #include <lib/dvb/db.h>
17 #include <lib/python/python.h>
19 int eventData::CacheSize=0;
20 descriptorMap eventData::descriptors;
21 __u8 eventData::data[4108];
22 extern const uint32_t crc32_table[256];
24 const eServiceReference &handleGroup(const eServiceReference &ref)
26 if (ref.flags & eServiceReference::isGroup)
28 ePtr<eDVBResourceManager> res;
29 if (!eDVBResourceManager::getInstance(res))
31 ePtr<iDVBChannelList> db;
32 if (!res->getChannelList(db))
35 if (!db->getBouquet(ref, bouquet))
37 std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
38 if (it != bouquet->m_services.end())
48 eventData::eventData(const eit_event_struct* e, int size, int type)
49 :ByteSize(size&0xFF), type(type&0xFF)
57 __u8 *data = (__u8*)e;
59 int descriptors_length = (data[ptr++]&0x0F) << 8;
60 descriptors_length |= data[ptr++];
61 while ( descriptors_length > 0 )
63 __u8 *descr = data+ptr;
64 int descr_len = descr[1]+2;
68 while(cnt++ < descr_len)
69 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
71 descriptorMap::iterator it =
72 descriptors.find(crc);
73 if ( it == descriptors.end() )
76 __u8 *d = new __u8[descr_len];
77 memcpy(d, descr, descr_len);
78 descriptors[crc] = descriptorPair(1, d);
84 descriptors_length -= descr_len;
86 ASSERT(pdescr <= &descr[65]);
87 ByteSize = 12+((pdescr-descr)*4);
88 EITdata = new __u8[ByteSize];
90 memcpy(EITdata, (__u8*) e, 12);
91 memcpy(EITdata+12, descr, ByteSize-12);
94 const eit_event_struct* eventData::get() const
97 int tmp = ByteSize-12;
98 memcpy(data, EITdata, 12);
99 __u32 *p = (__u32*)(EITdata+12);
102 descriptorMap::iterator it =
103 descriptors.find(*p++);
104 if ( it != descriptors.end() )
106 int b = it->second.second[1]+2;
107 memcpy(data+pos, it->second.second, b );
114 return (const eit_event_struct*)data;
117 eventData::~eventData()
123 __u32 *d = (__u32*)(EITdata+12);
126 descriptorMap::iterator it =
127 descriptors.find(*d++);
128 if ( it != descriptors.end() )
130 descriptorPair &p = it->second;
131 if (!--p.first) // no more used descriptor
133 CacheSize -= it->second.second[1];
134 delete [] it->second.second; // free descriptor memory
135 descriptors.erase(it); // remove entry from descriptor map
139 eFatal("[descriptor not found in descriptor cache!!!!!!");
146 void eventData::load(FILE *f)
152 fread(&size, sizeof(int), 1, f);
155 fread(&id, sizeof(__u32), 1, f);
156 fread(&p.first, sizeof(int), 1, f);
157 fread(header, 2, 1, f);
158 int bytes = header[1]+2;
159 p.second = new __u8[bytes];
160 p.second[0] = header[0];
161 p.second[1] = header[1];
162 fread(p.second+2, bytes-2, 1, f);
169 void eventData::save(FILE *f)
171 int size=descriptors.size();
172 descriptorMap::iterator it(descriptors.begin());
173 fwrite(&size, sizeof(int), 1, f);
176 fwrite(&it->first, sizeof(__u32), 1, f);
177 fwrite(&it->second.first, sizeof(int), 1, f);
178 fwrite(it->second.second, it->second.second[1]+2, 1, f);
184 eEPGCache* eEPGCache::instance;
185 pthread_mutex_t eEPGCache::cache_lock=
186 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
187 pthread_mutex_t eEPGCache::channel_map_lock=
188 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
190 DEFINE_REF(eEPGCache)
192 eEPGCache::eEPGCache()
193 :messages(this,1), cleanTimer(this)//, paused(0)
195 eDebug("[EPGC] Initialized EPGCache");
197 CONNECT(messages.recv_msg, eEPGCache::gotMessage);
198 CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
199 CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
201 ePtr<eDVBResourceManager> res_mgr;
202 eDVBResourceManager::getInstance(res_mgr);
204 eDebug("[eEPGCache] no resource manager !!!!!!!");
206 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
210 void eEPGCache::timeUpdated()
214 eDebug("[EPGC] time updated.. start EPG Mainloop");
217 messages.send(Message(Message::timeChanged));
220 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
224 // eDebug("[eEPGCache] add channel %p", chan);
225 channel_data *data = new channel_data(this);
226 data->channel = chan;
227 data->prevChannelState = -1;
228 #ifdef ENABLE_PRIVATE_EPG
229 data->m_PrivatePid = -1;
231 singleLock s(channel_map_lock);
232 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
233 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
237 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
239 channelMapIterator it =
240 m_knownChannels.find(chan);
241 if ( it == m_knownChannels.end() )
242 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
245 channel_data &data = *it->second;
246 ePtr<eDVBResourceManager> res_mgr;
247 if ( eDVBResourceManager::getInstance( res_mgr ) )
248 eDebug("[eEPGCache] no res manager!!");
251 ePtr<iDVBDemux> demux;
252 if ( data.channel->getDemux(demux, 0) )
254 eDebug("[eEPGCache] no demux!!");
259 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
262 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
266 res = demux->createSectionReader( this, data.m_ScheduleReader );
269 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
273 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
276 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
279 #ifdef ENABLE_PRIVATE_EPG
280 res = demux->createSectionReader( this, data.m_PrivateReader );
283 eDebug("[eEPGCache] couldnt initialize private reader!!");
287 #ifdef ENABLE_MHW_EPG
288 res = demux->createSectionReader( this, data.m_MHWReader );
291 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
294 res = demux->createSectionReader( this, data.m_MHWReader2 );
297 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
301 messages.send(Message(Message::startChannel, chan));
302 // -> gotMessage -> changedService
308 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
310 channelMapIterator it =
311 m_knownChannels.find(chan);
312 if ( it != m_knownChannels.end() )
315 chan->getState(state);
316 if ( it->second->prevChannelState != state )
320 case iDVBChannel::state_ok:
322 eDebug("[eEPGCache] channel %p running", chan);
323 DVBChannelRunning(chan);
326 case iDVBChannel::state_release:
328 eDebug("[eEPGCache] remove channel %p", chan);
329 messages.send(Message(Message::leaveChannel, chan));
330 pthread_mutex_lock(&it->second->channel_active);
331 singleLock s(channel_map_lock);
332 m_knownChannels.erase(it);
333 pthread_mutex_unlock(&it->second->channel_active);
336 // -> gotMessage -> abortEPG
339 default: // ignore all other events
343 it->second->prevChannelState = state;
348 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
350 timeMap::iterator tmp = tm_it;
351 while ((tmp->first+tmp->second->getDuration()-300) > TM)
354 #ifdef ENABLE_PRIVATE_EPG
355 && tmp->second->type != PRIVATE
358 && tmp->second->type != MHW
362 __u16 event_id = tmp->second->getEventID();
363 servicemap.first.erase(event_id);
365 Event evt((uint8_t*)tmp->second->get());
367 event.parseFrom(&evt, service.sid<<16|service.onid);
368 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
369 service.sid, event_id,
370 event.getBeginTimeString().c_str(),
371 event.getEventName().c_str(),
372 event.getExtendedDescription().c_str());
375 if (tmp == servicemap.second.begin())
377 servicemap.second.erase(tmp);
381 servicemap.second.erase(tmp--);
385 if (tmp == servicemap.second.begin())
392 while(tmp->first < (TM+duration-300))
394 if (tmp->first != TM && tmp->second->type != PRIVATE)
396 __u16 event_id = tmp->second->getEventID();
397 servicemap.first.erase(event_id);
399 Event evt((uint8_t*)tmp->second->get());
401 event.parseFrom(&evt, service.sid<<16|service.onid);
402 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
403 service.sid, event_id,
404 event.getBeginTimeString().c_str(),
405 event.getEventName().c_str(),
406 event.getExtendedDescription().c_str());
409 servicemap.second.erase(tmp++);
413 if (tmp == servicemap.second.end())
418 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
420 eit_t *eit = (eit_t*) data;
422 int len=HILO(eit->section_length)-1;//+3-4;
427 // This fixed the EPG on the Multichoice irdeto systems
428 // the EIT packet is non-compliant.. their EIT packet stinks
429 if ( data[ptr-1] < 0x40 )
432 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
433 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
437 time_t TM = parseDVBtime( eit_event->start_time_1, eit_event->start_time_2, eit_event->start_time_3, eit_event->start_time_4, eit_event->start_time_5);
438 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
440 if ( TM != 3599 && TM > -1)
441 channel->haveData |= source;
443 singleLock s(cache_lock);
444 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
445 // oder eine durch [] erzeugte
446 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
447 eventMap::iterator prevEventIt = servicemap.first.end();
448 timeMap::iterator prevTimeIt = servicemap.second.end();
452 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
454 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
456 eit_event->start_time_1,
457 eit_event->start_time_2,
458 eit_event->start_time_3,
459 eit_event->start_time_4,
460 eit_event->start_time_5);
465 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
468 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
470 __u16 event_id = HILO(eit_event->event_id);
471 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
474 int ev_erase_count = 0;
475 int tm_erase_count = 0;
477 // search in eventmap
478 eventMap::iterator ev_it =
479 servicemap.first.find(event_id);
481 // entry with this event_id is already exist ?
482 if ( ev_it != servicemap.first.end() )
484 if ( source > ev_it->second->type ) // update needed ?
485 goto next; // when not.. then skip this entry
487 // search this event in timemap
488 timeMap::iterator tm_it_tmp =
489 servicemap.second.find(ev_it->second->getStartTime());
491 if ( tm_it_tmp != servicemap.second.end() )
493 if ( tm_it_tmp->first == TM ) // just update eventdata
496 delete ev_it->second;
497 ev_it->second = tm_it_tmp->second =
498 new eventData(eit_event, eit_event_size, source);
499 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
502 else // event has new event begin time
505 // delete the found record from timemap
506 servicemap.second.erase(tm_it_tmp);
507 prevTimeIt=servicemap.second.end();
512 // search in timemap, for check of a case if new time has coincided with time of other event
513 // or event was is not found in eventmap
514 timeMap::iterator tm_it =
515 servicemap.second.find(TM);
517 if ( tm_it != servicemap.second.end() )
519 // event with same start time but another event_id...
520 if ( source > tm_it->second->type &&
521 ev_it == servicemap.first.end() )
522 goto next; // when not.. then skip this entry
524 // search this time in eventmap
525 eventMap::iterator ev_it_tmp =
526 servicemap.first.find(tm_it->second->getEventID());
528 if ( ev_it_tmp != servicemap.first.end() )
531 // delete the found record from eventmap
532 servicemap.first.erase(ev_it_tmp);
533 prevEventIt=servicemap.first.end();
537 evt = new eventData(eit_event, eit_event_size, source);
539 bool consistencyCheck=true;
541 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
544 delete ev_it->second;
545 delete tm_it->second;
549 else if (ev_erase_count == 0 && tm_erase_count > 0)
552 delete ev_it->second;
553 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
556 else if (ev_erase_count > 0 && tm_erase_count == 0)
559 delete tm_it->second;
560 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
563 else // added new eventData
566 consistencyCheck=false;
568 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
569 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
572 FixOverlapping(servicemap, TM, duration, tm_it, service);
575 if ( consistencyCheck )
577 if ( tm_it->second != evt || ev_it->second != evt )
578 eFatal("tm_it->second != ev_it->second");
579 else if ( tm_it->second->getStartTime() != tm_it->first )
580 eFatal("event start_time(%d) non equal timemap key(%d)",
581 tm_it->second->getStartTime(), tm_it->first );
582 else if ( tm_it->first != TM )
583 eFatal("timemap key(%d) non equal TM(%d)",
585 else if ( ev_it->second->getEventID() != ev_it->first )
586 eFatal("event_id (%d) non equal event_map key(%d)",
587 ev_it->second->getEventID(), ev_it->first);
588 else if ( ev_it->first != event_id )
589 eFatal("eventmap key(%d) non equal event_id(%d)",
590 ev_it->first, event_id );
596 if ( servicemap.first.size() != servicemap.second.size() )
598 FILE *f = fopen("/hdd/event_map.txt", "w+");
600 for (eventMap::iterator it(servicemap.first.begin())
601 ; it != servicemap.first.end(); ++it )
602 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
603 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
605 f = fopen("/hdd/time_map.txt", "w+");
607 for (timeMap::iterator it(servicemap.second.begin())
608 ; it != servicemap.second.end(); ++it )
609 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
610 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
613 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
614 service.sid, service.tsid, service.onid,
615 servicemap.first.size(), servicemap.second.size() );
618 ptr += eit_event_size;
619 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
623 void eEPGCache::flushEPG(const uniqueEPGKey & s)
625 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
626 singleLock l(cache_lock);
627 if (s) // clear only this service
629 eventCache::iterator it = eventDB.find(s);
630 if ( it != eventDB.end() )
632 eventMap &evMap = it->second.first;
633 timeMap &tmMap = it->second.second;
635 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
640 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
641 #ifdef ENABLE_PRIVATE_EPG
642 contentMaps::iterator it =
643 content_time_tables.find(s);
644 if ( it != content_time_tables.end() )
647 content_time_tables.erase(it);
652 else // clear complete EPG Cache
654 for (eventCache::iterator it(eventDB.begin());
655 it != eventDB.end(); ++it)
657 eventMap &evMap = it->second.first;
658 timeMap &tmMap = it->second.second;
659 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
665 #ifdef ENABLE_PRIVATE_EPG
666 content_time_tables.clear();
668 channelLastUpdated.clear();
669 singleLock m(channel_map_lock);
670 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
671 it->second->startEPG();
673 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
676 void eEPGCache::cleanLoop()
678 singleLock s(cache_lock);
679 if (!eventDB.empty())
681 eDebug("[EPGC] start cleanloop");
683 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
685 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
687 bool updated = false;
688 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
690 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
692 // remove entry from eventMap
693 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
694 if ( b != DBIt->second.first.end() )
696 // release Heap Memory for this entry (new ....)
697 // eDebug("[EPGC] delete old event (evmap)");
698 DBIt->second.first.erase(b);
701 // remove entry from timeMap
702 // eDebug("[EPGC] release heap mem");
704 DBIt->second.second.erase(It++);
705 // eDebug("[EPGC] delete old event (timeMap)");
711 #ifdef ENABLE_PRIVATE_EPG
714 contentMaps::iterator x =
715 content_time_tables.find( DBIt->first );
716 if ( x != content_time_tables.end() )
718 timeMap &tmMap = DBIt->second.second;
719 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
721 for ( contentTimeMap::iterator it(i->second.begin());
722 it != i->second.end(); )
724 if ( tmMap.find(it->second.first) == tmMap.end() )
725 i->second.erase(it++);
729 if ( i->second.size() )
732 x->second.erase(i++);
738 eDebug("[EPGC] stop cleanloop");
739 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
741 cleanTimer.start(CLEAN_INTERVAL,true);
744 eEPGCache::~eEPGCache()
746 messages.send(Message::quit);
747 kill(); // waiting for thread shutdown
748 singleLock s(cache_lock);
749 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
750 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
754 void eEPGCache::gotMessage( const Message &msg )
759 flushEPG(msg.service);
761 case Message::startChannel:
763 singleLock s(channel_map_lock);
764 channelMapIterator channel =
765 m_knownChannels.find(msg.channel);
766 if ( channel != m_knownChannels.end() )
767 channel->second->startChannel();
770 case Message::leaveChannel:
772 singleLock s(channel_map_lock);
773 channelMapIterator channel =
774 m_knownChannels.find(msg.channel);
775 if ( channel != m_knownChannels.end() )
776 channel->second->abortEPG();
782 #ifdef ENABLE_PRIVATE_EPG
783 case Message::got_private_pid:
785 singleLock s(channel_map_lock);
786 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
788 eDVBChannel *channel = (eDVBChannel*) it->first;
789 channel_data *data = it->second;
790 eDVBChannelID chid = channel->getChannelID();
791 if ( chid.transport_stream_id.get() == msg.service.tsid &&
792 chid.original_network_id.get() == msg.service.onid &&
793 data->m_PrivatePid == -1 )
795 data->m_PrevVersion = -1;
796 data->m_PrivatePid = msg.pid;
797 data->m_PrivateService = msg.service;
798 int onid = chid.original_network_id.get();
799 onid |= 0x80000000; // we use highest bit as private epg indicator
800 chid.original_network_id = onid;
801 updateMap::iterator It = channelLastUpdated.find( chid );
802 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
803 if (update < ZAP_DELAY)
805 data->startPrivateTimer.start(update, 1);
807 eDebug("[EPGC] next private update in %i min", update/60000);
808 else if (update >= 1000)
809 eDebug("[EPGC] next private update in %i sec", update/1000);
816 case Message::timeChanged:
820 eDebug("unhandled EPGCache Message!!");
825 void eEPGCache::thread()
835 void eEPGCache::load()
837 singleLock s(cache_lock);
838 FILE *f = fopen("/hdd/epg.dat", "r");
844 unsigned char md5_saved[16];
845 unsigned char md5[16];
848 if (!md5_file("/hdd/epg.dat", 1, md5))
850 FILE *f = fopen("/hdd/epg.dat.md5", "r");
853 fread( md5_saved, 16, 1, f);
855 if ( !memcmp(md5_saved, md5, 16) )
862 unsigned int magic=0;
863 fread( &magic, sizeof(int), 1, f);
864 if (magic != 0x98765432)
866 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
871 fread( text1, 13, 1, f);
872 if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
874 fread( &size, sizeof(int), 1, f);
881 fread( &key, sizeof(uniqueEPGKey), 1, f);
882 fread( &size, sizeof(int), 1, f);
888 fread( &type, sizeof(__u8), 1, f);
889 fread( &len, sizeof(__u8), 1, f);
890 event = new eventData(0, len, type);
891 event->EITdata = new __u8[len];
892 eventData::CacheSize+=len;
893 fread( event->EITdata, len, 1, f);
894 evMap[ event->getEventID() ]=event;
895 tmMap[ event->getStartTime() ]=event;
898 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
901 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
902 #ifdef ENABLE_PRIVATE_EPG
904 fread( text2, 11, 1, f);
905 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
908 fread( &size, sizeof(int), 1, f);
913 fread( &key, sizeof(uniqueEPGKey), 1, f);
914 eventMap &evMap=eventDB[key].first;
915 fread( &size, sizeof(int), 1, f);
920 fread( &content_id, sizeof(int), 1, f);
921 fread( &size, sizeof(int), 1, f);
926 fread( &time1, sizeof(time_t), 1, f);
927 fread( &time2, sizeof(time_t), 1, f);
928 fread( &event_id, sizeof(__u16), 1, f);
929 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
930 eventMap::iterator it =
931 evMap.find(event_id);
932 if (it != evMap.end())
933 it->second->type = PRIVATE;
938 #endif // ENABLE_PRIVATE_EPG
941 eDebug("[EPGC] don't read old epg database");
947 void eEPGCache::save()
951 if (statfs("/hdd", &s)<0)
959 // prevent writes to builtin flash
960 if ( tmp < 1024*1024*50 ) // storage size < 50MB
963 // check for enough free space on storage
966 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
969 FILE *f = fopen("/hdd/epg.dat", "w");
973 unsigned int magic = 0x98765432;
974 fwrite( &magic, sizeof(int), 1, f);
975 const char *text = "ENIGMA_EPG_V5";
976 fwrite( text, 13, 1, f );
977 int size = eventDB.size();
978 fwrite( &size, sizeof(int), 1, f );
979 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
981 timeMap &timemap = service_it->second.second;
982 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
983 size = timemap.size();
984 fwrite( &size, sizeof(int), 1, f);
985 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
987 __u8 len = time_it->second->ByteSize;
988 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
989 fwrite( &len, sizeof(__u8), 1, f);
990 fwrite( time_it->second->EITdata, len, 1, f);
994 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
996 #ifdef ENABLE_PRIVATE_EPG
997 const char* text3 = "PRIVATE_EPG";
998 fwrite( text3, 11, 1, f );
999 size = content_time_tables.size();
1000 fwrite( &size, sizeof(int), 1, f);
1001 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1003 contentMap &content_time_table = a->second;
1004 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1005 int size = content_time_table.size();
1006 fwrite( &size, sizeof(int), 1, f);
1007 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1009 int size = i->second.size();
1010 fwrite( &i->first, sizeof(int), 1, f);
1011 fwrite( &size, sizeof(int), 1, f);
1012 for ( contentTimeMap::iterator it(i->second.begin());
1013 it != i->second.end(); ++it )
1015 fwrite( &it->first, sizeof(time_t), 1, f);
1016 fwrite( &it->second.first, sizeof(time_t), 1, f);
1017 fwrite( &it->second.second, sizeof(__u16), 1, f);
1024 unsigned char md5[16];
1025 if (!md5_file("/hdd/epg.dat", 1, md5))
1027 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1030 fwrite( md5, 16, 1, f);
1038 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1040 ,abortTimer(ml), zapTimer(ml), state(0)
1041 ,isRunning(0), haveData(0)
1042 #ifdef ENABLE_PRIVATE_EPG
1043 ,startPrivateTimer(ml)
1045 #ifdef ENABLE_MHW_EPG
1046 ,m_MHWTimeoutTimer(ml)
1049 #ifdef ENABLE_MHW_EPG
1050 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1052 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1053 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1054 #ifdef ENABLE_PRIVATE_EPG
1055 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1057 pthread_mutex_init(&channel_active, 0);
1060 bool eEPGCache::channel_data::finishEPG()
1062 if (!isRunning) // epg ready
1064 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1065 zapTimer.start(UPDATE_INTERVAL, 1);
1066 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1067 for (int i=0; i < 3; ++i)
1069 seenSections[i].clear();
1070 calcedSections[i].clear();
1072 singleLock l(cache->cache_lock);
1073 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1074 #ifdef ENABLE_MHW_EPG
1082 void eEPGCache::channel_data::startEPG()
1084 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1087 for (int i=0; i < 3; ++i)
1089 seenSections[i].clear();
1090 calcedSections[i].clear();
1093 eDVBSectionFilterMask mask;
1094 memset(&mask, 0, sizeof(mask));
1096 #ifdef ENABLE_MHW_EPG
1098 mask.data[0] = 0x91;
1099 mask.mask[0] = 0xFF;
1100 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1101 m_MHWReader->start(mask);
1103 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1106 mask.data[0] = 0xC8;
1107 mask.mask[0] = 0xFF;
1109 mask.mask[1] = 0xFF;
1110 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1111 m_MHWReader2->start(mask);
1113 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1119 mask.flags = eDVBSectionFilterMask::rfCRC;
1121 mask.data[0] = 0x4E;
1122 mask.mask[0] = 0xFE;
1123 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1124 m_NowNextReader->start(mask);
1125 isRunning |= NOWNEXT;
1127 mask.data[0] = 0x50;
1128 mask.mask[0] = 0xF0;
1129 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1130 m_ScheduleReader->start(mask);
1131 isRunning |= SCHEDULE;
1133 mask.data[0] = 0x60;
1134 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1135 m_ScheduleOtherReader->start(mask);
1136 isRunning |= SCHEDULE_OTHER;
1138 abortTimer.start(7000,true);
1141 void eEPGCache::channel_data::abortNonAvail()
1145 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1147 eDebug("[EPGC] abort non avail nownext reading");
1148 isRunning &= ~NOWNEXT;
1149 m_NowNextReader->stop();
1152 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1154 eDebug("[EPGC] abort non avail schedule reading");
1155 isRunning &= ~SCHEDULE;
1156 m_ScheduleReader->stop();
1159 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1161 eDebug("[EPGC] abort non avail schedule_other reading");
1162 isRunning &= ~SCHEDULE_OTHER;
1163 m_ScheduleOtherReader->stop();
1164 m_ScheduleOtherConn=0;
1166 #ifdef ENABLE_MHW_EPG
1167 if ( !(haveData&MHW) && (isRunning&MHW) )
1169 eDebug("[EPGC] abort non avail mhw reading");
1171 m_MHWReader->stop();
1173 m_MHWReader2->stop();
1178 abortTimer.start(90000, true);
1182 for (int i=0; i < 3; ++i)
1184 seenSections[i].clear();
1185 calcedSections[i].clear();
1192 void eEPGCache::channel_data::startChannel()
1194 pthread_mutex_lock(&channel_active);
1195 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1197 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1199 if (update < ZAP_DELAY)
1202 zapTimer.start(update, 1);
1203 if (update >= 60000)
1204 eDebug("[EPGC] next update in %i min", update/60000);
1205 else if (update >= 1000)
1206 eDebug("[EPGC] next update in %i sec", update/1000);
1209 void eEPGCache::channel_data::abortEPG()
1211 for (int i=0; i < 3; ++i)
1213 seenSections[i].clear();
1214 calcedSections[i].clear();
1220 eDebug("[EPGC] abort caching events !!");
1221 if (isRunning & SCHEDULE)
1223 isRunning &= ~SCHEDULE;
1224 m_ScheduleReader->stop();
1227 if (isRunning & NOWNEXT)
1229 isRunning &= ~NOWNEXT;
1230 m_NowNextReader->stop();
1233 if (isRunning & SCHEDULE_OTHER)
1235 isRunning &= ~SCHEDULE_OTHER;
1236 m_ScheduleOtherReader->stop();
1237 m_ScheduleOtherConn=0;
1239 #ifdef ENABLE_MHW_EPG
1240 if (isRunning & MHW)
1243 m_MHWReader->stop();
1245 m_MHWReader2->stop();
1250 #ifdef ENABLE_PRIVATE_EPG
1251 if (m_PrivateReader)
1252 m_PrivateReader->stop();
1256 pthread_mutex_unlock(&channel_active);
1259 void eEPGCache::channel_data::readData( const __u8 *data)
1263 iDVBSectionReader *reader=NULL;
1267 reader=m_NowNextReader;
1272 reader=m_ScheduleReader;
1277 reader=m_ScheduleOtherReader;
1278 source=SCHEDULE_OTHER;
1282 eDebug("[EPGC] unknown table_id !!!");
1285 tidMap &seenSections = this->seenSections[map];
1286 tidMap &calcedSections = this->calcedSections[map];
1287 if ( state == 1 && calcedSections == seenSections || state > 1 )
1289 eDebugNoNewLine("[EPGC] ");
1294 eDebugNoNewLine("nownext");
1298 eDebugNoNewLine("schedule");
1300 case SCHEDULE_OTHER:
1301 m_ScheduleOtherConn=0;
1302 eDebugNoNewLine("schedule other");
1304 default: eDebugNoNewLine("unknown");break;
1306 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1309 isRunning &= ~source;
1315 eit_t *eit = (eit_t*) data;
1316 __u32 sectionNo = data[0] << 24;
1317 sectionNo |= data[3] << 16;
1318 sectionNo |= data[4] << 8;
1319 sectionNo |= eit->section_number;
1321 tidMap::iterator it =
1322 seenSections.find(sectionNo);
1324 if ( it == seenSections.end() )
1326 seenSections.insert(sectionNo);
1327 calcedSections.insert(sectionNo);
1328 __u32 tmpval = sectionNo & 0xFFFFFF00;
1329 __u8 incr = source == NOWNEXT ? 1 : 8;
1330 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1332 if ( i == eit->section_number )
1334 for (int x=i; x <= eit->segment_last_section_number; ++x)
1335 calcedSections.insert(tmpval|(x&0xFF));
1338 calcedSections.insert(tmpval|(i&0xFF));
1340 cache->sectionRead(data, source, this);
1345 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1346 // if t == -1 we search the current event...
1348 singleLock s(cache_lock);
1349 uniqueEPGKey key(handleGroup(service));
1351 // check if EPG for this service is ready...
1352 eventCache::iterator It = eventDB.find( key );
1353 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1356 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1357 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1358 It->second.second.upper_bound(t); // just >
1359 if ( i != It->second.second.end() )
1361 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1363 timeMap::iterator x = i;
1365 if ( x != It->second.second.end() )
1367 time_t start_time = x->second->getStartTime();
1372 if (t > (start_time+x->second->getDuration()))
1387 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1389 singleLock s(cache_lock);
1390 const eventData *data=0;
1391 RESULT ret = lookupEventTime(service, t, data, direction);
1393 result = data->get();
1397 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1399 singleLock s(cache_lock);
1400 const eventData *data=0;
1401 RESULT ret = lookupEventTime(service, t, data, direction);
1403 result = new Event((uint8_t*)data->get());
1407 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1409 singleLock s(cache_lock);
1410 const eventData *data=0;
1411 RESULT ret = lookupEventTime(service, t, data, direction);
1414 Event ev((uint8_t*)data->get());
1415 result = new eServiceEvent();
1416 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1417 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1422 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1424 singleLock s(cache_lock);
1425 uniqueEPGKey key(handleGroup(service));
1427 eventCache::iterator It = eventDB.find( key );
1428 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1430 eventMap::iterator i( It->second.first.find( event_id ));
1431 if ( i != It->second.first.end() )
1439 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1445 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1447 singleLock s(cache_lock);
1448 const eventData *data=0;
1449 RESULT ret = lookupEventId(service, event_id, data);
1451 result = data->get();
1455 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1457 singleLock s(cache_lock);
1458 const eventData *data=0;
1459 RESULT ret = lookupEventId(service, event_id, data);
1461 result = new Event((uint8_t*)data->get());
1465 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1467 singleLock s(cache_lock);
1468 const eventData *data=0;
1469 RESULT ret = lookupEventId(service, event_id, data);
1472 Event ev((uint8_t*)data->get());
1473 result = new eServiceEvent();
1474 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1475 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1480 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1483 eventCache::iterator It = eventDB.find(handleGroup(service));
1484 if ( It != eventDB.end() && It->second.second.size() )
1486 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1489 m_timemap_cursor = It->second.second.lower_bound(begin);
1490 if ( m_timemap_cursor != It->second.second.end() )
1492 if ( m_timemap_cursor->second->getStartTime() != begin )
1494 timeMap::iterator x = m_timemap_cursor;
1496 if ( x != It->second.second.end() )
1498 time_t start_time = x->second->getStartTime();
1499 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1500 m_timemap_cursor = x;
1506 m_timemap_cursor = It->second.second.begin();
1507 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1508 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1516 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1518 if ( m_timemap_cursor != m_timemap_end )
1520 result = m_timemap_cursor++->second;
1526 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1528 if ( m_timemap_cursor != m_timemap_end )
1530 result = m_timemap_cursor++->second->get();
1536 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1538 if ( m_timemap_cursor != m_timemap_end )
1540 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1546 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1548 if ( m_timemap_cursor != m_timemap_end )
1550 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1551 result = new eServiceEvent();
1552 return result->parseFrom(&ev, currentQueryTsidOnid);
1557 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, ePtr<eServiceEvent> &ptr, ePyObject nowTime, ePyObject service_name )
1561 while(pos < argcount)
1563 bool inc_refcount=false;
1564 switch(argstring[pos])
1566 case '0': // PyLong 0
1567 tmp = PyLong_FromLong(0);
1569 case 'I': // Event Id
1570 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1572 case 'B': // Event Begin Time
1573 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1575 case 'D': // Event Duration
1576 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1578 case 'T': // Event Title
1579 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1581 case 'S': // Event Short Description
1582 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1584 case 'E': // Event Extended Description
1585 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1587 case 'C': // Current Time
1589 inc_refcount = true;
1591 case 'R': // service reference string
1593 inc_refcount = true;
1595 case 'N': // service name
1597 inc_refcount = true;
1602 inc_refcount = true;
1606 PyTuple_SET_ITEM(tuple, pos++, tmp);
1610 int handleEvent(ePtr<eServiceEvent> &ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1614 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1615 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1619 Py_DECREF(service_name);
1622 Py_DECREF(convertFuncArgs);
1623 Py_DECREF(dest_list);
1624 PyErr_SetString(PyExc_StandardError,
1625 "error in convertFunc execute");
1626 eDebug("error in convertFunc execute");
1629 PyList_Append(dest_list, result);
1634 ePyObject tuple = PyTuple_New(argcount);
1635 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1636 PyList_Append(dest_list, tuple);
1642 // here we get a python list
1643 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1646 // B = Event Begin Time
1647 // D = Event Duration
1649 // S = Event Short Description
1650 // E = Event Extended Description
1652 // R = Service Reference
1654 // then for each service follows a tuple
1655 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1656 // the second is the type of query
1658 // -1 = event before given start_time
1659 // 0 = event intersects given start_time
1660 // +1 = event after given start_time
1662 // when type is eventid it is the event_id
1663 // when type is time then it is the start_time ( 0 for now_time )
1664 // the fourth is the end_time .. ( optional .. for query all events in time range)
1666 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1668 ePyObject convertFuncArgs;
1670 char *argstring=NULL;
1671 if (!PyList_Check(list))
1673 PyErr_SetString(PyExc_StandardError,
1679 int listSize=PyList_Size(list);
1682 PyErr_SetString(PyExc_StandardError,
1683 "not params given");
1684 eDebug("not params given");
1689 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1690 if (PyString_Check(argv))
1692 argstring = PyString_AS_STRING(argv);
1696 argstring = "I"; // just event id as default
1697 argcount = strlen(argstring);
1698 // eDebug("have %d args('%s')", argcount, argstring);
1702 if (!PyCallable_Check(convertFunc))
1704 PyErr_SetString(PyExc_StandardError,
1705 "convertFunc must be callable");
1706 eDebug("convertFunc is not callable");
1709 convertFuncArgs = PyTuple_New(argcount);
1712 ePyObject nowTime = strchr(argstring, 'C') ?
1713 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1716 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1719 ePyObject dest_list=PyList_New(0);
1720 while(listSize > listIt)
1722 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1723 if (PyTuple_Check(item))
1725 bool service_changed=false;
1730 int tupleSize=PyTuple_Size(item);
1733 while(tupleSize > tupleIt) // parse query args
1735 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1740 if (!PyString_Check(entry))
1742 eDebug("tuple entry 0 is no a string");
1749 type=PyInt_AsLong(entry);
1750 if (type < -1 || type > 2)
1752 eDebug("unknown type %d", type);
1757 event_id=stime=PyInt_AsLong(entry);
1760 minutes=PyInt_AsLong(entry);
1763 eDebug("unneeded extra argument");
1767 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1768 if (ref.type != eServiceReference::idDVB)
1770 eDebug("service reference for epg query is not valid");
1774 // redirect subservice querys to parent service
1775 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1776 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1778 eServiceCenterPtr service_center;
1779 if (!eServiceCenter::getPrivInstance(service_center))
1781 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1782 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1783 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1784 dvb_ref.setParentServiceID(eServiceID(0));
1786 service = PyString_FromString(dvb_ref.toString().c_str());
1787 service_changed = true;
1791 ePyObject service_name;
1792 if (must_get_service_name)
1794 ePtr<iStaticServiceInformation> sptr;
1795 eServiceCenterPtr service_center;
1796 eServiceCenter::getPrivInstance(service_center);
1799 service_center->info(ref, sptr);
1803 sptr->getName(ref, name);
1805 service_name = PyString_FromString(name.c_str());
1809 service_name = PyString_FromString("<n/a>");
1814 if (!startTimeQuery(ref, stime, minutes))
1816 ePtr<eServiceEvent> ptr;
1817 while (!getNextTimeEntry(ptr))
1819 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1830 ePtr<eServiceEvent> ptr;
1834 lookupEventId(ref, event_id, ptr);
1836 lookupEventTime(ref, stime, ptr, type);
1838 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1841 if (service_changed)
1844 Py_DECREF(service_name);
1849 if (convertFuncArgs)
1850 Py_DECREF(convertFuncArgs);
1856 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, ePyObject service_name, ePyObject service_reference)
1860 while(pos < argcount)
1862 bool inc_refcount=false;
1863 switch(argstring[pos])
1865 case '0': // PyLong 0
1866 tmp = PyLong_FromLong(0);
1868 case 'I': // Event Id
1869 tmp = PyLong_FromLong(evData->getEventID());
1871 case 'B': // Event Begin Time
1873 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1875 tmp = PyLong_FromLong(evData->getStartTime());
1877 case 'D': // Event Duration
1879 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1881 tmp = PyLong_FromLong(evData->getDuration());
1883 case 'T': // Event Title
1884 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1886 case 'S': // Event Short Description
1887 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1889 case 'E': // Event Extended Description
1890 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1892 case 'R': // service reference string
1893 tmp = service_reference;
1894 inc_refcount = true;
1896 case 'N': // service name
1898 inc_refcount = true;
1904 inc_refcount = true;
1908 PyTuple_SET_ITEM(tuple, pos++, tmp);
1912 // here we get a python tuple
1913 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1915 // B = Event Begin Time
1916 // D = Event Duration
1918 // S = Event Short Description
1919 // E = Event Extended Description
1920 // R = Service Reference
1922 // the second tuple entry is the MAX matches value
1923 // the third tuple entry is the type of query
1924 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1925 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1926 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1927 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1928 // the fourth is the servicereference string
1929 // the fifth is the eventid
1930 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1931 // the fourth is the search text
1933 // 0 = case sensitive (CASE_CHECK)
1934 // 1 = case insensitive (NO_CASECHECK)
1936 PyObject *eEPGCache::search(ePyObject arg)
1942 const char *argstring=0;
1946 bool needServiceEvent=false;
1949 if (PyTuple_Check(arg))
1951 int tuplesize=PyTuple_Size(arg);
1954 ePyObject obj = PyTuple_GET_ITEM(arg,0);
1955 if (PyString_Check(obj))
1957 argcount = PyString_GET_SIZE(obj);
1958 argstring = PyString_AS_STRING(obj);
1959 for (int i=0; i < argcount; ++i)
1960 switch(argstring[i])
1965 needServiceEvent=true;
1972 PyErr_SetString(PyExc_StandardError,
1974 eDebug("tuple arg 0 is not a string");
1979 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1982 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1983 if (tuplesize > 4 && querytype == 0)
1985 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
1986 if (PyString_Check(obj))
1988 refstr = PyString_AS_STRING(obj);
1989 eServiceReferenceDVB ref(refstr);
1992 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1993 singleLock s(cache_lock);
1994 const eventData *evData = 0;
1995 lookupEventId(ref, eventid, evData);
1998 __u8 *data = evData->EITdata;
1999 int tmp = evData->ByteSize-12;
2000 __u32 *p = (__u32*)(data+12);
2001 // search short and extended event descriptors
2005 descriptorMap::iterator it =
2006 eventData::descriptors.find(crc);
2007 if (it != eventData::descriptors.end())
2009 __u8 *descr_data = it->second.second;
2010 switch(descr_data[0])
2013 descr[++descridx]=crc;
2022 eDebug("event not found");
2026 PyErr_SetString(PyExc_StandardError,
2028 eDebug("tuple arg 4 is not a valid service reference string");
2034 PyErr_SetString(PyExc_StandardError,
2036 eDebug("tuple arg 4 is not a string");
2040 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2042 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2043 if (PyString_Check(obj))
2045 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2046 const char *str = PyString_AS_STRING(obj);
2047 int textlen = PyString_GET_SIZE(obj);
2049 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2051 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2052 singleLock s(cache_lock);
2053 for (descriptorMap::iterator it(eventData::descriptors.begin());
2054 it != eventData::descriptors.end() && descridx < 511; ++it)
2056 __u8 *data = it->second.second;
2057 if ( data[0] == 0x4D ) // short event descriptor
2059 int title_len = data[5];
2060 if ( querytype == 1 )
2062 if (title_len > textlen)
2064 else if (title_len < textlen)
2068 if ( !strncasecmp((const char*)data+6, str, title_len) )
2070 // std::string s((const char*)data+6, title_len);
2071 // eDebug("match1 %s %s", str, s.c_str() );
2072 descr[++descridx] = it->first;
2075 else if ( !strncmp((const char*)data+6, str, title_len) )
2077 // std::string s((const char*)data+6, title_len);
2078 // eDebug("match2 %s %s", str, s.c_str() );
2079 descr[++descridx] = it->first;
2085 while((title_len-idx) >= textlen)
2089 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2091 descr[++descridx] = it->first;
2092 // std::string s((const char*)data+6, title_len);
2093 // eDebug("match 3 %s %s", str, s.c_str() );
2096 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2098 descr[++descridx] = it->first;
2099 // std::string s((const char*)data+6, title_len);
2100 // eDebug("match 4 %s %s", str, s.c_str() );
2112 PyErr_SetString(PyExc_StandardError,
2114 eDebug("tuple arg 4 is not a string");
2120 PyErr_SetString(PyExc_StandardError,
2122 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2128 PyErr_SetString(PyExc_StandardError,
2130 eDebug("not enough args in tuple");
2136 PyErr_SetString(PyExc_StandardError,
2138 eDebug("arg 0 is not a tuple");
2142 ASSERT(descridx <= 512);
2146 int maxcount=maxmatches;
2147 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2148 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2149 // in this case we start searching with the base service
2150 bool first = ref.valid() ? true : false;
2151 singleLock s(cache_lock);
2152 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2153 while(cit != eventDB.end() && maxcount)
2155 if ( ref.valid() && !first && cit->first == ref )
2157 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2161 ePyObject service_name;
2162 ePyObject service_reference;
2163 timeMap &evmap = cit->second.second;
2165 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2167 int evid = evit->second->getEventID();
2168 if ( evid == eventid)
2170 __u8 *data = evit->second->EITdata;
2171 int tmp = evit->second->ByteSize-12;
2172 __u32 *p = (__u32*)(data+12);
2173 // check if any of our descriptor used by this event
2178 for ( int i=0; i <= descridx; ++i)
2180 if (descr[i] == crc32) // found...
2185 if ( (querytype == 0 && cnt == descridx) ||
2186 ((querytype == 1 || querytype == 2) && cnt != -1) )
2188 const uniqueEPGKey &service = cit->first;
2189 eServiceReference ref =
2190 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2193 // create servive event
2194 ePtr<eServiceEvent> ptr;
2195 if (needServiceEvent)
2197 lookupEventId(ref, evid, ptr);
2199 eDebug("event not found !!!!!!!!!!!");
2201 // create service name
2202 if (!service_name && strchr(argstring,'N'))
2204 ePtr<iStaticServiceInformation> sptr;
2205 eServiceCenterPtr service_center;
2206 eServiceCenter::getPrivInstance(service_center);
2209 service_center->info(ref, sptr);
2213 sptr->getName(ref, name);
2215 service_name = PyString_FromString(name.c_str());
2219 service_name = PyString_FromString("<n/a>");
2221 // create servicereference string
2222 if (!service_reference && strchr(argstring,'R'))
2223 service_reference = PyString_FromString(ref.toString().c_str());
2226 ret = PyList_New(0);
2228 ePyObject tuple = PyTuple_New(argcount);
2230 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2231 PyList_Append(ret, tuple);
2238 Py_DECREF(service_name);
2239 if (service_reference)
2240 Py_DECREF(service_reference);
2243 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2245 cit=eventDB.begin();
2258 #ifdef ENABLE_PRIVATE_EPG
2259 #include <dvbsi++/descriptor_tag.h>
2260 #include <dvbsi++/unknown_descriptor.h>
2261 #include <dvbsi++/private_data_specifier_descriptor.h>
2263 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2265 ePtr<eTable<ProgramMapSection> > ptr;
2266 if (!pmthandler->getPMT(ptr) && ptr)
2268 std::vector<ProgramMapSection*>::const_iterator i;
2269 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2271 const ProgramMapSection &pmt = **i;
2273 ElementaryStreamInfoConstIterator es;
2274 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2277 switch ((*es)->getType())
2279 case 0x05: // private
2280 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2281 desc != (*es)->getDescriptors()->end(); ++desc)
2283 switch ((*desc)->getTag())
2285 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2286 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2291 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2292 int descr_len = descr->getLength();
2295 uint8_t data[descr_len+2];
2296 descr->writeToBuffer(data);
2297 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2311 eServiceReferenceDVB ref;
2312 if (!pmthandler->getServiceReference(ref))
2314 int pid = (*es)->getPid();
2315 messages.send(Message(Message::got_private_pid, ref, pid));
2323 eDebug("PMTready but no pmt!!");
2330 date_time( const date_time &a )
2332 memcpy(data, a.data, 5);
2335 date_time( const __u8 data[5])
2337 memcpy(this->data, data, 5);
2338 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2343 const __u8& operator[](int pos) const
2349 struct less_datetime
2351 bool operator()( const date_time &a, const date_time &b ) const
2353 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2357 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2359 contentMap &content_time_table = content_time_tables[current_service];
2360 singleLock s(cache_lock);
2361 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2362 eventMap &evMap = eventDB[current_service].first;
2363 timeMap &tmMap = eventDB[current_service].second;
2365 int content_id = data[ptr++] << 24;
2366 content_id |= data[ptr++] << 16;
2367 content_id |= data[ptr++] << 8;
2368 content_id |= data[ptr++];
2370 contentTimeMap &time_event_map =
2371 content_time_table[content_id];
2372 for ( contentTimeMap::iterator it( time_event_map.begin() );
2373 it != time_event_map.end(); ++it )
2375 eventMap::iterator evIt( evMap.find(it->second.second) );
2376 if ( evIt != evMap.end() )
2378 delete evIt->second;
2381 tmMap.erase(it->second.first);
2383 time_event_map.clear();
2386 memcpy(duration, data+ptr, 3);
2389 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2391 const __u8 *descriptors[65];
2392 const __u8 **pdescr = descriptors;
2394 int descriptors_length = (data[ptr++]&0x0F) << 8;
2395 descriptors_length |= data[ptr++];
2396 while ( descriptors_length > 0 )
2398 int descr_type = data[ptr];
2399 int descr_len = data[ptr+1];
2400 descriptors_length -= (descr_len+2);
2401 if ( descr_type == 0xf2 )
2404 int tsid = data[ptr++] << 8;
2405 tsid |= data[ptr++];
2406 int onid = data[ptr++] << 8;
2407 onid |= data[ptr++];
2408 int sid = data[ptr++] << 8;
2411 // WORKAROUND for wrong transmitted epg data (01.08.2006)
2414 switch( (tsid << 16) | sid )
2416 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2417 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2418 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2419 case 0x0300f5: sid = 0xdc; break;
2420 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2421 case 0x1100d3: sid = 0xe3; break;
2424 ////////////////////////////////////////////
2426 uniqueEPGKey service( sid, onid, tsid );
2428 while( descr_len > 0 )
2431 datetime[0] = data[ptr++];
2432 datetime[1] = data[ptr++];
2433 int tmp_len = data[ptr++];
2435 while( tmp_len > 0 )
2437 memcpy(datetime+2, data+ptr, 3);
2441 start_times[datetime].push_back(service);
2452 ASSERT(pdescr <= &descriptors[65])
2454 eit_event_struct *ev_struct = (eit_event_struct*) event;
2455 ev_struct->running_status = 0;
2456 ev_struct->free_CA_mode = 1;
2457 memcpy(event+7, duration, 3);
2459 const __u8 **d=descriptors;
2460 while ( d < pdescr )
2462 memcpy(event+ptr, *d, ((*d)[1])+2);
2466 ASSERT(ptr <= 4098);
2467 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2469 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2470 if ( (it->first.tm + duration_sec) < now )
2472 memcpy(event+2, it->first.data, 5);
2475 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2477 event[bptr++] = 0x4A;
2478 __u8 *len = event+(bptr++);
2479 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2480 event[bptr++] = (i->tsid & 0xFF);
2481 event[bptr++] = (i->onid & 0xFF00) >> 8;
2482 event[bptr++] = (i->onid & 0xFF);
2483 event[bptr++] = (i->sid & 0xFF00) >> 8;
2484 event[bptr++] = (i->sid & 0xFF);
2485 event[bptr++] = 0xB0;
2486 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2487 *len = ((event+bptr) - len)-1;
2489 int llen = bptr - 12;
2490 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2491 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2493 time_t stime = it->first.tm;
2494 while( tmMap.find(stime) != tmMap.end() )
2496 event[6] += (stime - it->first.tm);
2498 while( evMap.find(event_id) != evMap.end() )
2500 event[0] = (event_id & 0xFF00) >> 8;
2501 event[1] = (event_id & 0xFF);
2502 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2503 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2504 evMap[event_id] = d;
2509 void eEPGCache::channel_data::startPrivateReader()
2511 eDVBSectionFilterMask mask;
2512 memset(&mask, 0, sizeof(mask));
2513 mask.pid = m_PrivatePid;
2514 mask.flags = eDVBSectionFilterMask::rfCRC;
2515 mask.data[0] = 0xA0;
2516 mask.mask[0] = 0xFF;
2517 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2518 if (m_PrevVersion != -1)
2520 mask.data[3] = m_PrevVersion << 1;
2521 mask.mask[3] = 0x3E;
2522 mask.mode[3] = 0x3E;
2524 seenPrivateSections.clear();
2526 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2527 m_PrivateReader->start(mask);
2530 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2532 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2534 cache->privateSectionRead(m_PrivateService, data);
2535 seenPrivateSections.insert(data[6]);
2537 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2539 eDebug("[EPGC] private finished");
2540 eDVBChannelID chid = channel->getChannelID();
2541 int tmp = chid.original_network_id.get();
2542 tmp |= 0x80000000; // we use highest bit as private epg indicator
2543 chid.original_network_id = tmp;
2544 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2545 m_PrevVersion = (data[5] & 0x3E) >> 1;
2546 startPrivateReader();
2550 #endif // ENABLE_PRIVATE_EPG
2552 #ifdef ENABLE_MHW_EPG
2553 void eEPGCache::channel_data::cleanup()
2558 m_program_ids.clear();
2561 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2563 // Names in mhw structs are not strings as they are not '\0' terminated.
2564 // This function converts the mhw name into a string.
2565 // Constraint: "length of out" = "length of in" + 1.
2567 for ( i=0; i < len_in; i++ )
2571 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2578 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2581 return_time[0] = toBCD( hours );
2582 return_time[1] = toBCD( minutes );
2586 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2588 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2591 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2592 // For date plus time of day
2594 // Remove offset in mhw time.
2595 __u8 local_hours = hours;
2598 else if ( hours >= 8 )
2601 // As far as we know all mhw time data is sent in central Europe time zone.
2602 // So, temporarily set timezone to western europe
2603 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2605 char *old_tz = getenv( "TZ" );
2606 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2610 localtime_r(&dt, &localnow);
2614 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2616 if (local_hours <= 5)
2619 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2620 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2623 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2625 if ( old_tz == NULL )
2631 // Calculate MJD according to annex in ETSI EN 300 468
2633 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2635 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2636 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2638 return_time[0] = (mjd & 0xFF00)>>8;
2639 return_time[1] = mjd & 0xFF;
2641 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2644 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2645 // data is borrowed from calling proc to save memory space.
2648 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2649 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2650 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2652 eit_t *packet = (eit_t *) data;
2653 packet->table_id = 0x50;
2654 packet->section_syntax_indicator = 1;
2655 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2656 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2657 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2658 packet->current_next_indicator = 0;
2659 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2660 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2661 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2662 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2663 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2664 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2665 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2666 packet->segment_last_table_id = 0x50;
2668 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2669 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2670 int prog_title_length = prog_title.length();
2672 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2673 prog_title_length + 1;
2675 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2676 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2677 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2681 u_char *data = (u_char*) event_data;
2682 data[2] = itTitle->second.mhw2_mjd_hi;
2683 data[3] = itTitle->second.mhw2_mjd_lo;
2684 data[4] = itTitle->second.mhw2_hours;
2685 data[5] = itTitle->second.mhw2_minutes;
2686 data[6] = itTitle->second.mhw2_seconds;
2687 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2691 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2692 (u_char *) event_data + 2 );
2693 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2696 event_data->running_status = 0;
2697 event_data->free_CA_mode = 0;
2698 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2700 eit_short_event_descriptor_struct *short_event_descriptor =
2701 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2702 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2703 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2704 prog_title_length - 1;
2705 short_event_descriptor->language_code_1 = 'e';
2706 short_event_descriptor->language_code_2 = 'n';
2707 short_event_descriptor->language_code_3 = 'g';
2708 short_event_descriptor->event_name_length = prog_title_length;
2709 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2710 memcpy(event_name, prog_title.c_str(), prog_title_length);
2713 event_name[prog_title_length] = 0;
2715 if ( sumText.length() > 0 )
2716 // There is summary info
2718 unsigned int sum_length = sumText.length();
2719 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2720 // Store summary in short event descriptor
2722 // Increase all relevant lengths
2723 event_name[prog_title_length] = sum_length;
2724 short_event_descriptor->descriptor_length += sum_length;
2725 packet_length += sum_length;
2726 descr_ll += sum_length;
2727 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2730 // Store summary in extended event descriptors
2732 int remaining_sum_length = sumText.length();
2733 int nbr_descr = int(remaining_sum_length/247) + 1;
2734 for ( int i=0; i < nbr_descr; i++)
2735 // Loop once per extended event descriptor
2737 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2738 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2739 remaining_sum_length -= sum_length;
2740 packet_length += 8 + sum_length;
2741 descr_ll += 8 + sum_length;
2743 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2744 ext_event_descriptor->descriptor_length = sum_length + 6;
2745 ext_event_descriptor->descriptor_number = i;
2746 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2747 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2748 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2749 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2750 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2752 the_text[-1] = sum_length;
2753 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2760 // Add content descriptor
2761 u_char *descriptor = (u_char *) data + packet_length;
2766 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2767 if ( content_descr.find( "FILM" ) != std::string::npos )
2769 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2772 descriptor[0] = 0x54;
2774 descriptor[2] = content_id;
2778 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2779 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2781 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2782 packet->section_length_lo = (packet_length - 3)&0xff;
2784 // Feed the data to eEPGCache::sectionRead()
2785 cache->sectionRead( data, MHW, this );
2788 void eEPGCache::channel_data::startTimeout(int msec)
2790 m_MHWTimeoutTimer.start(msec,true);
2791 m_MHWTimeoutet=false;
2794 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2796 m_MHWFilterMask.pid = pid;
2797 m_MHWFilterMask.data[0] = tid;
2798 m_MHWReader->start(m_MHWFilterMask);
2799 // eDebug("start 0x%02x 0x%02x", pid, tid);
2802 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2804 m_MHWFilterMask2.pid = pid;
2805 m_MHWFilterMask2.data[0] = tid;
2808 m_MHWFilterMask2.data[1] = ext;
2809 m_MHWFilterMask2.mask[1] = 0xFF;
2810 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2814 m_MHWFilterMask2.data[1] = 0;
2815 m_MHWFilterMask2.mask[1] = 0;
2816 // eDebug("start 0x%02x 0x%02x", pid, tid);
2818 m_MHWReader2->start(m_MHWFilterMask2);
2821 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2824 m_MHWReader2->stop();
2826 if ( state > 1 || // aborted
2827 // have si data.. so we dont read mhw data
2828 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2830 eDebug("[EPGC] mhw aborted %d", state);
2832 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2835 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2836 int record_size = sizeof( mhw_channel_name_t );
2837 int nbr_records = int (len/record_size);
2839 for ( int i = 0; i < nbr_records; i++ )
2841 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2842 m_channels.push_back( *channel );
2846 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2848 // Channels table has been read, start reading the themes table.
2849 startMHWReader(0xD3, 0x92);
2852 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2855 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2856 int record_size = sizeof( mhw_theme_name_t );
2857 int nbr_records = int (len/record_size);
2859 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2862 for ( int i = 0; i < nbr_records; i++ )
2864 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2865 if ( i >= next_idx )
2869 next_idx = (__u8) *(data + 3 + idx_ptr);
2875 m_themes[idx+sub_idx] = *theme;
2877 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2878 // Themes table has been read, start reading the titles table.
2879 startMHWReader(0xD2, 0x90);
2883 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2886 mhw_title_t *title = (mhw_title_t*) data;
2888 if ( title->channel_id == 0xFF ) // Separator
2889 return; // Continue reading of the current table.
2892 // Create unique key per title
2893 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2894 (title->ms.minutes);
2895 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2896 ((title->program_id_ml)<<8)|(title->program_id_lo);
2898 if ( m_titles.find( title_id ) == m_titles.end() )
2901 title->mhw2_mjd_hi = 0;
2902 title->mhw2_mjd_lo = 0;
2903 title->mhw2_duration_hi = 0;
2904 title->mhw2_duration_lo = 0;
2905 m_titles[ title_id ] = *title;
2906 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2907 // program_ids will be used to gather summaries.
2908 m_program_ids[ program_id ] = title_id;
2909 return; // Continue reading of the current table.
2911 else if (!checkTimeout())
2914 if ( !m_program_ids.empty())
2916 // Titles table has been read, there are summaries to read.
2917 // Start reading summaries, store corresponding titles on the fly.
2918 startMHWReader(0xD3, 0x90);
2919 eDebug("[EPGC] mhw %d titles(%d with summary) found",
2921 m_program_ids.size());
2926 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2929 mhw_summary_t *summary = (mhw_summary_t*) data;
2931 // Create unique key per record
2932 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2933 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2934 int len = ((data[1]&0xf)<<8) + data[2];
2936 // ugly workaround to convert const __u8* to char*
2938 memcpy(&tmp, &data, sizeof(void*));
2939 tmp[len+3] = 0; // Terminate as a string.
2941 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2942 if ( itProgid == m_program_ids.end() )
2943 { /* This part is to prevent to looping forever if some summaries are not received yet.
2944 There is a timeout of 4 sec. after the last successfully read summary. */
2945 if (!m_program_ids.empty() && !checkTimeout())
2946 return; // Continue reading of the current table.
2950 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2953 while((pos = the_text.find("\r\n")) != std::string::npos)
2954 the_text.replace(pos, 2, " ");
2956 // Find corresponding title, store title and summary in epgcache.
2957 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2958 if ( itTitle != m_titles.end() )
2961 storeTitle( itTitle, the_text, data );
2962 m_titles.erase( itTitle );
2964 m_program_ids.erase( itProgid );
2965 if ( !m_program_ids.empty() )
2966 return; // Continue reading of the current table.
2969 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
2970 eDVBLocalTimeHandler::getInstance()->nowTime(),
2971 m_program_ids.size());
2972 // Summaries have been read, titles that have summaries have been stored.
2973 // Now store titles that do not have summaries.
2974 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
2975 storeTitle( itTitle, "", data );
2979 m_MHWReader->stop();
2984 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
2986 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
2989 m_MHWReader->stop();
2991 if ( state > 1 || // aborted
2992 // have si data.. so we dont read mhw data
2993 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
2995 eDebug("[EPGC] mhw2 aborted %d", state);
2997 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3000 int num_channels = data[120];
3003 int ptr = 121 + 6 * num_channels;
3006 for( int chid = 0; chid < num_channels; ++chid )
3008 ptr += ( data[ptr] & 0x0f ) + 1;
3018 // data seems consistent...
3019 const __u8 *tmp = data+121;
3020 for (int i=0; i < num_channels; ++i)
3022 mhw_channel_name_t channel;
3023 channel.transport_stream_id_hi = *(tmp++);
3024 channel.transport_stream_id_lo = *(tmp++);
3025 channel.channel_id_hi = *(tmp++);
3026 channel.channel_id_lo = *(tmp++);
3027 #warning FIXME hardcoded network_id in mhw2 epg
3028 channel.network_id_hi = 0; // hardcoded astra 19.2
3029 channel.network_id_lo = 1;
3030 m_channels.push_back(channel);
3033 for (int i=0; i < num_channels; ++i)
3035 mhw_channel_name_t &channel = m_channels[i];
3036 int channel_name_len=*(tmp++)&0x0f;
3038 for (; x < channel_name_len; ++x)
3039 channel.name[x]=*(tmp++);
3040 channel.name[x+1]=0;
3043 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3045 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3048 eDebug("[EPGC] mhw2 themes nyi");
3050 else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3055 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3057 if(data[dataLen-1] != 0xff)
3059 while( pos < dataLen )
3068 if( data[pos] > 0xc0 )
3070 pos += ( data[pos] - 0xc0 );
3074 if( data[pos] == 0xff )
3090 // data seems consistent...
3095 title.channel_id = data[pos]+1;
3096 title.program_id_ml = data[pos+1];
3097 title.program_id_lo = data[pos+2];
3098 title.mhw2_mjd_hi = data[pos+3];
3099 title.mhw2_mjd_lo = data[pos+4];
3100 title.mhw2_hours = data[pos+5];
3101 title.mhw2_minutes = data[pos+6];
3102 title.mhw2_seconds = data[pos+7];
3103 int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3104 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3105 title.mhw2_duration_lo = duration&0xFF;
3106 __u8 slen = data[pos+10] & 0x3f;
3107 __u8 *dest = ((__u8*)title.title)-4;
3108 memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3109 memset(dest+slen, 0x20, 33-slen);
3111 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3112 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3114 // Create unique key per title
3115 __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3117 // eDebug("program_id: %08x, %s", program_id,
3118 // std::string((const char *)title.title, (int)(slen > 23 ? 23 : slen)).c_str());
3122 if ( m_titles.find( title_id ) == m_titles.end() )
3125 m_titles[ title_id ] = title;
3126 if (summary_id != 0xFFFF && // no summary avail
3127 m_program_ids.find(summary_id) == m_program_ids.end())
3129 m_program_ids[ summary_id ] = title_id;
3134 if ( !checkTimeout() )
3135 continue; // Continue reading of the current table.
3143 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3144 if (!m_program_ids.empty())
3146 // Titles table has been read, there are summaries to read.
3147 // Start reading summaries, store corresponding titles on the fly.
3148 startMHWReader2(0x236, 0x96);
3156 else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3159 int len, loop, pos, lenline;
3168 loop = data[pos] & 0x0f;
3173 for( ; loop > 0; --loop )
3175 if( dataLen > (pos+len) )
3177 lenline = data[pos+len];
3186 else if (!checkTimeout())
3187 return; // continue reading
3188 if (valid && !checkTimeout())
3190 // data seems consistent...
3191 __u32 summary_id = (data[3]<<8)|data[4];
3193 // ugly workaround to convert const __u8* to char*
3195 memcpy(&tmp, &data, sizeof(void*));
3200 loop = tmp[pos] & 0x0f;
3202 for( ; loop > 0; loop -- )
3204 lenline = tmp[pos+len];
3213 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( summary_id ) );
3214 if ( itProgid == m_program_ids.end() )
3215 { /* This part is to prevent to looping forever if some summaries are not received yet.
3216 There is a timeout of 4 sec. after the last successfully read summary. */
3218 if ( !m_program_ids.empty() && !checkTimeout() )
3219 return; // Continue reading of the current table.
3224 std::string the_text = (char *) (data + pos + 1);
3226 // Find corresponding title, store title and summary in epgcache.
3227 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3228 if ( itTitle != m_titles.end() )
3230 storeTitle( itTitle, the_text, data );
3231 m_titles.erase( itTitle );
3233 m_program_ids.erase( itProgid );
3234 if ( !m_program_ids.empty() )
3235 return; // Continue reading of the current table.
3239 if (isRunning & eEPGCache::MHW)
3241 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3243 // Channels table has been read, start reading the themes table.
3244 startMHWReader2(0x231, 0xC8, 1);
3247 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3249 // Themes table has been read, start reading the titles table.
3250 startMHWReader2(0x234, 0xe6);
3255 // Summaries have been read, titles that have summaries have been stored.
3256 // Now store titles that do not have summaries.
3257 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3258 storeTitle( itTitle, "", data );
3259 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3260 eDVBLocalTimeHandler::getInstance()->nowTime(),
3261 m_program_ids.size());
3268 m_MHWReader2->stop();