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 = eventDB[DBIt->first].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 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
787 eDVBChannel *channel = (eDVBChannel*) it->first;
788 channel_data *data = it->second;
789 eDVBChannelID chid = channel->getChannelID();
790 if ( chid.transport_stream_id.get() == msg.service.tsid &&
791 chid.original_network_id.get() == msg.service.onid &&
792 data->m_PrivatePid == -1 )
794 data->m_PrevVersion = -1;
795 data->m_PrivatePid = msg.pid;
796 data->m_PrivateService = msg.service;
797 int onid = chid.original_network_id.get();
798 onid |= 0x80000000; // we use highest bit as private epg indicator
799 chid.original_network_id = onid;
800 updateMap::iterator It = channelLastUpdated.find( chid );
801 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
802 if (update < ZAP_DELAY)
804 data->startPrivateTimer.start(update, 1);
806 eDebug("[EPGC] next private update in %i min", update/60000);
807 else if (update >= 1000)
808 eDebug("[EPGC] next private update in %i sec", update/1000);
815 case Message::timeChanged:
819 eDebug("unhandled EPGCache Message!!");
824 void eEPGCache::thread()
834 void eEPGCache::load()
836 singleLock s(cache_lock);
837 FILE *f = fopen("/hdd/epg.dat", "r");
843 unsigned char md5_saved[16];
844 unsigned char md5[16];
847 if (!md5_file("/hdd/epg.dat", 1, md5))
849 FILE *f = fopen("/hdd/epg.dat.md5", "r");
852 fread( md5_saved, 16, 1, f);
854 if ( !memcmp(md5_saved, md5, 16) )
861 unsigned int magic=0;
862 fread( &magic, sizeof(int), 1, f);
863 if (magic != 0x98765432)
865 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
870 fread( text1, 13, 1, f);
871 if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
873 fread( &size, sizeof(int), 1, f);
880 fread( &key, sizeof(uniqueEPGKey), 1, f);
881 fread( &size, sizeof(int), 1, f);
887 fread( &type, sizeof(__u8), 1, f);
888 fread( &len, sizeof(__u8), 1, f);
889 event = new eventData(0, len, type);
890 event->EITdata = new __u8[len];
891 eventData::CacheSize+=len;
892 fread( event->EITdata, len, 1, f);
893 evMap[ event->getEventID() ]=event;
894 tmMap[ event->getStartTime() ]=event;
897 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
900 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
901 #ifdef ENABLE_PRIVATE_EPG
903 fread( text2, 11, 1, f);
904 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
907 fread( &size, sizeof(int), 1, f);
912 fread( &key, sizeof(uniqueEPGKey), 1, f);
913 eventMap &evMap=eventDB[key].first;
914 fread( &size, sizeof(int), 1, f);
919 fread( &content_id, sizeof(int), 1, f);
920 fread( &size, sizeof(int), 1, f);
925 fread( &time1, sizeof(time_t), 1, f);
926 fread( &time2, sizeof(time_t), 1, f);
927 fread( &event_id, sizeof(__u16), 1, f);
928 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
929 eventMap::iterator it =
930 evMap.find(event_id);
931 if (it != evMap.end())
932 it->second->type = PRIVATE;
937 #endif // ENABLE_PRIVATE_EPG
940 eDebug("[EPGC] don't read old epg database");
946 void eEPGCache::save()
950 if (statfs("/hdd", &s)<0)
958 // prevent writes to builtin flash
959 if ( tmp < 1024*1024*50 ) // storage size < 50MB
962 // check for enough free space on storage
965 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
968 FILE *f = fopen("/hdd/epg.dat", "w");
972 unsigned int magic = 0x98765432;
973 fwrite( &magic, sizeof(int), 1, f);
974 const char *text = "ENIGMA_EPG_V5";
975 fwrite( text, 13, 1, f );
976 int size = eventDB.size();
977 fwrite( &size, sizeof(int), 1, f );
978 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
980 timeMap &timemap = service_it->second.second;
981 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
982 size = timemap.size();
983 fwrite( &size, sizeof(int), 1, f);
984 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
986 __u8 len = time_it->second->ByteSize;
987 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
988 fwrite( &len, sizeof(__u8), 1, f);
989 fwrite( time_it->second->EITdata, len, 1, f);
993 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
995 #ifdef ENABLE_PRIVATE_EPG
996 const char* text3 = "PRIVATE_EPG";
997 fwrite( text3, 11, 1, f );
998 size = content_time_tables.size();
999 fwrite( &size, sizeof(int), 1, f);
1000 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1002 contentMap &content_time_table = a->second;
1003 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1004 int size = content_time_table.size();
1005 fwrite( &size, sizeof(int), 1, f);
1006 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1008 int size = i->second.size();
1009 fwrite( &i->first, sizeof(int), 1, f);
1010 fwrite( &size, sizeof(int), 1, f);
1011 for ( contentTimeMap::iterator it(i->second.begin());
1012 it != i->second.end(); ++it )
1014 fwrite( &it->first, sizeof(time_t), 1, f);
1015 fwrite( &it->second.first, sizeof(time_t), 1, f);
1016 fwrite( &it->second.second, sizeof(__u16), 1, f);
1023 unsigned char md5[16];
1024 if (!md5_file("/hdd/epg.dat", 1, md5))
1026 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1029 fwrite( md5, 16, 1, f);
1037 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1039 ,abortTimer(ml), zapTimer(ml), state(0)
1040 ,isRunning(0), haveData(0)
1041 #ifdef ENABLE_PRIVATE_EPG
1042 ,startPrivateTimer(ml)
1044 #ifdef ENABLE_MHW_EPG
1045 ,m_MHWTimeoutTimer(ml)
1048 #ifdef ENABLE_MHW_EPG
1049 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1051 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1052 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1053 #ifdef ENABLE_PRIVATE_EPG
1054 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1056 pthread_mutex_init(&channel_active, 0);
1059 bool eEPGCache::channel_data::finishEPG()
1061 if (!isRunning) // epg ready
1063 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1064 zapTimer.start(UPDATE_INTERVAL, 1);
1065 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1066 for (int i=0; i < 3; ++i)
1068 seenSections[i].clear();
1069 calcedSections[i].clear();
1071 singleLock l(cache->cache_lock);
1072 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1073 #ifdef ENABLE_MHW_EPG
1081 void eEPGCache::channel_data::startEPG()
1083 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1086 for (int i=0; i < 3; ++i)
1088 seenSections[i].clear();
1089 calcedSections[i].clear();
1092 eDVBSectionFilterMask mask;
1093 memset(&mask, 0, sizeof(mask));
1095 #ifdef ENABLE_MHW_EPG
1097 mask.data[0] = 0x91;
1098 mask.mask[0] = 0xFF;
1099 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1100 m_MHWReader->start(mask);
1102 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1105 mask.data[0] = 0xC8;
1106 mask.mask[0] = 0xFF;
1108 mask.mask[1] = 0xFF;
1109 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1110 m_MHWReader2->start(mask);
1112 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1118 mask.flags = eDVBSectionFilterMask::rfCRC;
1120 mask.data[0] = 0x4E;
1121 mask.mask[0] = 0xFE;
1122 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1123 m_NowNextReader->start(mask);
1124 isRunning |= NOWNEXT;
1126 mask.data[0] = 0x50;
1127 mask.mask[0] = 0xF0;
1128 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1129 m_ScheduleReader->start(mask);
1130 isRunning |= SCHEDULE;
1132 mask.data[0] = 0x60;
1133 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1134 m_ScheduleOtherReader->start(mask);
1135 isRunning |= SCHEDULE_OTHER;
1137 abortTimer.start(7000,true);
1140 void eEPGCache::channel_data::abortNonAvail()
1144 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1146 eDebug("[EPGC] abort non avail nownext reading");
1147 isRunning &= ~NOWNEXT;
1148 m_NowNextReader->stop();
1151 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1153 eDebug("[EPGC] abort non avail schedule reading");
1154 isRunning &= ~SCHEDULE;
1155 m_ScheduleReader->stop();
1158 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1160 eDebug("[EPGC] abort non avail schedule_other reading");
1161 isRunning &= ~SCHEDULE_OTHER;
1162 m_ScheduleOtherReader->stop();
1163 m_ScheduleOtherConn=0;
1165 #ifdef ENABLE_MHW_EPG
1166 if ( !(haveData&MHW) && (isRunning&MHW) )
1168 eDebug("[EPGC] abort non avail mhw reading");
1170 m_MHWReader->stop();
1172 m_MHWReader2->stop();
1177 abortTimer.start(90000, true);
1181 for (int i=0; i < 3; ++i)
1183 seenSections[i].clear();
1184 calcedSections[i].clear();
1191 void eEPGCache::channel_data::startChannel()
1193 pthread_mutex_lock(&channel_active);
1194 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1196 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1198 if (update < ZAP_DELAY)
1201 zapTimer.start(update, 1);
1202 if (update >= 60000)
1203 eDebug("[EPGC] next update in %i min", update/60000);
1204 else if (update >= 1000)
1205 eDebug("[EPGC] next update in %i sec", update/1000);
1208 void eEPGCache::channel_data::abortEPG()
1210 for (int i=0; i < 3; ++i)
1212 seenSections[i].clear();
1213 calcedSections[i].clear();
1219 eDebug("[EPGC] abort caching events !!");
1220 if (isRunning & SCHEDULE)
1222 isRunning &= ~SCHEDULE;
1223 m_ScheduleReader->stop();
1226 if (isRunning & NOWNEXT)
1228 isRunning &= ~NOWNEXT;
1229 m_NowNextReader->stop();
1232 if (isRunning & SCHEDULE_OTHER)
1234 isRunning &= ~SCHEDULE_OTHER;
1235 m_ScheduleOtherReader->stop();
1236 m_ScheduleOtherConn=0;
1238 #ifdef ENABLE_MHW_EPG
1239 if (isRunning & MHW)
1242 m_MHWReader->stop();
1244 m_MHWReader2->stop();
1249 #ifdef ENABLE_PRIVATE_EPG
1250 if (m_PrivateReader)
1251 m_PrivateReader->stop();
1255 pthread_mutex_unlock(&channel_active);
1258 void eEPGCache::channel_data::readData( const __u8 *data)
1262 iDVBSectionReader *reader=NULL;
1266 reader=m_NowNextReader;
1271 reader=m_ScheduleReader;
1276 reader=m_ScheduleOtherReader;
1277 source=SCHEDULE_OTHER;
1281 eDebug("[EPGC] unknown table_id !!!");
1284 tidMap &seenSections = this->seenSections[map];
1285 tidMap &calcedSections = this->calcedSections[map];
1286 if ( state == 1 && calcedSections == seenSections || state > 1 )
1288 eDebugNoNewLine("[EPGC] ");
1293 eDebugNoNewLine("nownext");
1297 eDebugNoNewLine("schedule");
1299 case SCHEDULE_OTHER:
1300 m_ScheduleOtherConn=0;
1301 eDebugNoNewLine("schedule other");
1303 default: eDebugNoNewLine("unknown");break;
1305 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1308 isRunning &= ~source;
1314 eit_t *eit = (eit_t*) data;
1315 __u32 sectionNo = data[0] << 24;
1316 sectionNo |= data[3] << 16;
1317 sectionNo |= data[4] << 8;
1318 sectionNo |= eit->section_number;
1320 tidMap::iterator it =
1321 seenSections.find(sectionNo);
1323 if ( it == seenSections.end() )
1325 seenSections.insert(sectionNo);
1326 calcedSections.insert(sectionNo);
1327 __u32 tmpval = sectionNo & 0xFFFFFF00;
1328 __u8 incr = source == NOWNEXT ? 1 : 8;
1329 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1331 if ( i == eit->section_number )
1333 for (int x=i; x <= eit->segment_last_section_number; ++x)
1334 calcedSections.insert(tmpval|(x&0xFF));
1337 calcedSections.insert(tmpval|(i&0xFF));
1339 cache->sectionRead(data, source, this);
1344 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1345 // if t == -1 we search the current event...
1347 singleLock s(cache_lock);
1348 uniqueEPGKey key(handleGroup(service));
1350 // check if EPG for this service is ready...
1351 eventCache::iterator It = eventDB.find( key );
1352 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1355 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1356 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1357 It->second.second.upper_bound(t); // just >
1358 if ( i != It->second.second.end() )
1360 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1362 timeMap::iterator x = i;
1364 if ( x != It->second.second.end() )
1366 time_t start_time = x->second->getStartTime();
1371 if (t > (start_time+x->second->getDuration()))
1386 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1388 singleLock s(cache_lock);
1389 const eventData *data=0;
1390 RESULT ret = lookupEventTime(service, t, data, direction);
1392 result = data->get();
1396 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1398 singleLock s(cache_lock);
1399 const eventData *data=0;
1400 RESULT ret = lookupEventTime(service, t, data, direction);
1402 result = new Event((uint8_t*)data->get());
1406 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1408 singleLock s(cache_lock);
1409 const eventData *data=0;
1410 RESULT ret = lookupEventTime(service, t, data, direction);
1413 Event ev((uint8_t*)data->get());
1414 result = new eServiceEvent();
1415 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1416 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1421 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1423 singleLock s(cache_lock);
1424 uniqueEPGKey key(handleGroup(service));
1426 eventCache::iterator It = eventDB.find( key );
1427 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1429 eventMap::iterator i( It->second.first.find( event_id ));
1430 if ( i != It->second.first.end() )
1438 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1444 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1446 singleLock s(cache_lock);
1447 const eventData *data=0;
1448 RESULT ret = lookupEventId(service, event_id, data);
1450 result = data->get();
1454 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1456 singleLock s(cache_lock);
1457 const eventData *data=0;
1458 RESULT ret = lookupEventId(service, event_id, data);
1460 result = new Event((uint8_t*)data->get());
1464 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1466 singleLock s(cache_lock);
1467 const eventData *data=0;
1468 RESULT ret = lookupEventId(service, event_id, data);
1471 Event ev((uint8_t*)data->get());
1472 result = new eServiceEvent();
1473 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1474 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1479 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1481 eventCache::iterator It = eventDB.find(handleGroup(service));
1482 if ( It != eventDB.end() && It->second.second.size() )
1484 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1487 m_timemap_cursor = It->second.second.lower_bound(begin);
1488 if ( m_timemap_cursor != It->second.second.end() )
1490 if ( m_timemap_cursor->second->getStartTime() != begin )
1492 timeMap::iterator x = m_timemap_cursor;
1494 if ( x != It->second.second.end() )
1496 time_t start_time = x->second->getStartTime();
1497 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1498 m_timemap_cursor = x;
1504 m_timemap_cursor = It->second.second.begin();
1505 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1506 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1512 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1514 if ( m_timemap_cursor != m_timemap_end )
1516 result = m_timemap_cursor++->second;
1522 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1524 if ( m_timemap_cursor != m_timemap_end )
1526 result = m_timemap_cursor++->second->get();
1532 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1534 if ( m_timemap_cursor != m_timemap_end )
1536 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1542 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1544 if ( m_timemap_cursor != m_timemap_end )
1546 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1547 result = new eServiceEvent();
1548 return result->parseFrom(&ev, currentQueryTsidOnid);
1553 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, ePtr<eServiceEvent> &ptr, ePyObject nowTime, ePyObject service_name )
1557 while(pos < argcount)
1559 bool inc_refcount=false;
1560 switch(argstring[pos])
1562 case '0': // PyLong 0
1563 tmp = PyLong_FromLong(0);
1565 case 'I': // Event Id
1566 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1568 case 'B': // Event Begin Time
1569 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1571 case 'D': // Event Duration
1572 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1574 case 'T': // Event Title
1575 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1577 case 'S': // Event Short Description
1578 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1580 case 'E': // Event Extended Description
1581 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1583 case 'C': // Current Time
1585 inc_refcount = true;
1587 case 'R': // service reference string
1589 inc_refcount = true;
1591 case 'N': // service name
1593 inc_refcount = true;
1598 inc_refcount = true;
1602 PyTuple_SET_ITEM(tuple, pos++, tmp);
1606 int handleEvent(ePtr<eServiceEvent> &ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1610 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1611 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1615 Py_DECREF(service_name);
1618 Py_DECREF(convertFuncArgs);
1619 Py_DECREF(dest_list);
1620 PyErr_SetString(PyExc_StandardError,
1621 "error in convertFunc execute");
1622 eDebug("error in convertFunc execute");
1625 PyList_Append(dest_list, result);
1630 ePyObject tuple = PyTuple_New(argcount);
1631 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1632 PyList_Append(dest_list, tuple);
1638 // here we get a python list
1639 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1642 // B = Event Begin Time
1643 // D = Event Duration
1645 // S = Event Short Description
1646 // E = Event Extended Description
1648 // R = Service Reference
1650 // then for each service follows a tuple
1651 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1652 // the second is the type of query
1654 // -1 = event before given start_time
1655 // 0 = event intersects given start_time
1656 // +1 = event after given start_time
1658 // when type is eventid it is the event_id
1659 // when type is time then it is the start_time ( 0 for now_time )
1660 // the fourth is the end_time .. ( optional .. for query all events in time range)
1662 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1664 ePyObject convertFuncArgs;
1666 char *argstring=NULL;
1667 if (!PyList_Check(list))
1669 PyErr_SetString(PyExc_StandardError,
1675 int listSize=PyList_Size(list);
1678 PyErr_SetString(PyExc_StandardError,
1679 "not params given");
1680 eDebug("not params given");
1685 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1686 if (PyString_Check(argv))
1688 argstring = PyString_AS_STRING(argv);
1692 argstring = "I"; // just event id as default
1693 argcount = strlen(argstring);
1694 // eDebug("have %d args('%s')", argcount, argstring);
1698 if (!PyCallable_Check(convertFunc))
1700 PyErr_SetString(PyExc_StandardError,
1701 "convertFunc must be callable");
1702 eDebug("convertFunc is not callable");
1705 convertFuncArgs = PyTuple_New(argcount);
1708 ePyObject nowTime = strchr(argstring, 'C') ?
1709 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1712 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1715 ePyObject dest_list=PyList_New(0);
1716 while(listSize > listIt)
1718 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1719 if (PyTuple_Check(item))
1721 bool service_changed=false;
1726 int tupleSize=PyTuple_Size(item);
1729 while(tupleSize > tupleIt) // parse query args
1731 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1736 if (!PyString_Check(entry))
1738 eDebug("tuple entry 0 is no a string");
1745 type=PyInt_AsLong(entry);
1746 if (type < -1 || type > 2)
1748 eDebug("unknown type %d", type);
1753 event_id=stime=PyInt_AsLong(entry);
1756 minutes=PyInt_AsLong(entry);
1759 eDebug("unneeded extra argument");
1763 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1764 if (ref.type != eServiceReference::idDVB)
1766 eDebug("service reference for epg query is not valid");
1770 // redirect subservice querys to parent service
1771 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1772 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1774 eServiceCenterPtr service_center;
1775 if (!eServiceCenter::getPrivInstance(service_center))
1777 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1778 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1779 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1780 dvb_ref.setParentServiceID(eServiceID(0));
1782 service = PyString_FromString(dvb_ref.toString().c_str());
1783 service_changed = true;
1787 ePyObject service_name;
1788 if (must_get_service_name)
1790 ePtr<iStaticServiceInformation> sptr;
1791 eServiceCenterPtr service_center;
1792 eServiceCenter::getPrivInstance(service_center);
1795 service_center->info(ref, sptr);
1799 sptr->getName(ref, name);
1801 service_name = PyString_FromString(name.c_str());
1805 service_name = PyString_FromString("<n/a>");
1810 if (!startTimeQuery(ref, stime, minutes))
1812 ePtr<eServiceEvent> ptr;
1813 while (!getNextTimeEntry(ptr))
1815 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1826 ePtr<eServiceEvent> ptr;
1830 lookupEventId(ref, event_id, ptr);
1832 lookupEventTime(ref, stime, ptr, type);
1834 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1837 if (service_changed)
1840 Py_DECREF(service_name);
1845 if (convertFuncArgs)
1846 Py_DECREF(convertFuncArgs);
1852 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, ePyObject service_name, ePyObject service_reference)
1856 while(pos < argcount)
1858 bool inc_refcount=false;
1859 switch(argstring[pos])
1861 case '0': // PyLong 0
1862 tmp = PyLong_FromLong(0);
1864 case 'I': // Event Id
1865 tmp = PyLong_FromLong(evData->getEventID());
1867 case 'B': // Event Begin Time
1869 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1871 tmp = PyLong_FromLong(evData->getStartTime());
1873 case 'D': // Event Duration
1875 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1877 tmp = PyLong_FromLong(evData->getDuration());
1879 case 'T': // Event Title
1880 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1882 case 'S': // Event Short Description
1883 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1885 case 'E': // Event Extended Description
1886 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1888 case 'R': // service reference string
1889 tmp = service_reference;
1890 inc_refcount = true;
1892 case 'N': // service name
1894 inc_refcount = true;
1900 inc_refcount = true;
1904 PyTuple_SET_ITEM(tuple, pos++, tmp);
1908 // here we get a python tuple
1909 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1911 // B = Event Begin Time
1912 // D = Event Duration
1914 // S = Event Short Description
1915 // E = Event Extended Description
1916 // R = Service Reference
1918 // the second tuple entry is the MAX matches value
1919 // the third tuple entry is the type of query
1920 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1921 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1922 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1923 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1924 // the fourth is the servicereference string
1925 // the fifth is the eventid
1926 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1927 // the fourth is the search text
1929 // 0 = case sensitive (CASE_CHECK)
1930 // 1 = case insensitive (NO_CASECHECK)
1932 PyObject *eEPGCache::search(ePyObject arg)
1938 const char *argstring=0;
1942 bool needServiceEvent=false;
1945 if (PyTuple_Check(arg))
1947 int tuplesize=PyTuple_Size(arg);
1950 ePyObject obj = PyTuple_GET_ITEM(arg,0);
1951 if (PyString_Check(obj))
1953 argcount = PyString_GET_SIZE(obj);
1954 argstring = PyString_AS_STRING(obj);
1955 for (int i=0; i < argcount; ++i)
1956 switch(argstring[i])
1961 needServiceEvent=true;
1968 PyErr_SetString(PyExc_StandardError,
1970 eDebug("tuple arg 0 is not a string");
1975 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1978 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1979 if (tuplesize > 4 && querytype == 0)
1981 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
1982 if (PyString_Check(obj))
1984 refstr = PyString_AS_STRING(obj);
1985 eServiceReferenceDVB ref(refstr);
1988 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1989 singleLock s(cache_lock);
1990 const eventData *evData = 0;
1991 lookupEventId(ref, eventid, evData);
1994 __u8 *data = evData->EITdata;
1995 int tmp = evData->ByteSize-12;
1996 __u32 *p = (__u32*)(data+12);
1997 // search short and extended event descriptors
2001 descriptorMap::iterator it =
2002 eventData::descriptors.find(crc);
2003 if (it != eventData::descriptors.end())
2005 __u8 *descr_data = it->second.second;
2006 switch(descr_data[0])
2009 descr[++descridx]=crc;
2018 eDebug("event not found");
2022 PyErr_SetString(PyExc_StandardError,
2024 eDebug("tuple arg 4 is not a valid service reference string");
2030 PyErr_SetString(PyExc_StandardError,
2032 eDebug("tuple arg 4 is not a string");
2036 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2038 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2039 if (PyString_Check(obj))
2041 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2042 const char *str = PyString_AS_STRING(obj);
2043 int textlen = PyString_GET_SIZE(obj);
2045 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2047 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2048 singleLock s(cache_lock);
2049 for (descriptorMap::iterator it(eventData::descriptors.begin());
2050 it != eventData::descriptors.end() && descridx < 511; ++it)
2052 __u8 *data = it->second.second;
2053 if ( data[0] == 0x4D ) // short event descriptor
2055 int title_len = data[5];
2056 if ( querytype == 1 )
2058 if (title_len > textlen)
2060 else if (title_len < textlen)
2064 if ( !strncasecmp((const char*)data+6, str, title_len) )
2066 // std::string s((const char*)data+6, title_len);
2067 // eDebug("match1 %s %s", str, s.c_str() );
2068 descr[++descridx] = it->first;
2071 else if ( !strncmp((const char*)data+6, str, title_len) )
2073 // std::string s((const char*)data+6, title_len);
2074 // eDebug("match2 %s %s", str, s.c_str() );
2075 descr[++descridx] = it->first;
2081 while((title_len-idx) >= textlen)
2085 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2087 descr[++descridx] = it->first;
2088 // std::string s((const char*)data+6, title_len);
2089 // eDebug("match 3 %s %s", str, s.c_str() );
2092 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2094 descr[++descridx] = it->first;
2095 // std::string s((const char*)data+6, title_len);
2096 // eDebug("match 4 %s %s", str, s.c_str() );
2108 PyErr_SetString(PyExc_StandardError,
2110 eDebug("tuple arg 4 is not a string");
2116 PyErr_SetString(PyExc_StandardError,
2118 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2124 PyErr_SetString(PyExc_StandardError,
2126 eDebug("not enough args in tuple");
2132 PyErr_SetString(PyExc_StandardError,
2134 eDebug("arg 0 is not a tuple");
2138 ASSERT(descridx <= 512);
2142 int maxcount=maxmatches;
2143 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2144 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2145 // in this case we start searching with the base service
2146 bool first = ref.valid() ? true : false;
2147 singleLock s(cache_lock);
2148 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2149 while(cit != eventDB.end() && maxcount)
2151 if ( ref.valid() && !first && cit->first == ref )
2153 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2157 ePyObject service_name;
2158 ePyObject service_reference;
2159 timeMap &evmap = cit->second.second;
2161 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2163 int evid = evit->second->getEventID();
2164 if ( evid == eventid)
2166 __u8 *data = evit->second->EITdata;
2167 int tmp = evit->second->ByteSize-12;
2168 __u32 *p = (__u32*)(data+12);
2169 // check if any of our descriptor used by this event
2174 for ( int i=0; i <= descridx; ++i)
2176 if (descr[i] == crc32) // found...
2181 if ( (querytype == 0 && cnt == descridx) ||
2182 ((querytype == 1 || querytype == 2) && cnt != -1) )
2184 const uniqueEPGKey &service = cit->first;
2185 eServiceReference ref =
2186 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2189 // create servive event
2190 ePtr<eServiceEvent> ptr;
2191 if (needServiceEvent)
2193 lookupEventId(ref, evid, ptr);
2195 eDebug("event not found !!!!!!!!!!!");
2197 // create service name
2198 if (!service_name && strchr(argstring,'N'))
2200 ePtr<iStaticServiceInformation> sptr;
2201 eServiceCenterPtr service_center;
2202 eServiceCenter::getPrivInstance(service_center);
2205 service_center->info(ref, sptr);
2209 sptr->getName(ref, name);
2211 service_name = PyString_FromString(name.c_str());
2215 service_name = PyString_FromString("<n/a>");
2217 // create servicereference string
2218 if (!service_reference && strchr(argstring,'R'))
2219 service_reference = PyString_FromString(ref.toString().c_str());
2222 ret = PyList_New(0);
2224 ePyObject tuple = PyTuple_New(argcount);
2226 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2227 PyList_Append(ret, tuple);
2234 Py_DECREF(service_name);
2235 if (service_reference)
2236 Py_DECREF(service_reference);
2239 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2241 cit=eventDB.begin();
2254 #ifdef ENABLE_PRIVATE_EPG
2255 #include <dvbsi++/descriptor_tag.h>
2256 #include <dvbsi++/unknown_descriptor.h>
2257 #include <dvbsi++/private_data_specifier_descriptor.h>
2259 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2261 ePtr<eTable<ProgramMapSection> > ptr;
2262 if (!pmthandler->getPMT(ptr) && ptr)
2264 std::vector<ProgramMapSection*>::const_iterator i;
2265 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2267 const ProgramMapSection &pmt = **i;
2269 ElementaryStreamInfoConstIterator es;
2270 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2273 switch ((*es)->getType())
2275 case 0x05: // private
2276 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2277 desc != (*es)->getDescriptors()->end(); ++desc)
2279 switch ((*desc)->getTag())
2281 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2282 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2287 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2288 int descr_len = descr->getLength();
2291 uint8_t data[descr_len+2];
2292 descr->writeToBuffer(data);
2293 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2307 eServiceReferenceDVB ref;
2308 if (!pmthandler->getServiceReference(ref))
2310 int pid = (*es)->getPid();
2311 messages.send(Message(Message::got_private_pid, ref, pid));
2319 eDebug("PMTready but no pmt!!");
2326 date_time( const date_time &a )
2328 memcpy(data, a.data, 5);
2331 date_time( const __u8 data[5])
2333 memcpy(this->data, data, 5);
2334 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2339 const __u8& operator[](int pos) const
2345 struct less_datetime
2347 bool operator()( const date_time &a, const date_time &b ) const
2349 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2353 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2355 contentMap &content_time_table = content_time_tables[current_service];
2356 singleLock s(cache_lock);
2357 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2358 eventMap &evMap = eventDB[current_service].first;
2359 timeMap &tmMap = eventDB[current_service].second;
2361 int content_id = data[ptr++] << 24;
2362 content_id |= data[ptr++] << 16;
2363 content_id |= data[ptr++] << 8;
2364 content_id |= data[ptr++];
2366 contentTimeMap &time_event_map =
2367 content_time_table[content_id];
2368 for ( contentTimeMap::iterator it( time_event_map.begin() );
2369 it != time_event_map.end(); ++it )
2371 eventMap::iterator evIt( evMap.find(it->second.second) );
2372 if ( evIt != evMap.end() )
2374 delete evIt->second;
2377 tmMap.erase(it->second.first);
2379 time_event_map.clear();
2382 memcpy(duration, data+ptr, 3);
2385 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2387 const __u8 *descriptors[65];
2388 const __u8 **pdescr = descriptors;
2390 int descriptors_length = (data[ptr++]&0x0F) << 8;
2391 descriptors_length |= data[ptr++];
2392 while ( descriptors_length > 0 )
2394 int descr_type = data[ptr];
2395 int descr_len = data[ptr+1];
2396 descriptors_length -= (descr_len+2);
2397 if ( descr_type == 0xf2 )
2400 int tsid = data[ptr++] << 8;
2401 tsid |= data[ptr++];
2402 int onid = data[ptr++] << 8;
2403 onid |= data[ptr++];
2404 int sid = data[ptr++] << 8;
2407 // WORKAROUND for wrong transmitted epg data (01.08.2006)
2410 switch( (tsid << 16) | sid )
2412 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2413 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2414 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2415 case 0x0300f5: sid = 0xdc; break;
2416 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2417 case 0x1100d3: sid = 0xe3; break;
2420 ////////////////////////////////////////////
2422 uniqueEPGKey service( sid, onid, tsid );
2424 while( descr_len > 0 )
2427 datetime[0] = data[ptr++];
2428 datetime[1] = data[ptr++];
2429 int tmp_len = data[ptr++];
2431 while( tmp_len > 0 )
2433 memcpy(datetime+2, data+ptr, 3);
2437 start_times[datetime].push_back(service);
2448 ASSERT(pdescr <= &descriptors[65])
2450 eit_event_struct *ev_struct = (eit_event_struct*) event;
2451 ev_struct->running_status = 0;
2452 ev_struct->free_CA_mode = 1;
2453 memcpy(event+7, duration, 3);
2455 const __u8 **d=descriptors;
2456 while ( d < pdescr )
2458 memcpy(event+ptr, *d, ((*d)[1])+2);
2462 ASSERT(ptr <= 4098);
2463 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2465 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2466 if ( (it->first.tm + duration_sec) < now )
2468 memcpy(event+2, it->first.data, 5);
2471 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2473 event[bptr++] = 0x4A;
2474 __u8 *len = event+(bptr++);
2475 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2476 event[bptr++] = (i->tsid & 0xFF);
2477 event[bptr++] = (i->onid & 0xFF00) >> 8;
2478 event[bptr++] = (i->onid & 0xFF);
2479 event[bptr++] = (i->sid & 0xFF00) >> 8;
2480 event[bptr++] = (i->sid & 0xFF);
2481 event[bptr++] = 0xB0;
2482 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2483 *len = ((event+bptr) - len)-1;
2485 int llen = bptr - 12;
2486 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2487 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2489 time_t stime = it->first.tm;
2490 while( tmMap.find(stime) != tmMap.end() )
2492 event[6] += (stime - it->first.tm);
2494 while( evMap.find(event_id) != evMap.end() )
2496 event[0] = (event_id & 0xFF00) >> 8;
2497 event[1] = (event_id & 0xFF);
2498 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2499 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2500 evMap[event_id] = d;
2505 void eEPGCache::channel_data::startPrivateReader()
2507 eDVBSectionFilterMask mask;
2508 memset(&mask, 0, sizeof(mask));
2509 mask.pid = m_PrivatePid;
2510 mask.flags = eDVBSectionFilterMask::rfCRC;
2511 mask.data[0] = 0xA0;
2512 mask.mask[0] = 0xFF;
2513 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2514 if (m_PrevVersion != -1)
2516 mask.data[3] = m_PrevVersion << 1;
2517 mask.mask[3] = 0x3E;
2518 mask.mode[3] = 0x3E;
2520 seenPrivateSections.clear();
2522 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2523 m_PrivateReader->start(mask);
2526 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2528 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2530 cache->privateSectionRead(m_PrivateService, data);
2531 seenPrivateSections.insert(data[6]);
2533 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2535 eDebug("[EPGC] private finished");
2536 eDVBChannelID chid = channel->getChannelID();
2537 int tmp = chid.original_network_id.get();
2538 tmp |= 0x80000000; // we use highest bit as private epg indicator
2539 chid.original_network_id = tmp;
2540 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2541 m_PrevVersion = (data[5] & 0x3E) >> 1;
2542 startPrivateReader();
2546 #endif // ENABLE_PRIVATE_EPG
2548 #ifdef ENABLE_MHW_EPG
2549 void eEPGCache::channel_data::cleanup()
2554 m_program_ids.clear();
2557 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2559 // Names in mhw structs are not strings as they are not '\0' terminated.
2560 // This function converts the mhw name into a string.
2561 // Constraint: "length of out" = "length of in" + 1.
2563 for ( i=0; i < len_in; i++ )
2567 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2574 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2577 return_time[0] = toBCD( hours );
2578 return_time[1] = toBCD( minutes );
2582 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2584 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2587 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2588 // For date plus time of day
2590 // Remove offset in mhw time.
2591 __u8 local_hours = hours;
2594 else if ( hours >= 8 )
2597 // As far as we know all mhw time data is sent in central Europe time zone.
2598 // So, temporarily set timezone to western europe
2599 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2601 char *old_tz = getenv( "TZ" );
2602 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2605 tm *localnow = localtime( &dt );
2609 if ( day + 1 < localnow->tm_wday ) // day + 1 to prevent old events to show for next week.
2611 if (local_hours <= 5)
2614 dt += 3600*24*(day - localnow->tm_wday); // Shift dt to the recording date (local time zone).
2615 dt += 3600*(local_hours - localnow->tm_hour); // Shift dt to the recording hour.
2617 tm *recdate = gmtime( &dt ); // This will also take care of DST.
2619 if ( old_tz == NULL )
2625 // Calculate MJD according to annex in ETSI EN 300 468
2627 if ( recdate->tm_mon <= 1 ) // Jan or Feb
2629 int mjd = 14956 + recdate->tm_mday + int( (recdate->tm_year - l) * 365.25) +
2630 int( (recdate->tm_mon + 2 + l * 12) * 30.6001);
2632 return_time[0] = (mjd & 0xFF00)>>8;
2633 return_time[1] = mjd & 0xFF;
2635 timeMHW2DVB( recdate->tm_hour, minutes, return_time+2 );
2638 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2639 // data is borrowed from calling proc to save memory space.
2642 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2643 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2644 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2646 eit_t *packet = (eit_t *) data;
2647 packet->table_id = 0x50;
2648 packet->section_syntax_indicator = 1;
2649 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2650 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2651 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2652 packet->current_next_indicator = 0;
2653 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2654 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2655 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2656 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2657 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2658 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2659 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2660 packet->segment_last_table_id = 0x50;
2662 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2663 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2664 int prog_title_length = prog_title.length();
2666 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2667 prog_title_length + 1;
2669 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2670 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2671 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2675 u_char *data = (u_char*) event_data;
2676 data[2] = itTitle->second.mhw2_mjd_hi;
2677 data[3] = itTitle->second.mhw2_mjd_lo;
2678 data[4] = itTitle->second.mhw2_hours;
2679 data[5] = itTitle->second.mhw2_minutes;
2680 data[6] = itTitle->second.mhw2_seconds;
2681 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2685 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2686 (u_char *) event_data + 2 );
2687 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2690 event_data->running_status = 0;
2691 event_data->free_CA_mode = 0;
2692 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2694 eit_short_event_descriptor_struct *short_event_descriptor =
2695 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2696 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2697 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2698 prog_title_length - 1;
2699 short_event_descriptor->language_code_1 = 'e';
2700 short_event_descriptor->language_code_2 = 'n';
2701 short_event_descriptor->language_code_3 = 'g';
2702 short_event_descriptor->event_name_length = prog_title_length;
2703 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2704 memcpy(event_name, prog_title.c_str(), prog_title_length);
2707 event_name[prog_title_length] = 0;
2709 if ( sumText.length() > 0 )
2710 // There is summary info
2712 unsigned int sum_length = sumText.length();
2713 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2714 // Store summary in short event descriptor
2716 // Increase all relevant lengths
2717 event_name[prog_title_length] = sum_length;
2718 short_event_descriptor->descriptor_length += sum_length;
2719 packet_length += sum_length;
2720 descr_ll += sum_length;
2721 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2724 // Store summary in extended event descriptors
2726 int remaining_sum_length = sumText.length();
2727 int nbr_descr = int(remaining_sum_length/247) + 1;
2728 for ( int i=0; i < nbr_descr; i++)
2729 // Loop once per extended event descriptor
2731 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2732 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2733 remaining_sum_length -= sum_length;
2734 packet_length += 8 + sum_length;
2735 descr_ll += 8 + sum_length;
2737 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2738 ext_event_descriptor->descriptor_length = sum_length + 6;
2739 ext_event_descriptor->descriptor_number = i;
2740 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2741 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2742 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2743 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2744 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2746 the_text[-1] = sum_length;
2747 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2754 // Add content descriptor
2755 u_char *descriptor = (u_char *) data + packet_length;
2760 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2761 if ( content_descr.find( "FILM" ) != std::string::npos )
2763 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2766 descriptor[0] = 0x54;
2768 descriptor[2] = content_id;
2772 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2773 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2775 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2776 packet->section_length_lo = (packet_length - 3)&0xff;
2778 // Feed the data to eEPGCache::sectionRead()
2779 cache->sectionRead( data, MHW, this );
2782 void eEPGCache::channel_data::startTimeout(int msec)
2784 m_MHWTimeoutTimer.start(msec,true);
2785 m_MHWTimeoutet=false;
2788 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2790 m_MHWFilterMask.pid = pid;
2791 m_MHWFilterMask.data[0] = tid;
2792 m_MHWReader->start(m_MHWFilterMask);
2793 // eDebug("start 0x%02x 0x%02x", pid, tid);
2796 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2798 m_MHWFilterMask2.pid = pid;
2799 m_MHWFilterMask2.data[0] = tid;
2802 m_MHWFilterMask2.data[1] = ext;
2803 m_MHWFilterMask2.mask[1] = 0xFF;
2804 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2808 m_MHWFilterMask2.data[1] = 0;
2809 m_MHWFilterMask2.mask[1] = 0;
2810 // eDebug("start 0x%02x 0x%02x", pid, tid);
2812 m_MHWReader2->start(m_MHWFilterMask2);
2815 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2818 m_MHWReader2->stop();
2820 if ( state > 1 || // aborted
2821 // have si data.. so we dont read mhw data
2822 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2824 eDebug("[EPGC] mhw aborted %d", state);
2826 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2829 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2830 int record_size = sizeof( mhw_channel_name_t );
2831 int nbr_records = int (len/record_size);
2833 for ( int i = 0; i < nbr_records; i++ )
2835 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2836 m_channels.push_back( *channel );
2840 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2842 // Channels table has been read, start reading the themes table.
2843 startMHWReader(0xD3, 0x92);
2846 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2849 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2850 int record_size = sizeof( mhw_theme_name_t );
2851 int nbr_records = int (len/record_size);
2853 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2856 for ( int i = 0; i < nbr_records; i++ )
2858 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2859 if ( i >= next_idx )
2863 next_idx = (__u8) *(data + 3 + idx_ptr);
2869 m_themes[idx+sub_idx] = *theme;
2871 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2872 // Themes table has been read, start reading the titles table.
2873 startMHWReader(0xD2, 0x90);
2877 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2880 mhw_title_t *title = (mhw_title_t*) data;
2882 if ( title->channel_id == 0xFF ) // Separator
2883 return; // Continue reading of the current table.
2886 // Create unique key per title
2887 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2888 (title->ms.minutes);
2889 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2890 ((title->program_id_ml)<<8)|(title->program_id_lo);
2892 if ( m_titles.find( title_id ) == m_titles.end() )
2895 title->mhw2_mjd_hi = 0;
2896 title->mhw2_mjd_lo = 0;
2897 title->mhw2_duration_hi = 0;
2898 title->mhw2_duration_lo = 0;
2899 m_titles[ title_id ] = *title;
2900 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2901 // program_ids will be used to gather summaries.
2902 m_program_ids[ program_id ] = title_id;
2903 return; // Continue reading of the current table.
2905 else if (!checkTimeout())
2908 if ( !m_program_ids.empty())
2910 // Titles table has been read, there are summaries to read.
2911 // Start reading summaries, store corresponding titles on the fly.
2912 startMHWReader(0xD3, 0x90);
2913 eDebug("[EPGC] mhw %d titles(%d with summary) found",
2915 m_program_ids.size());
2920 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2923 mhw_summary_t *summary = (mhw_summary_t*) data;
2925 // Create unique key per record
2926 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2927 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2928 int len = ((data[1]&0xf)<<8) + data[2];
2930 // ugly workaround to convert const __u8* to char*
2932 memcpy(&tmp, &data, sizeof(void*));
2933 tmp[len+3] = 0; // Terminate as a string.
2935 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2936 if ( itProgid == m_program_ids.end() )
2937 { /* This part is to prevent to looping forever if some summaries are not received yet.
2938 There is a timeout of 4 sec. after the last successfully read summary. */
2939 if (!m_program_ids.empty() && !checkTimeout())
2940 return; // Continue reading of the current table.
2944 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2947 while((pos = the_text.find("\r\n")) != std::string::npos)
2948 the_text.replace(pos, 2, " ");
2950 // Find corresponding title, store title and summary in epgcache.
2951 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2952 if ( itTitle != m_titles.end() )
2955 storeTitle( itTitle, the_text, data );
2956 m_titles.erase( itTitle );
2958 m_program_ids.erase( itProgid );
2959 if ( !m_program_ids.empty() )
2960 return; // Continue reading of the current table.
2963 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
2964 eDVBLocalTimeHandler::getInstance()->nowTime(),
2965 m_program_ids.size());
2966 // Summaries have been read, titles that have summaries have been stored.
2967 // Now store titles that do not have summaries.
2968 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
2969 storeTitle( itTitle, "", data );
2973 m_MHWReader->stop();
2978 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
2980 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
2983 m_MHWReader->stop();
2985 if ( state > 1 || // aborted
2986 // have si data.. so we dont read mhw data
2987 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
2989 eDebug("[EPGC] mhw2 aborted %d", state);
2991 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
2994 int num_channels = data[120];
2997 int ptr = 121 + 6 * num_channels;
3000 for( int chid = 0; chid < num_channels; ++chid )
3002 ptr += ( data[ptr] & 0x0f ) + 1;
3012 // data seems consistent...
3013 const __u8 *tmp = data+121;
3014 for (int i=0; i < num_channels; ++i)
3016 mhw_channel_name_t channel;
3017 channel.transport_stream_id_hi = *(tmp++);
3018 channel.transport_stream_id_lo = *(tmp++);
3019 channel.channel_id_hi = *(tmp++);
3020 channel.channel_id_lo = *(tmp++);
3021 #warning FIXME hardcoded network_id in mhw2 epg
3022 channel.network_id_hi = 0; // hardcoded astra 19.2
3023 channel.network_id_lo = 1;
3024 m_channels.push_back(channel);
3027 for (int i=0; i < num_channels; ++i)
3029 mhw_channel_name_t &channel = m_channels[i];
3030 int channel_name_len=*(tmp++)&0x0f;
3032 for (; x < channel_name_len; ++x)
3033 channel.name[x]=*(tmp++);
3034 channel.name[x+1]=0;
3037 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3039 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3042 eDebug("[EPGC] mhw2 themes nyi");
3044 else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3049 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3051 if(data[dataLen-1] != 0xff)
3053 while( pos < dataLen )
3062 if( data[pos] > 0xc0 )
3064 pos += ( data[pos] - 0xc0 );
3068 if( data[pos] == 0xff )
3084 // data seems consistent...
3089 title.channel_id = data[pos]+1;
3090 title.program_id_ml = data[pos+1];
3091 title.program_id_lo = data[pos+2];
3092 title.mhw2_mjd_hi = data[pos+3];
3093 title.mhw2_mjd_lo = data[pos+4];
3094 title.mhw2_hours = data[pos+5];
3095 title.mhw2_minutes = data[pos+6];
3096 title.mhw2_seconds = data[pos+7];
3097 int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3098 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3099 title.mhw2_duration_lo = duration&0xFF;
3100 __u8 slen = data[pos+10] & 0x3f;
3101 __u8 *dest = ((__u8*)title.title)-4;
3102 memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3103 memset(dest+slen, 0x20, 33-slen);
3105 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3106 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3108 // Create unique key per title
3109 __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3111 // eDebug("program_id: %08x, %s", program_id,
3112 // std::string((const char *)title.title, (int)(slen > 23 ? 23 : slen)).c_str());
3116 if ( m_titles.find( title_id ) == m_titles.end() )
3119 m_titles[ title_id ] = title;
3120 if (summary_id != 0xFFFF && // no summary avail
3121 m_program_ids.find(summary_id) == m_program_ids.end())
3123 m_program_ids[ summary_id ] = title_id;
3128 if ( !checkTimeout() )
3129 continue; // Continue reading of the current table.
3137 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3138 if (!m_program_ids.empty())
3140 // Titles table has been read, there are summaries to read.
3141 // Start reading summaries, store corresponding titles on the fly.
3142 startMHWReader2(0x236, 0x96);
3150 else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3153 int len, loop, pos, lenline;
3162 loop = data[pos] & 0x0f;
3167 for( ; loop > 0; --loop )
3169 if( dataLen > (pos+len) )
3171 lenline = data[pos+len];
3180 else if (!checkTimeout())
3181 return; // continue reading
3182 if (valid && !checkTimeout())
3184 // data seems consistent...
3185 __u32 summary_id = (data[3]<<8)|data[4];
3187 // ugly workaround to convert const __u8* to char*
3189 memcpy(&tmp, &data, sizeof(void*));
3194 loop = tmp[pos] & 0x0f;
3196 for( ; loop > 0; loop -- )
3198 lenline = tmp[pos+len];
3207 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( summary_id ) );
3208 if ( itProgid == m_program_ids.end() )
3209 { /* This part is to prevent to looping forever if some summaries are not received yet.
3210 There is a timeout of 4 sec. after the last successfully read summary. */
3212 if ( !m_program_ids.empty() && !checkTimeout() )
3213 return; // Continue reading of the current table.
3218 std::string the_text = (char *) (data + pos + 1);
3220 // Find corresponding title, store title and summary in epgcache.
3221 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3222 if ( itTitle != m_titles.end() )
3224 storeTitle( itTitle, the_text, data );
3225 m_titles.erase( itTitle );
3227 m_program_ids.erase( itProgid );
3228 if ( !m_program_ids.empty() )
3229 return; // Continue reading of the current table.
3233 if (isRunning & eEPGCache::MHW)
3235 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3237 // Channels table has been read, start reading the themes table.
3238 startMHWReader2(0x231, 0xC8, 1);
3241 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3243 // Themes table has been read, start reading the titles table.
3244 startMHWReader2(0x234, 0xe6);
3249 // Summaries have been read, titles that have summaries have been stored.
3250 // Now store titles that do not have summaries.
3251 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3252 storeTitle( itTitle, "", data );
3253 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3254 eDVBLocalTimeHandler::getInstance()->nowTime(),
3255 m_program_ids.size());
3262 m_MHWReader2->stop();