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>
18 #include <dvbsi++/descriptor_tag.h>
20 int eventData::CacheSize=0;
21 descriptorMap eventData::descriptors;
22 __u8 eventData::data[4108];
23 extern const uint32_t crc32_table[256];
25 const eServiceReference &handleGroup(const eServiceReference &ref)
27 if (ref.flags & eServiceReference::isGroup)
29 ePtr<eDVBResourceManager> res;
30 if (!eDVBResourceManager::getInstance(res))
32 ePtr<iDVBChannelList> db;
33 if (!res->getChannelList(db))
36 if (!db->getBouquet(ref, bouquet))
38 std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
39 if (it != bouquet->m_services.end())
49 eventData::eventData(const eit_event_struct* e, int size, int type)
50 :ByteSize(size&0xFF), type(type&0xFF)
58 __u8 *data = (__u8*)e;
64 __u8 *descr = data+ptr;
65 int descr_len = descr[1];
67 if (size >= descr_len)
71 case EXTENDED_EVENT_DESCRIPTOR:
72 case SHORT_EVENT_DESCRIPTOR:
73 case LINKAGE_DESCRIPTOR:
74 case COMPONENT_DESCRIPTOR:
78 while(cnt++ < descr_len)
79 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
81 descriptorMap::iterator it =
82 descriptors.find(crc);
83 if ( it == descriptors.end() )
86 __u8 *d = new __u8[descr_len];
87 memcpy(d, descr, descr_len);
88 descriptors[crc] = descriptorPair(1, d);
95 default: // do not cache all other descriptors
104 ASSERT(pdescr <= &descr[65]);
105 ByteSize = 10+((pdescr-descr)*4);
106 EITdata = new __u8[ByteSize];
108 memcpy(EITdata, (__u8*) e, 10);
109 memcpy(EITdata+10, descr, ByteSize-10);
112 const eit_event_struct* eventData::get() const
115 int tmp = ByteSize-10;
116 memcpy(data, EITdata, 10);
117 int descriptors_length=0;
118 __u32 *p = (__u32*)(EITdata+10);
121 descriptorMap::iterator it =
122 descriptors.find(*p++);
123 if ( it != descriptors.end() )
125 int b = it->second.second[1]+2;
126 memcpy(data+pos, it->second.second, b );
128 descriptors_length += b;
131 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(p-1));
135 data[10] = (descriptors_length >> 8) & 0x0F;
136 data[11] = descriptors_length & 0xFF;
137 return (eit_event_struct*)data;
140 eventData::~eventData()
144 CacheSize -= ByteSize;
145 __u32 *d = (__u32*)(EITdata+10);
149 descriptorMap::iterator it =
150 descriptors.find(*d++);
151 if ( it != descriptors.end() )
153 descriptorPair &p = it->second;
154 if (!--p.first) // no more used descriptor
156 CacheSize -= it->second.second[1];
157 delete [] it->second.second; // free descriptor memory
158 descriptors.erase(it); // remove entry from descriptor map
162 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(d-1));
169 void eventData::load(FILE *f)
175 fread(&size, sizeof(int), 1, f);
178 fread(&id, sizeof(__u32), 1, f);
179 fread(&p.first, sizeof(int), 1, f);
180 fread(header, 2, 1, f);
181 int bytes = header[1]+2;
182 p.second = new __u8[bytes];
183 p.second[0] = header[0];
184 p.second[1] = header[1];
185 fread(p.second+2, bytes-2, 1, f);
192 void eventData::save(FILE *f)
194 int size=descriptors.size();
195 descriptorMap::iterator it(descriptors.begin());
196 fwrite(&size, sizeof(int), 1, f);
199 fwrite(&it->first, sizeof(__u32), 1, f);
200 fwrite(&it->second.first, sizeof(int), 1, f);
201 fwrite(it->second.second, it->second.second[1]+2, 1, f);
207 eEPGCache* eEPGCache::instance;
208 pthread_mutex_t eEPGCache::cache_lock=
209 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
210 pthread_mutex_t eEPGCache::channel_map_lock=
211 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
213 DEFINE_REF(eEPGCache)
215 eEPGCache::eEPGCache()
216 :messages(this,1), cleanTimer(this)//, paused(0)
218 eDebug("[EPGC] Initialized EPGCache");
220 CONNECT(messages.recv_msg, eEPGCache::gotMessage);
221 CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
222 CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
224 ePtr<eDVBResourceManager> res_mgr;
225 eDVBResourceManager::getInstance(res_mgr);
227 eDebug("[eEPGCache] no resource manager !!!!!!!");
229 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
233 void eEPGCache::timeUpdated()
237 eDebug("[EPGC] time updated.. start EPG Mainloop");
240 messages.send(Message(Message::timeChanged));
243 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
247 // eDebug("[eEPGCache] add channel %p", chan);
248 channel_data *data = new channel_data(this);
249 data->channel = chan;
250 data->prevChannelState = -1;
251 #ifdef ENABLE_PRIVATE_EPG
252 data->m_PrivatePid = -1;
254 singleLock s(channel_map_lock);
255 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
256 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
260 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
262 channelMapIterator it =
263 m_knownChannels.find(chan);
264 if ( it == m_knownChannels.end() )
265 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
268 channel_data &data = *it->second;
269 ePtr<eDVBResourceManager> res_mgr;
270 if ( eDVBResourceManager::getInstance( res_mgr ) )
271 eDebug("[eEPGCache] no res manager!!");
274 ePtr<iDVBDemux> demux;
275 if ( data.channel->getDemux(demux, 0) )
277 eDebug("[eEPGCache] no demux!!");
282 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
285 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
289 res = demux->createSectionReader( this, data.m_ScheduleReader );
292 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
296 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
299 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
302 #ifdef ENABLE_PRIVATE_EPG
303 res = demux->createSectionReader( this, data.m_PrivateReader );
306 eDebug("[eEPGCache] couldnt initialize private reader!!");
310 #ifdef ENABLE_MHW_EPG
311 res = demux->createSectionReader( this, data.m_MHWReader );
314 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
317 res = demux->createSectionReader( this, data.m_MHWReader2 );
320 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
324 messages.send(Message(Message::startChannel, chan));
325 // -> gotMessage -> changedService
331 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
333 channelMapIterator it =
334 m_knownChannels.find(chan);
335 if ( it != m_knownChannels.end() )
338 chan->getState(state);
339 if ( it->second->prevChannelState != state )
343 case iDVBChannel::state_ok:
345 eDebug("[eEPGCache] channel %p running", chan);
346 DVBChannelRunning(chan);
349 case iDVBChannel::state_release:
351 eDebug("[eEPGCache] remove channel %p", chan);
352 messages.send(Message(Message::leaveChannel, chan));
353 pthread_mutex_lock(&it->second->channel_active);
354 singleLock s(channel_map_lock);
355 m_knownChannels.erase(it);
356 pthread_mutex_unlock(&it->second->channel_active);
359 // -> gotMessage -> abortEPG
362 default: // ignore all other events
366 it->second->prevChannelState = state;
371 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
373 timeMap::iterator tmp = tm_it;
374 while ((tmp->first+tmp->second->getDuration()-300) > TM)
377 #ifdef ENABLE_PRIVATE_EPG
378 && tmp->second->type != PRIVATE
381 && tmp->second->type != MHW
385 __u16 event_id = tmp->second->getEventID();
386 servicemap.first.erase(event_id);
388 Event evt((uint8_t*)tmp->second->get());
390 event.parseFrom(&evt, service.sid<<16|service.onid);
391 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
392 service.sid, event_id,
393 event.getBeginTimeString().c_str(),
394 event.getEventName().c_str(),
395 event.getExtendedDescription().c_str());
398 if (tmp == servicemap.second.begin())
400 servicemap.second.erase(tmp);
404 servicemap.second.erase(tmp--);
408 if (tmp == servicemap.second.begin())
415 while(tmp->first < (TM+duration-300))
417 if (tmp->first != TM && tmp->second->type != PRIVATE)
419 __u16 event_id = tmp->second->getEventID();
420 servicemap.first.erase(event_id);
422 Event evt((uint8_t*)tmp->second->get());
424 event.parseFrom(&evt, service.sid<<16|service.onid);
425 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
426 service.sid, event_id,
427 event.getBeginTimeString().c_str(),
428 event.getEventName().c_str(),
429 event.getExtendedDescription().c_str());
432 servicemap.second.erase(tmp++);
436 if (tmp == servicemap.second.end())
441 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
443 eit_t *eit = (eit_t*) data;
445 int len=HILO(eit->section_length)-1;//+3-4;
450 // This fixed the EPG on the Multichoice irdeto systems
451 // the EIT packet is non-compliant.. their EIT packet stinks
452 if ( data[ptr-1] < 0x40 )
455 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
456 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
460 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);
461 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
463 if ( TM != 3599 && TM > -1)
464 channel->haveData |= source;
466 singleLock s(cache_lock);
467 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
468 // oder eine durch [] erzeugte
469 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
470 eventMap::iterator prevEventIt = servicemap.first.end();
471 timeMap::iterator prevTimeIt = servicemap.second.end();
475 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
477 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
479 eit_event->start_time_1,
480 eit_event->start_time_2,
481 eit_event->start_time_3,
482 eit_event->start_time_4,
483 eit_event->start_time_5);
488 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
491 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
493 __u16 event_id = HILO(eit_event->event_id);
494 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
497 int ev_erase_count = 0;
498 int tm_erase_count = 0;
500 // search in eventmap
501 eventMap::iterator ev_it =
502 servicemap.first.find(event_id);
504 // entry with this event_id is already exist ?
505 if ( ev_it != servicemap.first.end() )
507 if ( source > ev_it->second->type ) // update needed ?
508 goto next; // when not.. then skip this entry
510 // search this event in timemap
511 timeMap::iterator tm_it_tmp =
512 servicemap.second.find(ev_it->second->getStartTime());
514 if ( tm_it_tmp != servicemap.second.end() )
516 if ( tm_it_tmp->first == TM ) // just update eventdata
519 eventData *tmp = ev_it->second;
520 ev_it->second = tm_it_tmp->second =
521 new eventData(eit_event, eit_event_size, source);
522 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
526 else // event has new event begin time
529 // delete the found record from timemap
530 servicemap.second.erase(tm_it_tmp);
531 prevTimeIt=servicemap.second.end();
536 // search in timemap, for check of a case if new time has coincided with time of other event
537 // or event was is not found in eventmap
538 timeMap::iterator tm_it =
539 servicemap.second.find(TM);
541 if ( tm_it != servicemap.second.end() )
543 // event with same start time but another event_id...
544 if ( source > tm_it->second->type &&
545 ev_it == servicemap.first.end() )
546 goto next; // when not.. then skip this entry
548 // search this time in eventmap
549 eventMap::iterator ev_it_tmp =
550 servicemap.first.find(tm_it->second->getEventID());
552 if ( ev_it_tmp != servicemap.first.end() )
555 // delete the found record from eventmap
556 servicemap.first.erase(ev_it_tmp);
557 prevEventIt=servicemap.first.end();
560 evt = new eventData(eit_event, eit_event_size, source);
562 bool consistencyCheck=true;
564 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
566 eventData *tmp1 = ev_it->second,
567 *tmp2 = tm_it->second;
574 else if (ev_erase_count == 0 && tm_erase_count > 0)
576 eventData *tmp = ev_it->second;
577 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
582 else if (ev_erase_count > 0 && tm_erase_count == 0)
584 eventData *tmp = tm_it->second;
585 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
590 else // added new eventData
593 consistencyCheck=false;
595 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
596 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
599 FixOverlapping(servicemap, TM, duration, tm_it, service);
602 if ( consistencyCheck )
604 if ( tm_it->second != evt || ev_it->second != evt )
605 eFatal("tm_it->second != ev_it->second");
606 else if ( tm_it->second->getStartTime() != tm_it->first )
607 eFatal("event start_time(%d) non equal timemap key(%d)",
608 tm_it->second->getStartTime(), tm_it->first );
609 else if ( tm_it->first != TM )
610 eFatal("timemap key(%d) non equal TM(%d)",
612 else if ( ev_it->second->getEventID() != ev_it->first )
613 eFatal("event_id (%d) non equal event_map key(%d)",
614 ev_it->second->getEventID(), ev_it->first);
615 else if ( ev_it->first != event_id )
616 eFatal("eventmap key(%d) non equal event_id(%d)",
617 ev_it->first, event_id );
623 if ( servicemap.first.size() != servicemap.second.size() )
625 FILE *f = fopen("/hdd/event_map.txt", "w+");
627 for (eventMap::iterator it(servicemap.first.begin())
628 ; it != servicemap.first.end(); ++it )
629 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
630 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
632 f = fopen("/hdd/time_map.txt", "w+");
634 for (timeMap::iterator it(servicemap.second.begin())
635 ; it != servicemap.second.end(); ++it )
636 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
637 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
640 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
641 service.sid, service.tsid, service.onid,
642 servicemap.first.size(), servicemap.second.size() );
645 ptr += eit_event_size;
646 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
650 void eEPGCache::flushEPG(const uniqueEPGKey & s)
652 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
653 singleLock l(cache_lock);
654 if (s) // clear only this service
656 eventCache::iterator it = eventDB.find(s);
657 if ( it != eventDB.end() )
659 eventMap &evMap = it->second.first;
660 timeMap &tmMap = it->second.second;
662 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
667 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
668 #ifdef ENABLE_PRIVATE_EPG
669 contentMaps::iterator it =
670 content_time_tables.find(s);
671 if ( it != content_time_tables.end() )
674 content_time_tables.erase(it);
679 else // clear complete EPG Cache
681 for (eventCache::iterator it(eventDB.begin());
682 it != eventDB.end(); ++it)
684 eventMap &evMap = it->second.first;
685 timeMap &tmMap = it->second.second;
686 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
692 #ifdef ENABLE_PRIVATE_EPG
693 content_time_tables.clear();
695 channelLastUpdated.clear();
696 singleLock m(channel_map_lock);
697 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
698 it->second->startEPG();
700 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
703 void eEPGCache::cleanLoop()
705 singleLock s(cache_lock);
706 if (!eventDB.empty())
708 eDebug("[EPGC] start cleanloop");
710 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
712 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
714 bool updated = false;
715 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
717 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
719 // remove entry from eventMap
720 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
721 if ( b != DBIt->second.first.end() )
723 // release Heap Memory for this entry (new ....)
724 // eDebug("[EPGC] delete old event (evmap)");
725 DBIt->second.first.erase(b);
728 // remove entry from timeMap
729 // eDebug("[EPGC] release heap mem");
731 DBIt->second.second.erase(It++);
732 // eDebug("[EPGC] delete old event (timeMap)");
738 #ifdef ENABLE_PRIVATE_EPG
741 contentMaps::iterator x =
742 content_time_tables.find( DBIt->first );
743 if ( x != content_time_tables.end() )
745 timeMap &tmMap = DBIt->second.second;
746 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
748 for ( contentTimeMap::iterator it(i->second.begin());
749 it != i->second.end(); )
751 if ( tmMap.find(it->second.first) == tmMap.end() )
752 i->second.erase(it++);
756 if ( i->second.size() )
759 x->second.erase(i++);
765 eDebug("[EPGC] stop cleanloop");
766 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
768 cleanTimer.start(CLEAN_INTERVAL,true);
771 eEPGCache::~eEPGCache()
773 messages.send(Message::quit);
774 kill(); // waiting for thread shutdown
775 singleLock s(cache_lock);
776 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
777 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
781 void eEPGCache::gotMessage( const Message &msg )
786 flushEPG(msg.service);
788 case Message::startChannel:
790 singleLock s(channel_map_lock);
791 channelMapIterator channel =
792 m_knownChannels.find(msg.channel);
793 if ( channel != m_knownChannels.end() )
794 channel->second->startChannel();
797 case Message::leaveChannel:
799 singleLock s(channel_map_lock);
800 channelMapIterator channel =
801 m_knownChannels.find(msg.channel);
802 if ( channel != m_knownChannels.end() )
803 channel->second->abortEPG();
809 #ifdef ENABLE_PRIVATE_EPG
810 case Message::got_private_pid:
812 singleLock s(channel_map_lock);
813 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
815 eDVBChannel *channel = (eDVBChannel*) it->first;
816 channel_data *data = it->second;
817 eDVBChannelID chid = channel->getChannelID();
818 if ( chid.transport_stream_id.get() == msg.service.tsid &&
819 chid.original_network_id.get() == msg.service.onid &&
820 data->m_PrivatePid == -1 )
822 data->m_PrevVersion = -1;
823 data->m_PrivatePid = msg.pid;
824 data->m_PrivateService = msg.service;
825 int onid = chid.original_network_id.get();
826 onid |= 0x80000000; // we use highest bit as private epg indicator
827 chid.original_network_id = onid;
828 updateMap::iterator It = channelLastUpdated.find( chid );
829 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
830 if (update < ZAP_DELAY)
832 data->startPrivateTimer.start(update, 1);
834 eDebug("[EPGC] next private update in %i min", update/60000);
835 else if (update >= 1000)
836 eDebug("[EPGC] next private update in %i sec", update/1000);
843 case Message::timeChanged:
847 eDebug("unhandled EPGCache Message!!");
852 void eEPGCache::thread()
862 void eEPGCache::load()
864 singleLock s(cache_lock);
865 FILE *f = fopen("/hdd/epg.dat", "r");
871 unsigned char md5_saved[16];
872 unsigned char md5[16];
875 if (!md5_file("/hdd/epg.dat", 1, md5))
877 FILE *f = fopen("/hdd/epg.dat.md5", "r");
880 fread( md5_saved, 16, 1, f);
882 if ( !memcmp(md5_saved, md5, 16) )
889 unsigned int magic=0;
890 fread( &magic, sizeof(int), 1, f);
891 if (magic != 0x98765432)
893 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
898 fread( text1, 13, 1, f);
899 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
901 fread( &size, sizeof(int), 1, f);
908 fread( &key, sizeof(uniqueEPGKey), 1, f);
909 fread( &size, sizeof(int), 1, f);
915 fread( &type, sizeof(__u8), 1, f);
916 fread( &len, sizeof(__u8), 1, f);
917 event = new eventData(0, len, type);
918 event->EITdata = new __u8[len];
919 eventData::CacheSize+=len;
920 fread( event->EITdata, len, 1, f);
921 evMap[ event->getEventID() ]=event;
922 tmMap[ event->getStartTime() ]=event;
925 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
928 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
929 #ifdef ENABLE_PRIVATE_EPG
931 fread( text2, 11, 1, f);
932 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
935 fread( &size, sizeof(int), 1, f);
940 fread( &key, sizeof(uniqueEPGKey), 1, f);
941 eventMap &evMap=eventDB[key].first;
942 fread( &size, sizeof(int), 1, f);
947 fread( &content_id, sizeof(int), 1, f);
948 fread( &size, sizeof(int), 1, f);
953 fread( &time1, sizeof(time_t), 1, f);
954 fread( &time2, sizeof(time_t), 1, f);
955 fread( &event_id, sizeof(__u16), 1, f);
956 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
957 eventMap::iterator it =
958 evMap.find(event_id);
959 if (it != evMap.end())
960 it->second->type = PRIVATE;
965 #endif // ENABLE_PRIVATE_EPG
968 eDebug("[EPGC] don't read old epg database");
974 void eEPGCache::save()
978 if (statfs("/hdd", &s)<0)
986 // prevent writes to builtin flash
987 if ( tmp < 1024*1024*50 ) // storage size < 50MB
990 // check for enough free space on storage
993 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
996 FILE *f = fopen("/hdd/epg.dat", "w");
1000 unsigned int magic = 0x98765432;
1001 fwrite( &magic, sizeof(int), 1, f);
1002 const char *text = "ENIGMA_EPG_V7";
1003 fwrite( text, 13, 1, f );
1004 int size = eventDB.size();
1005 fwrite( &size, sizeof(int), 1, f );
1006 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1008 timeMap &timemap = service_it->second.second;
1009 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1010 size = timemap.size();
1011 fwrite( &size, sizeof(int), 1, f);
1012 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1014 __u8 len = time_it->second->ByteSize;
1015 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1016 fwrite( &len, sizeof(__u8), 1, f);
1017 fwrite( time_it->second->EITdata, len, 1, f);
1021 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
1023 #ifdef ENABLE_PRIVATE_EPG
1024 const char* text3 = "PRIVATE_EPG";
1025 fwrite( text3, 11, 1, f );
1026 size = content_time_tables.size();
1027 fwrite( &size, sizeof(int), 1, f);
1028 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1030 contentMap &content_time_table = a->second;
1031 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1032 int size = content_time_table.size();
1033 fwrite( &size, sizeof(int), 1, f);
1034 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1036 int size = i->second.size();
1037 fwrite( &i->first, sizeof(int), 1, f);
1038 fwrite( &size, sizeof(int), 1, f);
1039 for ( contentTimeMap::iterator it(i->second.begin());
1040 it != i->second.end(); ++it )
1042 fwrite( &it->first, sizeof(time_t), 1, f);
1043 fwrite( &it->second.first, sizeof(time_t), 1, f);
1044 fwrite( &it->second.second, sizeof(__u16), 1, f);
1051 unsigned char md5[16];
1052 if (!md5_file("/hdd/epg.dat", 1, md5))
1054 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1057 fwrite( md5, 16, 1, f);
1065 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1067 ,abortTimer(ml), zapTimer(ml), state(0)
1068 ,isRunning(0), haveData(0)
1069 #ifdef ENABLE_PRIVATE_EPG
1070 ,startPrivateTimer(ml)
1072 #ifdef ENABLE_MHW_EPG
1073 ,m_MHWTimeoutTimer(ml)
1076 #ifdef ENABLE_MHW_EPG
1077 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1079 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1080 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1081 #ifdef ENABLE_PRIVATE_EPG
1082 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1084 pthread_mutex_init(&channel_active, 0);
1087 bool eEPGCache::channel_data::finishEPG()
1089 if (!isRunning) // epg ready
1091 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1092 zapTimer.start(UPDATE_INTERVAL, 1);
1093 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1094 for (int i=0; i < 3; ++i)
1096 seenSections[i].clear();
1097 calcedSections[i].clear();
1099 singleLock l(cache->cache_lock);
1100 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1101 #ifdef ENABLE_MHW_EPG
1109 void eEPGCache::channel_data::startEPG()
1111 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1114 for (int i=0; i < 3; ++i)
1116 seenSections[i].clear();
1117 calcedSections[i].clear();
1120 eDVBSectionFilterMask mask;
1121 memset(&mask, 0, sizeof(mask));
1123 #ifdef ENABLE_MHW_EPG
1125 mask.data[0] = 0x91;
1126 mask.mask[0] = 0xFF;
1127 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1128 m_MHWReader->start(mask);
1130 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1133 mask.data[0] = 0xC8;
1134 mask.mask[0] = 0xFF;
1136 mask.mask[1] = 0xFF;
1137 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1138 m_MHWReader2->start(mask);
1140 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1146 mask.flags = eDVBSectionFilterMask::rfCRC;
1148 mask.data[0] = 0x4E;
1149 mask.mask[0] = 0xFE;
1150 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1151 m_NowNextReader->start(mask);
1152 isRunning |= NOWNEXT;
1154 mask.data[0] = 0x50;
1155 mask.mask[0] = 0xF0;
1156 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1157 m_ScheduleReader->start(mask);
1158 isRunning |= SCHEDULE;
1160 mask.data[0] = 0x60;
1161 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1162 m_ScheduleOtherReader->start(mask);
1163 isRunning |= SCHEDULE_OTHER;
1165 abortTimer.start(7000,true);
1168 void eEPGCache::channel_data::abortNonAvail()
1172 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1174 eDebug("[EPGC] abort non avail nownext reading");
1175 isRunning &= ~NOWNEXT;
1176 m_NowNextReader->stop();
1179 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1181 eDebug("[EPGC] abort non avail schedule reading");
1182 isRunning &= ~SCHEDULE;
1183 m_ScheduleReader->stop();
1186 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1188 eDebug("[EPGC] abort non avail schedule_other reading");
1189 isRunning &= ~SCHEDULE_OTHER;
1190 m_ScheduleOtherReader->stop();
1191 m_ScheduleOtherConn=0;
1193 #ifdef ENABLE_MHW_EPG
1194 if ( !(haveData&MHW) && (isRunning&MHW) )
1196 eDebug("[EPGC] abort non avail mhw reading");
1198 m_MHWReader->stop();
1200 m_MHWReader2->stop();
1205 abortTimer.start(90000, true);
1209 for (int i=0; i < 3; ++i)
1211 seenSections[i].clear();
1212 calcedSections[i].clear();
1219 void eEPGCache::channel_data::startChannel()
1221 pthread_mutex_lock(&channel_active);
1222 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1224 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1226 if (update < ZAP_DELAY)
1229 zapTimer.start(update, 1);
1230 if (update >= 60000)
1231 eDebug("[EPGC] next update in %i min", update/60000);
1232 else if (update >= 1000)
1233 eDebug("[EPGC] next update in %i sec", update/1000);
1236 void eEPGCache::channel_data::abortEPG()
1238 for (int i=0; i < 3; ++i)
1240 seenSections[i].clear();
1241 calcedSections[i].clear();
1247 eDebug("[EPGC] abort caching events !!");
1248 if (isRunning & SCHEDULE)
1250 isRunning &= ~SCHEDULE;
1251 m_ScheduleReader->stop();
1254 if (isRunning & NOWNEXT)
1256 isRunning &= ~NOWNEXT;
1257 m_NowNextReader->stop();
1260 if (isRunning & SCHEDULE_OTHER)
1262 isRunning &= ~SCHEDULE_OTHER;
1263 m_ScheduleOtherReader->stop();
1264 m_ScheduleOtherConn=0;
1266 #ifdef ENABLE_MHW_EPG
1267 if (isRunning & MHW)
1270 m_MHWReader->stop();
1272 m_MHWReader2->stop();
1277 #ifdef ENABLE_PRIVATE_EPG
1278 if (m_PrivateReader)
1279 m_PrivateReader->stop();
1283 pthread_mutex_unlock(&channel_active);
1286 void eEPGCache::channel_data::readData( const __u8 *data)
1290 iDVBSectionReader *reader=NULL;
1294 reader=m_NowNextReader;
1299 reader=m_ScheduleReader;
1304 reader=m_ScheduleOtherReader;
1305 source=SCHEDULE_OTHER;
1309 eDebug("[EPGC] unknown table_id !!!");
1312 tidMap &seenSections = this->seenSections[map];
1313 tidMap &calcedSections = this->calcedSections[map];
1314 if ( state == 1 && calcedSections == seenSections || state > 1 )
1316 eDebugNoNewLine("[EPGC] ");
1321 eDebugNoNewLine("nownext");
1325 eDebugNoNewLine("schedule");
1327 case SCHEDULE_OTHER:
1328 m_ScheduleOtherConn=0;
1329 eDebugNoNewLine("schedule other");
1331 default: eDebugNoNewLine("unknown");break;
1333 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1336 isRunning &= ~source;
1342 eit_t *eit = (eit_t*) data;
1343 __u32 sectionNo = data[0] << 24;
1344 sectionNo |= data[3] << 16;
1345 sectionNo |= data[4] << 8;
1346 sectionNo |= eit->section_number;
1348 tidMap::iterator it =
1349 seenSections.find(sectionNo);
1351 if ( it == seenSections.end() )
1353 seenSections.insert(sectionNo);
1354 calcedSections.insert(sectionNo);
1355 __u32 tmpval = sectionNo & 0xFFFFFF00;
1356 __u8 incr = source == NOWNEXT ? 1 : 8;
1357 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1359 if ( i == eit->section_number )
1361 for (int x=i; x <= eit->segment_last_section_number; ++x)
1362 calcedSections.insert(tmpval|(x&0xFF));
1365 calcedSections.insert(tmpval|(i&0xFF));
1367 cache->sectionRead(data, source, this);
1372 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1373 // if t == -1 we search the current event...
1375 singleLock s(cache_lock);
1376 uniqueEPGKey key(handleGroup(service));
1378 // check if EPG for this service is ready...
1379 eventCache::iterator It = eventDB.find( key );
1380 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1383 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1384 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1385 It->second.second.upper_bound(t); // just >
1386 if ( i != It->second.second.end() )
1388 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1390 timeMap::iterator x = i;
1392 if ( x != It->second.second.end() )
1394 time_t start_time = x->second->getStartTime();
1399 if (t > (start_time+x->second->getDuration()))
1414 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1416 singleLock s(cache_lock);
1417 const eventData *data=0;
1418 RESULT ret = lookupEventTime(service, t, data, direction);
1420 result = data->get();
1424 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1426 singleLock s(cache_lock);
1427 const eventData *data=0;
1428 RESULT ret = lookupEventTime(service, t, data, direction);
1430 result = new Event((uint8_t*)data->get());
1434 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1436 singleLock s(cache_lock);
1437 const eventData *data=0;
1438 RESULT ret = lookupEventTime(service, t, data, direction);
1441 Event ev((uint8_t*)data->get());
1442 result = new eServiceEvent();
1443 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1444 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1449 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1451 singleLock s(cache_lock);
1452 uniqueEPGKey key(handleGroup(service));
1454 eventCache::iterator It = eventDB.find( key );
1455 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1457 eventMap::iterator i( It->second.first.find( event_id ));
1458 if ( i != It->second.first.end() )
1466 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1472 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1474 singleLock s(cache_lock);
1475 const eventData *data=0;
1476 RESULT ret = lookupEventId(service, event_id, data);
1478 result = data->get();
1482 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1484 singleLock s(cache_lock);
1485 const eventData *data=0;
1486 RESULT ret = lookupEventId(service, event_id, data);
1488 result = new Event((uint8_t*)data->get());
1492 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1494 singleLock s(cache_lock);
1495 const eventData *data=0;
1496 RESULT ret = lookupEventId(service, event_id, data);
1499 Event ev((uint8_t*)data->get());
1500 result = new eServiceEvent();
1501 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1502 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1507 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1510 eventCache::iterator It = eventDB.find(handleGroup(service));
1511 if ( It != eventDB.end() && It->second.second.size() )
1513 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1516 m_timemap_cursor = It->second.second.lower_bound(begin);
1517 if ( m_timemap_cursor != It->second.second.end() )
1519 if ( m_timemap_cursor->second->getStartTime() != begin )
1521 timeMap::iterator x = m_timemap_cursor;
1523 if ( x != It->second.second.end() )
1525 time_t start_time = x->second->getStartTime();
1526 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1527 m_timemap_cursor = x;
1533 m_timemap_cursor = It->second.second.begin();
1534 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1535 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1543 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1545 if ( m_timemap_cursor != m_timemap_end )
1547 result = m_timemap_cursor++->second;
1553 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1555 if ( m_timemap_cursor != m_timemap_end )
1557 result = m_timemap_cursor++->second->get();
1563 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1565 if ( m_timemap_cursor != m_timemap_end )
1567 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1573 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1575 if ( m_timemap_cursor != m_timemap_end )
1577 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1578 result = new eServiceEvent();
1579 return result->parseFrom(&ev, currentQueryTsidOnid);
1584 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, ePtr<eServiceEvent> &ptr, ePyObject nowTime, ePyObject service_name )
1588 while(pos < argcount)
1590 bool inc_refcount=false;
1591 switch(argstring[pos])
1593 case '0': // PyLong 0
1594 tmp = PyLong_FromLong(0);
1596 case 'I': // Event Id
1597 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1599 case 'B': // Event Begin Time
1600 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1602 case 'D': // Event Duration
1603 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1605 case 'T': // Event Title
1606 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1608 case 'S': // Event Short Description
1609 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1611 case 'E': // Event Extended Description
1612 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1614 case 'C': // Current Time
1616 inc_refcount = true;
1618 case 'R': // service reference string
1620 inc_refcount = true;
1622 case 'N': // service name
1624 inc_refcount = true;
1629 inc_refcount = true;
1633 PyTuple_SET_ITEM(tuple, pos++, tmp);
1637 int handleEvent(ePtr<eServiceEvent> &ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1641 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1642 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1646 Py_DECREF(service_name);
1649 Py_DECREF(convertFuncArgs);
1650 Py_DECREF(dest_list);
1651 PyErr_SetString(PyExc_StandardError,
1652 "error in convertFunc execute");
1653 eDebug("error in convertFunc execute");
1656 PyList_Append(dest_list, result);
1661 ePyObject tuple = PyTuple_New(argcount);
1662 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1663 PyList_Append(dest_list, tuple);
1669 // here we get a python list
1670 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1673 // B = Event Begin Time
1674 // D = Event Duration
1676 // S = Event Short Description
1677 // E = Event Extended Description
1679 // R = Service Reference
1681 // then for each service follows a tuple
1682 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1683 // the second is the type of query
1685 // -1 = event before given start_time
1686 // 0 = event intersects given start_time
1687 // +1 = event after given start_time
1689 // when type is eventid it is the event_id
1690 // when type is time then it is the start_time ( 0 for now_time )
1691 // the fourth is the end_time .. ( optional .. for query all events in time range)
1693 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1695 ePyObject convertFuncArgs;
1697 char *argstring=NULL;
1698 if (!PyList_Check(list))
1700 PyErr_SetString(PyExc_StandardError,
1706 int listSize=PyList_Size(list);
1709 PyErr_SetString(PyExc_StandardError,
1710 "not params given");
1711 eDebug("not params given");
1716 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1717 if (PyString_Check(argv))
1719 argstring = PyString_AS_STRING(argv);
1723 argstring = "I"; // just event id as default
1724 argcount = strlen(argstring);
1725 // eDebug("have %d args('%s')", argcount, argstring);
1729 if (!PyCallable_Check(convertFunc))
1731 PyErr_SetString(PyExc_StandardError,
1732 "convertFunc must be callable");
1733 eDebug("convertFunc is not callable");
1736 convertFuncArgs = PyTuple_New(argcount);
1739 ePyObject nowTime = strchr(argstring, 'C') ?
1740 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1743 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1746 ePyObject dest_list=PyList_New(0);
1747 while(listSize > listIt)
1749 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1750 if (PyTuple_Check(item))
1752 bool service_changed=false;
1757 int tupleSize=PyTuple_Size(item);
1760 while(tupleSize > tupleIt) // parse query args
1762 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1767 if (!PyString_Check(entry))
1769 eDebug("tuple entry 0 is no a string");
1776 type=PyInt_AsLong(entry);
1777 if (type < -1 || type > 2)
1779 eDebug("unknown type %d", type);
1784 event_id=stime=PyInt_AsLong(entry);
1787 minutes=PyInt_AsLong(entry);
1790 eDebug("unneeded extra argument");
1794 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1795 if (ref.type != eServiceReference::idDVB)
1797 eDebug("service reference for epg query is not valid");
1801 // redirect subservice querys to parent service
1802 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1803 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1805 eServiceCenterPtr service_center;
1806 if (!eServiceCenter::getPrivInstance(service_center))
1808 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1809 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1810 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1811 dvb_ref.setParentServiceID(eServiceID(0));
1813 service = PyString_FromString(dvb_ref.toString().c_str());
1814 service_changed = true;
1818 ePyObject service_name;
1819 if (must_get_service_name)
1821 ePtr<iStaticServiceInformation> sptr;
1822 eServiceCenterPtr service_center;
1823 eServiceCenter::getPrivInstance(service_center);
1826 service_center->info(ref, sptr);
1830 sptr->getName(ref, name);
1832 service_name = PyString_FromString(name.c_str());
1836 service_name = PyString_FromString("<n/a>");
1841 if (!startTimeQuery(ref, stime, minutes))
1843 ePtr<eServiceEvent> ptr;
1844 while (!getNextTimeEntry(ptr))
1846 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1857 ePtr<eServiceEvent> ptr;
1861 lookupEventId(ref, event_id, ptr);
1863 lookupEventTime(ref, stime, ptr, type);
1865 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1868 if (service_changed)
1871 Py_DECREF(service_name);
1876 if (convertFuncArgs)
1877 Py_DECREF(convertFuncArgs);
1883 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, ePyObject service_name, ePyObject service_reference)
1887 while(pos < argcount)
1889 bool inc_refcount=false;
1890 switch(argstring[pos])
1892 case '0': // PyLong 0
1893 tmp = PyLong_FromLong(0);
1895 case 'I': // Event Id
1896 tmp = PyLong_FromLong(evData->getEventID());
1898 case 'B': // Event Begin Time
1900 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1902 tmp = PyLong_FromLong(evData->getStartTime());
1904 case 'D': // Event Duration
1906 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1908 tmp = PyLong_FromLong(evData->getDuration());
1910 case 'T': // Event Title
1911 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1913 case 'S': // Event Short Description
1914 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1916 case 'E': // Event Extended Description
1917 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1919 case 'R': // service reference string
1920 tmp = service_reference;
1921 inc_refcount = true;
1923 case 'N': // service name
1925 inc_refcount = true;
1931 inc_refcount = true;
1935 PyTuple_SET_ITEM(tuple, pos++, tmp);
1939 // here we get a python tuple
1940 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1942 // B = Event Begin Time
1943 // D = Event Duration
1945 // S = Event Short Description
1946 // E = Event Extended Description
1947 // R = Service Reference
1949 // the second tuple entry is the MAX matches value
1950 // the third tuple entry is the type of query
1951 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1952 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1953 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1954 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1955 // the fourth is the servicereference string
1956 // the fifth is the eventid
1957 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1958 // the fourth is the search text
1960 // 0 = case sensitive (CASE_CHECK)
1961 // 1 = case insensitive (NO_CASECHECK)
1963 PyObject *eEPGCache::search(ePyObject arg)
1969 const char *argstring=0;
1973 bool needServiceEvent=false;
1976 if (PyTuple_Check(arg))
1978 int tuplesize=PyTuple_Size(arg);
1981 ePyObject obj = PyTuple_GET_ITEM(arg,0);
1982 if (PyString_Check(obj))
1984 argcount = PyString_GET_SIZE(obj);
1985 argstring = PyString_AS_STRING(obj);
1986 for (int i=0; i < argcount; ++i)
1987 switch(argstring[i])
1992 needServiceEvent=true;
1999 PyErr_SetString(PyExc_StandardError,
2001 eDebug("tuple arg 0 is not a string");
2006 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2009 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2010 if (tuplesize > 4 && querytype == 0)
2012 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2013 if (PyString_Check(obj))
2015 refstr = PyString_AS_STRING(obj);
2016 eServiceReferenceDVB ref(refstr);
2019 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2020 singleLock s(cache_lock);
2021 const eventData *evData = 0;
2022 lookupEventId(ref, eventid, evData);
2025 __u8 *data = evData->EITdata;
2026 int tmp = evData->ByteSize-10;
2027 __u32 *p = (__u32*)(data+10);
2028 // search short and extended event descriptors
2032 descriptorMap::iterator it =
2033 eventData::descriptors.find(crc);
2034 if (it != eventData::descriptors.end())
2036 __u8 *descr_data = it->second.second;
2037 switch(descr_data[0])
2040 descr[++descridx]=crc;
2049 eDebug("event not found");
2053 PyErr_SetString(PyExc_StandardError,
2055 eDebug("tuple arg 4 is not a valid service reference string");
2061 PyErr_SetString(PyExc_StandardError,
2063 eDebug("tuple arg 4 is not a string");
2067 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2069 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2070 if (PyString_Check(obj))
2072 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2073 const char *str = PyString_AS_STRING(obj);
2074 int textlen = PyString_GET_SIZE(obj);
2076 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2078 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2079 singleLock s(cache_lock);
2080 for (descriptorMap::iterator it(eventData::descriptors.begin());
2081 it != eventData::descriptors.end() && descridx < 511; ++it)
2083 __u8 *data = it->second.second;
2084 if ( data[0] == 0x4D ) // short event descriptor
2086 int title_len = data[5];
2087 if ( querytype == 1 )
2089 if (title_len > textlen)
2091 else if (title_len < textlen)
2095 if ( !strncasecmp((const char*)data+6, str, title_len) )
2097 // std::string s((const char*)data+6, title_len);
2098 // eDebug("match1 %s %s", str, s.c_str() );
2099 descr[++descridx] = it->first;
2102 else if ( !strncmp((const char*)data+6, str, title_len) )
2104 // std::string s((const char*)data+6, title_len);
2105 // eDebug("match2 %s %s", str, s.c_str() );
2106 descr[++descridx] = it->first;
2112 while((title_len-idx) >= textlen)
2116 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2118 descr[++descridx] = it->first;
2119 // std::string s((const char*)data+6, title_len);
2120 // eDebug("match 3 %s %s", str, s.c_str() );
2123 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2125 descr[++descridx] = it->first;
2126 // std::string s((const char*)data+6, title_len);
2127 // eDebug("match 4 %s %s", str, s.c_str() );
2139 PyErr_SetString(PyExc_StandardError,
2141 eDebug("tuple arg 4 is not a string");
2147 PyErr_SetString(PyExc_StandardError,
2149 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2155 PyErr_SetString(PyExc_StandardError,
2157 eDebug("not enough args in tuple");
2163 PyErr_SetString(PyExc_StandardError,
2165 eDebug("arg 0 is not a tuple");
2169 ASSERT(descridx <= 512);
2173 int maxcount=maxmatches;
2174 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2175 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2176 // in this case we start searching with the base service
2177 bool first = ref.valid() ? true : false;
2178 singleLock s(cache_lock);
2179 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2180 while(cit != eventDB.end() && maxcount)
2182 if ( ref.valid() && !first && cit->first == ref )
2184 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2188 ePyObject service_name;
2189 ePyObject service_reference;
2190 timeMap &evmap = cit->second.second;
2192 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2194 int evid = evit->second->getEventID();
2195 if ( evid == eventid)
2197 __u8 *data = evit->second->EITdata;
2198 int tmp = evit->second->ByteSize-12;
2199 __u32 *p = (__u32*)(data+12);
2200 // check if any of our descriptor used by this event
2205 for ( int i=0; i <= descridx; ++i)
2207 if (descr[i] == crc32) // found...
2212 if ( (querytype == 0 && cnt == descridx) ||
2213 ((querytype == 1 || querytype == 2) && cnt != -1) )
2215 const uniqueEPGKey &service = cit->first;
2216 eServiceReference ref =
2217 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2220 // create servive event
2221 ePtr<eServiceEvent> ptr;
2222 if (needServiceEvent)
2224 lookupEventId(ref, evid, ptr);
2226 eDebug("event not found !!!!!!!!!!!");
2228 // create service name
2229 if (!service_name && strchr(argstring,'N'))
2231 ePtr<iStaticServiceInformation> sptr;
2232 eServiceCenterPtr service_center;
2233 eServiceCenter::getPrivInstance(service_center);
2236 service_center->info(ref, sptr);
2240 sptr->getName(ref, name);
2242 service_name = PyString_FromString(name.c_str());
2246 service_name = PyString_FromString("<n/a>");
2248 // create servicereference string
2249 if (!service_reference && strchr(argstring,'R'))
2250 service_reference = PyString_FromString(ref.toString().c_str());
2253 ret = PyList_New(0);
2255 ePyObject tuple = PyTuple_New(argcount);
2257 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2258 PyList_Append(ret, tuple);
2265 Py_DECREF(service_name);
2266 if (service_reference)
2267 Py_DECREF(service_reference);
2270 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2272 cit=eventDB.begin();
2285 #ifdef ENABLE_PRIVATE_EPG
2286 #include <dvbsi++/descriptor_tag.h>
2287 #include <dvbsi++/unknown_descriptor.h>
2288 #include <dvbsi++/private_data_specifier_descriptor.h>
2290 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2292 ePtr<eTable<ProgramMapSection> > ptr;
2293 if (!pmthandler->getPMT(ptr) && ptr)
2295 std::vector<ProgramMapSection*>::const_iterator i;
2296 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2298 const ProgramMapSection &pmt = **i;
2300 ElementaryStreamInfoConstIterator es;
2301 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2304 switch ((*es)->getType())
2306 case 0x05: // private
2307 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2308 desc != (*es)->getDescriptors()->end(); ++desc)
2310 switch ((*desc)->getTag())
2312 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2313 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2318 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2319 int descr_len = descr->getLength();
2322 uint8_t data[descr_len+2];
2323 descr->writeToBuffer(data);
2324 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2338 eServiceReferenceDVB ref;
2339 if (!pmthandler->getServiceReference(ref))
2341 int pid = (*es)->getPid();
2342 messages.send(Message(Message::got_private_pid, ref, pid));
2350 eDebug("PMTready but no pmt!!");
2357 date_time( const date_time &a )
2359 memcpy(data, a.data, 5);
2362 date_time( const __u8 data[5])
2364 memcpy(this->data, data, 5);
2365 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2370 const __u8& operator[](int pos) const
2376 struct less_datetime
2378 bool operator()( const date_time &a, const date_time &b ) const
2380 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2384 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2386 contentMap &content_time_table = content_time_tables[current_service];
2387 singleLock s(cache_lock);
2388 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2389 eventMap &evMap = eventDB[current_service].first;
2390 timeMap &tmMap = eventDB[current_service].second;
2392 int content_id = data[ptr++] << 24;
2393 content_id |= data[ptr++] << 16;
2394 content_id |= data[ptr++] << 8;
2395 content_id |= data[ptr++];
2397 contentTimeMap &time_event_map =
2398 content_time_table[content_id];
2399 for ( contentTimeMap::iterator it( time_event_map.begin() );
2400 it != time_event_map.end(); ++it )
2402 eventMap::iterator evIt( evMap.find(it->second.second) );
2403 if ( evIt != evMap.end() )
2405 delete evIt->second;
2408 tmMap.erase(it->second.first);
2410 time_event_map.clear();
2413 memcpy(duration, data+ptr, 3);
2416 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2418 const __u8 *descriptors[65];
2419 const __u8 **pdescr = descriptors;
2421 int descriptors_length = (data[ptr++]&0x0F) << 8;
2422 descriptors_length |= data[ptr++];
2423 while ( descriptors_length > 1 )
2425 int descr_type = data[ptr];
2426 int descr_len = data[ptr+1];
2427 descriptors_length -= 2;
2428 if (descriptors_length >= descr_len)
2430 descriptors_length -= descr_len;
2431 if ( descr_type == 0xf2 && descr_len > 5)
2434 int tsid = data[ptr++] << 8;
2435 tsid |= data[ptr++];
2436 int onid = data[ptr++] << 8;
2437 onid |= data[ptr++];
2438 int sid = data[ptr++] << 8;
2441 // WORKAROUND for wrong transmitted epg data (01.08.2006)
2444 switch( (tsid << 16) | sid )
2446 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2447 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2448 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2449 case 0x0300f5: sid = 0xdc; break;
2450 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2451 case 0x1100d3: sid = 0xe3; break;
2454 ////////////////////////////////////////////
2456 uniqueEPGKey service( sid, onid, tsid );
2458 while( descr_len > 2 )
2461 datetime[0] = data[ptr++];
2462 datetime[1] = data[ptr++];
2463 int tmp_len = data[ptr++];
2465 if (descr_len >= tmp_len)
2467 descr_len -= tmp_len;
2468 while( tmp_len > 2 )
2470 memcpy(datetime+2, data+ptr, 3);
2473 start_times[datetime].push_back(service);
2486 ASSERT(pdescr <= &descriptors[65])
2488 eit_event_struct *ev_struct = (eit_event_struct*) event;
2489 ev_struct->running_status = 0;
2490 ev_struct->free_CA_mode = 1;
2491 memcpy(event+7, duration, 3);
2493 const __u8 **d=descriptors;
2494 while ( d < pdescr )
2496 memcpy(event+ptr, *d, ((*d)[1])+2);
2500 ASSERT(ptr <= 4098);
2501 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2503 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2504 if ( (it->first.tm + duration_sec) < now )
2506 memcpy(event+2, it->first.data, 5);
2509 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2511 event[bptr++] = 0x4A;
2512 __u8 *len = event+(bptr++);
2513 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2514 event[bptr++] = (i->tsid & 0xFF);
2515 event[bptr++] = (i->onid & 0xFF00) >> 8;
2516 event[bptr++] = (i->onid & 0xFF);
2517 event[bptr++] = (i->sid & 0xFF00) >> 8;
2518 event[bptr++] = (i->sid & 0xFF);
2519 event[bptr++] = 0xB0;
2520 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2521 *len = ((event+bptr) - len)-1;
2523 int llen = bptr - 12;
2524 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2525 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2527 time_t stime = it->first.tm;
2528 while( tmMap.find(stime) != tmMap.end() )
2530 event[6] += (stime - it->first.tm);
2532 while( evMap.find(event_id) != evMap.end() )
2534 event[0] = (event_id & 0xFF00) >> 8;
2535 event[1] = (event_id & 0xFF);
2536 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2537 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2538 evMap[event_id] = d;
2540 ASSERT(bptr <= 4098);
2544 void eEPGCache::channel_data::startPrivateReader()
2546 eDVBSectionFilterMask mask;
2547 memset(&mask, 0, sizeof(mask));
2548 mask.pid = m_PrivatePid;
2549 mask.flags = eDVBSectionFilterMask::rfCRC;
2550 mask.data[0] = 0xA0;
2551 mask.mask[0] = 0xFF;
2552 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2553 if (m_PrevVersion != -1)
2555 mask.data[3] = m_PrevVersion << 1;
2556 mask.mask[3] = 0x3E;
2557 mask.mode[3] = 0x3E;
2559 seenPrivateSections.clear();
2561 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2562 m_PrivateReader->start(mask);
2565 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2567 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2569 cache->privateSectionRead(m_PrivateService, data);
2570 seenPrivateSections.insert(data[6]);
2572 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2574 eDebug("[EPGC] private finished");
2575 eDVBChannelID chid = channel->getChannelID();
2576 int tmp = chid.original_network_id.get();
2577 tmp |= 0x80000000; // we use highest bit as private epg indicator
2578 chid.original_network_id = tmp;
2579 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2580 m_PrevVersion = (data[5] & 0x3E) >> 1;
2581 startPrivateReader();
2585 #endif // ENABLE_PRIVATE_EPG
2587 #ifdef ENABLE_MHW_EPG
2588 void eEPGCache::channel_data::cleanup()
2593 m_program_ids.clear();
2596 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2598 // Names in mhw structs are not strings as they are not '\0' terminated.
2599 // This function converts the mhw name into a string.
2600 // Constraint: "length of out" = "length of in" + 1.
2602 for ( i=0; i < len_in; i++ )
2606 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2613 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2616 return_time[0] = toBCD( hours );
2617 return_time[1] = toBCD( minutes );
2621 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2623 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2626 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2627 // For date plus time of day
2629 // Remove offset in mhw time.
2630 __u8 local_hours = hours;
2633 else if ( hours >= 8 )
2636 // As far as we know all mhw time data is sent in central Europe time zone.
2637 // So, temporarily set timezone to western europe
2638 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2640 char *old_tz = getenv( "TZ" );
2641 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2645 localtime_r(&dt, &localnow);
2649 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2651 if (local_hours <= 5)
2654 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2655 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2658 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2660 if ( old_tz == NULL )
2666 // Calculate MJD according to annex in ETSI EN 300 468
2668 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2670 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2671 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2673 return_time[0] = (mjd & 0xFF00)>>8;
2674 return_time[1] = mjd & 0xFF;
2676 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2679 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2680 // data is borrowed from calling proc to save memory space.
2683 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2684 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2685 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2687 eit_t *packet = (eit_t *) data;
2688 packet->table_id = 0x50;
2689 packet->section_syntax_indicator = 1;
2690 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2691 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2692 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2693 packet->current_next_indicator = 0;
2694 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2695 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2696 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2697 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2698 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2699 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2700 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2701 packet->segment_last_table_id = 0x50;
2703 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2704 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2705 int prog_title_length = prog_title.length();
2707 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2708 prog_title_length + 1;
2710 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2711 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2712 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2716 u_char *data = (u_char*) event_data;
2717 data[2] = itTitle->second.mhw2_mjd_hi;
2718 data[3] = itTitle->second.mhw2_mjd_lo;
2719 data[4] = itTitle->second.mhw2_hours;
2720 data[5] = itTitle->second.mhw2_minutes;
2721 data[6] = itTitle->second.mhw2_seconds;
2722 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2726 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2727 (u_char *) event_data + 2 );
2728 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2731 event_data->running_status = 0;
2732 event_data->free_CA_mode = 0;
2733 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2735 eit_short_event_descriptor_struct *short_event_descriptor =
2736 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2737 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2738 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2739 prog_title_length - 1;
2740 short_event_descriptor->language_code_1 = 'e';
2741 short_event_descriptor->language_code_2 = 'n';
2742 short_event_descriptor->language_code_3 = 'g';
2743 short_event_descriptor->event_name_length = prog_title_length;
2744 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2745 memcpy(event_name, prog_title.c_str(), prog_title_length);
2748 event_name[prog_title_length] = 0;
2750 if ( sumText.length() > 0 )
2751 // There is summary info
2753 unsigned int sum_length = sumText.length();
2754 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2755 // Store summary in short event descriptor
2757 // Increase all relevant lengths
2758 event_name[prog_title_length] = sum_length;
2759 short_event_descriptor->descriptor_length += sum_length;
2760 packet_length += sum_length;
2761 descr_ll += sum_length;
2762 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2765 // Store summary in extended event descriptors
2767 int remaining_sum_length = sumText.length();
2768 int nbr_descr = int(remaining_sum_length/247) + 1;
2769 for ( int i=0; i < nbr_descr; i++)
2770 // Loop once per extended event descriptor
2772 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2773 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2774 remaining_sum_length -= sum_length;
2775 packet_length += 8 + sum_length;
2776 descr_ll += 8 + sum_length;
2778 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2779 ext_event_descriptor->descriptor_length = sum_length + 6;
2780 ext_event_descriptor->descriptor_number = i;
2781 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2782 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2783 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2784 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2785 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2787 the_text[-1] = sum_length;
2788 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2795 // Add content descriptor
2796 u_char *descriptor = (u_char *) data + packet_length;
2801 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2802 if ( content_descr.find( "FILM" ) != std::string::npos )
2804 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2807 descriptor[0] = 0x54;
2809 descriptor[2] = content_id;
2813 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2814 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2816 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2817 packet->section_length_lo = (packet_length - 3)&0xff;
2819 // Feed the data to eEPGCache::sectionRead()
2820 cache->sectionRead( data, MHW, this );
2823 void eEPGCache::channel_data::startTimeout(int msec)
2825 m_MHWTimeoutTimer.start(msec,true);
2826 m_MHWTimeoutet=false;
2829 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2831 m_MHWFilterMask.pid = pid;
2832 m_MHWFilterMask.data[0] = tid;
2833 m_MHWReader->start(m_MHWFilterMask);
2834 // eDebug("start 0x%02x 0x%02x", pid, tid);
2837 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2839 m_MHWFilterMask2.pid = pid;
2840 m_MHWFilterMask2.data[0] = tid;
2843 m_MHWFilterMask2.data[1] = ext;
2844 m_MHWFilterMask2.mask[1] = 0xFF;
2845 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2849 m_MHWFilterMask2.data[1] = 0;
2850 m_MHWFilterMask2.mask[1] = 0;
2851 // eDebug("start 0x%02x 0x%02x", pid, tid);
2853 m_MHWReader2->start(m_MHWFilterMask2);
2856 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2859 m_MHWReader2->stop();
2861 if ( state > 1 || // aborted
2862 // have si data.. so we dont read mhw data
2863 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2865 eDebug("[EPGC] mhw aborted %d", state);
2867 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2870 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2871 int record_size = sizeof( mhw_channel_name_t );
2872 int nbr_records = int (len/record_size);
2874 for ( int i = 0; i < nbr_records; i++ )
2876 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2877 m_channels.push_back( *channel );
2881 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2883 // Channels table has been read, start reading the themes table.
2884 startMHWReader(0xD3, 0x92);
2887 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2890 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2891 int record_size = sizeof( mhw_theme_name_t );
2892 int nbr_records = int (len/record_size);
2894 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2897 for ( int i = 0; i < nbr_records; i++ )
2899 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2900 if ( i >= next_idx )
2904 next_idx = (__u8) *(data + 3 + idx_ptr);
2910 m_themes[idx+sub_idx] = *theme;
2912 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2913 // Themes table has been read, start reading the titles table.
2914 startMHWReader(0xD2, 0x90);
2918 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2921 mhw_title_t *title = (mhw_title_t*) data;
2923 if ( title->channel_id == 0xFF ) // Separator
2924 return; // Continue reading of the current table.
2927 // Create unique key per title
2928 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2929 (title->ms.minutes);
2930 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2931 ((title->program_id_ml)<<8)|(title->program_id_lo);
2933 if ( m_titles.find( title_id ) == m_titles.end() )
2936 title->mhw2_mjd_hi = 0;
2937 title->mhw2_mjd_lo = 0;
2938 title->mhw2_duration_hi = 0;
2939 title->mhw2_duration_lo = 0;
2940 m_titles[ title_id ] = *title;
2941 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2942 // program_ids will be used to gather summaries.
2943 m_program_ids[ program_id ] = title_id;
2944 return; // Continue reading of the current table.
2946 else if (!checkTimeout())
2949 if ( !m_program_ids.empty())
2951 // Titles table has been read, there are summaries to read.
2952 // Start reading summaries, store corresponding titles on the fly.
2953 startMHWReader(0xD3, 0x90);
2954 eDebug("[EPGC] mhw %d titles(%d with summary) found",
2956 m_program_ids.size());
2961 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2964 mhw_summary_t *summary = (mhw_summary_t*) data;
2966 // Create unique key per record
2967 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2968 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2969 int len = ((data[1]&0xf)<<8) + data[2];
2971 // ugly workaround to convert const __u8* to char*
2973 memcpy(&tmp, &data, sizeof(void*));
2974 tmp[len+3] = 0; // Terminate as a string.
2976 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2977 if ( itProgid == m_program_ids.end() )
2978 { /* This part is to prevent to looping forever if some summaries are not received yet.
2979 There is a timeout of 4 sec. after the last successfully read summary. */
2980 if (!m_program_ids.empty() && !checkTimeout())
2981 return; // Continue reading of the current table.
2985 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2988 while((pos = the_text.find("\r\n")) != std::string::npos)
2989 the_text.replace(pos, 2, " ");
2991 // Find corresponding title, store title and summary in epgcache.
2992 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2993 if ( itTitle != m_titles.end() )
2996 storeTitle( itTitle, the_text, data );
2997 m_titles.erase( itTitle );
2999 m_program_ids.erase( itProgid );
3000 if ( !m_program_ids.empty() )
3001 return; // Continue reading of the current table.
3004 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3005 eDVBLocalTimeHandler::getInstance()->nowTime(),
3006 m_program_ids.size());
3007 // Summaries have been read, titles that have summaries have been stored.
3008 // Now store titles that do not have summaries.
3009 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3010 storeTitle( itTitle, "", data );
3014 m_MHWReader->stop();
3019 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3021 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3024 m_MHWReader->stop();
3026 if ( state > 1 || // aborted
3027 // have si data.. so we dont read mhw data
3028 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
3030 eDebug("[EPGC] mhw2 aborted %d", state);
3032 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3035 int num_channels = data[120];
3038 int ptr = 121 + 6 * num_channels;
3041 for( int chid = 0; chid < num_channels; ++chid )
3043 ptr += ( data[ptr] & 0x0f ) + 1;
3053 // data seems consistent...
3054 const __u8 *tmp = data+121;
3055 for (int i=0; i < num_channels; ++i)
3057 mhw_channel_name_t channel;
3058 channel.transport_stream_id_hi = *(tmp++);
3059 channel.transport_stream_id_lo = *(tmp++);
3060 channel.channel_id_hi = *(tmp++);
3061 channel.channel_id_lo = *(tmp++);
3062 #warning FIXME hardcoded network_id in mhw2 epg
3063 channel.network_id_hi = 0; // hardcoded astra 19.2
3064 channel.network_id_lo = 1;
3065 m_channels.push_back(channel);
3068 for (int i=0; i < num_channels; ++i)
3070 mhw_channel_name_t &channel = m_channels[i];
3071 int channel_name_len=*(tmp++)&0x0f;
3073 for (; x < channel_name_len; ++x)
3074 channel.name[x]=*(tmp++);
3075 channel.name[x+1]=0;
3078 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3080 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3083 eDebug("[EPGC] mhw2 themes nyi");
3085 else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3090 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3092 if(data[dataLen-1] != 0xff)
3094 while( pos < dataLen )
3103 if( data[pos] > 0xc0 )
3105 pos += ( data[pos] - 0xc0 );
3109 if( data[pos] == 0xff )
3125 // data seems consistent...
3130 title.channel_id = data[pos]+1;
3131 title.program_id_ml = data[pos+1];
3132 title.program_id_lo = data[pos+2];
3133 title.mhw2_mjd_hi = data[pos+3];
3134 title.mhw2_mjd_lo = data[pos+4];
3135 title.mhw2_hours = data[pos+5];
3136 title.mhw2_minutes = data[pos+6];
3137 title.mhw2_seconds = data[pos+7];
3138 int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3139 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3140 title.mhw2_duration_lo = duration&0xFF;
3141 __u8 slen = data[pos+10] & 0x3f;
3142 __u8 *dest = ((__u8*)title.title)-4;
3143 memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3144 memset(dest+slen, 0x20, 33-slen);
3146 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3147 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3149 // Create unique key per title
3150 __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3152 // eDebug("program_id: %08x, %s", program_id,
3153 // std::string((const char *)title.title, (int)(slen > 23 ? 23 : slen)).c_str());
3157 if ( m_titles.find( title_id ) == m_titles.end() )
3160 m_titles[ title_id ] = title;
3161 if (summary_id != 0xFFFF && // no summary avail
3162 m_program_ids.find(summary_id) == m_program_ids.end())
3164 m_program_ids[ summary_id ] = title_id;
3169 if ( !checkTimeout() )
3170 continue; // Continue reading of the current table.
3178 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3179 if (!m_program_ids.empty())
3181 // Titles table has been read, there are summaries to read.
3182 // Start reading summaries, store corresponding titles on the fly.
3183 startMHWReader2(0x236, 0x96);
3191 else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3194 int len, loop, pos, lenline;
3203 loop = data[pos] & 0x0f;
3208 for( ; loop > 0; --loop )
3210 if( dataLen > (pos+len) )
3212 lenline = data[pos+len];
3221 else if (!checkTimeout())
3222 return; // continue reading
3223 if (valid && !checkTimeout())
3225 // data seems consistent...
3226 __u32 summary_id = (data[3]<<8)|data[4];
3228 // ugly workaround to convert const __u8* to char*
3230 memcpy(&tmp, &data, sizeof(void*));
3235 loop = tmp[pos] & 0x0f;
3237 for( ; loop > 0; loop -- )
3239 lenline = tmp[pos+len];
3248 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( summary_id ) );
3249 if ( itProgid == m_program_ids.end() )
3250 { /* This part is to prevent to looping forever if some summaries are not received yet.
3251 There is a timeout of 4 sec. after the last successfully read summary. */
3253 if ( !m_program_ids.empty() && !checkTimeout() )
3254 return; // Continue reading of the current table.
3259 std::string the_text = (char *) (data + pos + 1);
3261 // Find corresponding title, store title and summary in epgcache.
3262 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3263 if ( itTitle != m_titles.end() )
3265 storeTitle( itTitle, the_text, data );
3266 m_titles.erase( itTitle );
3268 m_program_ids.erase( itProgid );
3269 if ( !m_program_ids.empty() )
3270 return; // Continue reading of the current table.
3274 if (isRunning & eEPGCache::MHW)
3276 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3278 // Channels table has been read, start reading the themes table.
3279 startMHWReader2(0x231, 0xC8, 1);
3282 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3284 // Themes table has been read, start reading the titles table.
3285 startMHWReader2(0x234, 0xe6);
3290 // Summaries have been read, titles that have summaries have been stored.
3291 // Now store titles that do not have summaries.
3292 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3293 storeTitle( itTitle, "", data );
3294 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3295 eDVBLocalTimeHandler::getInstance()->nowTime(),
3296 m_program_ids.size());
3303 m_MHWReader2->stop();