1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
7 #include <lib/service/event.h>
11 #include <unistd.h> // for usleep
12 #include <sys/vfs.h> // for statfs
13 // #include <libmd5sum.h>
14 #include <lib/base/eerror.h>
15 #include <lib/base/estring.h>
16 #include <lib/dvb/pmt.h>
17 #include <lib/dvb/db.h>
18 #include <lib/python/python.h>
19 #include <dvbsi++/descriptor_tag.h>
21 int eventData::CacheSize=0;
22 descriptorMap eventData::descriptors;
23 __u8 eventData::data[4108];
24 extern const uint32_t crc32_table[256];
26 const eServiceReference &handleGroup(const eServiceReference &ref)
28 if (ref.flags & eServiceReference::isGroup)
30 ePtr<eDVBResourceManager> res;
31 if (!eDVBResourceManager::getInstance(res))
33 ePtr<iDVBChannelList> db;
34 if (!res->getChannelList(db))
37 if (!db->getBouquet(ref, bouquet))
39 std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
40 if (it != bouquet->m_services.end())
49 eventData::eventData(const eit_event_struct* e, int size, int type)
50 :ByteSize(size&0xFF), type(type&0xFF)
58 __u8 *data = (__u8*)e;
64 __u8 *descr = data+ptr;
65 int descr_len = descr[1];
67 if (size >= descr_len)
71 case EXTENDED_EVENT_DESCRIPTOR:
72 case SHORT_EVENT_DESCRIPTOR:
73 case LINKAGE_DESCRIPTOR:
74 case COMPONENT_DESCRIPTOR:
78 while(cnt++ < descr_len)
79 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
81 descriptorMap::iterator it =
82 descriptors.find(crc);
83 if ( it == descriptors.end() )
86 __u8 *d = new __u8[descr_len];
87 memcpy(d, descr, descr_len);
88 descriptors[crc] = descriptorPair(1, d);
95 default: // do not cache all other descriptors
104 ASSERT(pdescr <= &descr[65]);
105 ByteSize = 10+((pdescr-descr)*4);
106 EITdata = new __u8[ByteSize];
108 memcpy(EITdata, (__u8*) e, 10);
109 memcpy(EITdata+10, descr, ByteSize-10);
112 const eit_event_struct* eventData::get() const
115 int tmp = ByteSize-10;
116 memcpy(data, EITdata, 10);
117 int descriptors_length=0;
118 __u32 *p = (__u32*)(EITdata+10);
121 descriptorMap::iterator it =
122 descriptors.find(*p++);
123 if ( it != descriptors.end() )
125 int b = it->second.second[1]+2;
126 memcpy(data+pos, it->second.second, b );
128 descriptors_length += b;
131 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(p-1));
135 data[10] = (descriptors_length >> 8) & 0x0F;
136 data[11] = descriptors_length & 0xFF;
137 return (eit_event_struct*)data;
140 eventData::~eventData()
144 CacheSize -= ByteSize;
145 __u32 *d = (__u32*)(EITdata+10);
149 descriptorMap::iterator it =
150 descriptors.find(*d++);
151 if ( it != descriptors.end() )
153 descriptorPair &p = it->second;
154 if (!--p.first) // no more used descriptor
156 CacheSize -= it->second.second[1];
157 delete [] it->second.second; // free descriptor memory
158 descriptors.erase(it); // remove entry from descriptor map
162 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(d-1));
169 void eventData::load(FILE *f)
175 fread(&size, sizeof(int), 1, f);
178 fread(&id, sizeof(__u32), 1, f);
179 fread(&p.first, sizeof(int), 1, f);
180 fread(header, 2, 1, f);
181 int bytes = header[1]+2;
182 p.second = new __u8[bytes];
183 p.second[0] = header[0];
184 p.second[1] = header[1];
185 fread(p.second+2, bytes-2, 1, f);
192 void eventData::save(FILE *f)
194 int size=descriptors.size();
195 descriptorMap::iterator it(descriptors.begin());
196 fwrite(&size, sizeof(int), 1, f);
199 fwrite(&it->first, sizeof(__u32), 1, f);
200 fwrite(&it->second.first, sizeof(int), 1, f);
201 fwrite(it->second.second, it->second.second[1]+2, 1, f);
207 eEPGCache* eEPGCache::instance;
208 pthread_mutex_t eEPGCache::cache_lock=
209 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
210 pthread_mutex_t eEPGCache::channel_map_lock=
211 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
213 DEFINE_REF(eEPGCache)
215 eEPGCache::eEPGCache()
216 :messages(this,1), cleanTimer(this)//, paused(0)
218 eDebug("[EPGC] Initialized EPGCache");
220 CONNECT(messages.recv_msg, eEPGCache::gotMessage);
221 CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
222 CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
224 ePtr<eDVBResourceManager> res_mgr;
225 eDVBResourceManager::getInstance(res_mgr);
227 eDebug("[eEPGCache] no resource manager !!!!!!!");
230 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
231 if (eDVBLocalTimeHandler::getInstance()->ready())
237 void eEPGCache::timeUpdated()
241 eDebug("[EPGC] time updated.. start EPG Mainloop");
244 messages.send(Message(Message::timeChanged));
247 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
251 // eDebug("[eEPGCache] add channel %p", chan);
252 channel_data *data = new channel_data(this);
253 data->channel = chan;
254 data->prevChannelState = -1;
255 #ifdef ENABLE_PRIVATE_EPG
256 data->m_PrivatePid = -1;
258 singleLock s(channel_map_lock);
259 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
260 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
264 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
266 channelMapIterator it =
267 m_knownChannels.find(chan);
268 if ( it == m_knownChannels.end() )
269 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
272 channel_data &data = *it->second;
273 ePtr<eDVBResourceManager> res_mgr;
274 if ( eDVBResourceManager::getInstance( res_mgr ) )
275 eDebug("[eEPGCache] no res manager!!");
278 ePtr<iDVBDemux> demux;
279 if ( data.channel->getDemux(demux, 0) )
281 eDebug("[eEPGCache] no demux!!");
286 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
289 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
293 res = demux->createSectionReader( this, data.m_ScheduleReader );
296 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
300 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
303 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
306 #ifdef ENABLE_PRIVATE_EPG
307 res = demux->createSectionReader( this, data.m_PrivateReader );
310 eDebug("[eEPGCache] couldnt initialize private reader!!");
314 #ifdef ENABLE_MHW_EPG
315 res = demux->createSectionReader( this, data.m_MHWReader );
318 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
321 res = demux->createSectionReader( this, data.m_MHWReader2 );
324 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
328 messages.send(Message(Message::startChannel, chan));
329 // -> gotMessage -> changedService
335 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
337 channelMapIterator it =
338 m_knownChannels.find(chan);
339 if ( it != m_knownChannels.end() )
342 chan->getState(state);
343 if ( it->second->prevChannelState != state )
347 case iDVBChannel::state_ok:
349 eDebug("[eEPGCache] channel %p running", chan);
350 DVBChannelRunning(chan);
353 case iDVBChannel::state_release:
355 eDebug("[eEPGCache] remove channel %p", chan);
356 messages.send(Message(Message::leaveChannel, chan));
357 pthread_mutex_lock(&it->second->channel_active);
358 singleLock s(channel_map_lock);
359 m_knownChannels.erase(it);
360 pthread_mutex_unlock(&it->second->channel_active);
363 // -> gotMessage -> abortEPG
366 default: // ignore all other events
370 it->second->prevChannelState = state;
375 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
377 timeMap::iterator tmp = tm_it;
378 while ((tmp->first+tmp->second->getDuration()-300) > TM)
381 #ifdef ENABLE_PRIVATE_EPG
382 && tmp->second->type != PRIVATE
385 && tmp->second->type != MHW
389 __u16 event_id = tmp->second->getEventID();
390 servicemap.first.erase(event_id);
392 Event evt((uint8_t*)tmp->second->get());
394 event.parseFrom(&evt, service.sid<<16|service.onid);
395 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
396 service.sid, event_id,
397 event.getBeginTimeString().c_str(),
398 event.getEventName().c_str(),
399 event.getExtendedDescription().c_str());
402 if (tmp == servicemap.second.begin())
404 servicemap.second.erase(tmp);
408 servicemap.second.erase(tmp--);
412 if (tmp == servicemap.second.begin())
419 while(tmp->first < (TM+duration-300))
421 if (tmp->first != TM && tmp->second->type != PRIVATE)
423 __u16 event_id = tmp->second->getEventID();
424 servicemap.first.erase(event_id);
426 Event evt((uint8_t*)tmp->second->get());
428 event.parseFrom(&evt, service.sid<<16|service.onid);
429 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
430 service.sid, event_id,
431 event.getBeginTimeString().c_str(),
432 event.getEventName().c_str(),
433 event.getExtendedDescription().c_str());
436 servicemap.second.erase(tmp++);
440 if (tmp == servicemap.second.end())
445 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
447 eit_t *eit = (eit_t*) data;
449 int len=HILO(eit->section_length)-1;//+3-4;
454 // This fixed the EPG on the Multichoice irdeto systems
455 // the EIT packet is non-compliant.. their EIT packet stinks
456 if ( data[ptr-1] < 0x40 )
459 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
460 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
464 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);
465 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
467 if ( TM != 3599 && TM > -1)
468 channel->haveData |= source;
470 singleLock s(cache_lock);
471 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
472 // oder eine durch [] erzeugte
473 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
474 eventMap::iterator prevEventIt = servicemap.first.end();
475 timeMap::iterator prevTimeIt = servicemap.second.end();
479 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
481 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
483 eit_event->start_time_1,
484 eit_event->start_time_2,
485 eit_event->start_time_3,
486 eit_event->start_time_4,
487 eit_event->start_time_5);
492 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
495 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
497 __u16 event_id = HILO(eit_event->event_id);
498 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
501 int ev_erase_count = 0;
502 int tm_erase_count = 0;
504 // search in eventmap
505 eventMap::iterator ev_it =
506 servicemap.first.find(event_id);
508 // entry with this event_id is already exist ?
509 if ( ev_it != servicemap.first.end() )
511 if ( source > ev_it->second->type ) // update needed ?
512 goto next; // when not.. then skip this entry
514 // search this event in timemap
515 timeMap::iterator tm_it_tmp =
516 servicemap.second.find(ev_it->second->getStartTime());
518 if ( tm_it_tmp != servicemap.second.end() )
520 if ( tm_it_tmp->first == TM ) // just update eventdata
523 eventData *tmp = ev_it->second;
524 ev_it->second = tm_it_tmp->second =
525 new eventData(eit_event, eit_event_size, source);
526 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
530 else // event has new event begin time
533 // delete the found record from timemap
534 servicemap.second.erase(tm_it_tmp);
535 prevTimeIt=servicemap.second.end();
540 // search in timemap, for check of a case if new time has coincided with time of other event
541 // or event was is not found in eventmap
542 timeMap::iterator tm_it =
543 servicemap.second.find(TM);
545 if ( tm_it != servicemap.second.end() )
547 // event with same start time but another event_id...
548 if ( source > tm_it->second->type &&
549 ev_it == servicemap.first.end() )
550 goto next; // when not.. then skip this entry
552 // search this time in eventmap
553 eventMap::iterator ev_it_tmp =
554 servicemap.first.find(tm_it->second->getEventID());
556 if ( ev_it_tmp != servicemap.first.end() )
559 // delete the found record from eventmap
560 servicemap.first.erase(ev_it_tmp);
561 prevEventIt=servicemap.first.end();
564 evt = new eventData(eit_event, eit_event_size, source);
566 bool consistencyCheck=true;
568 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
571 delete ev_it->second;
572 delete tm_it->second;
576 else if (ev_erase_count == 0 && tm_erase_count > 0)
579 delete ev_it->second;
580 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
583 else if (ev_erase_count > 0 && tm_erase_count == 0)
586 delete tm_it->second;
587 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 FILE *f = fopen("/hdd/epg.dat", "r");
867 unlink("/hdd/epg.dat");
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 singleLock s(cache_lock);
902 fread( &size, sizeof(int), 1, f);
909 fread( &key, sizeof(uniqueEPGKey), 1, f);
910 fread( &size, sizeof(int), 1, f);
916 fread( &type, sizeof(__u8), 1, f);
917 fread( &len, sizeof(__u8), 1, f);
918 event = new eventData(0, len, type);
919 event->EITdata = new __u8[len];
920 eventData::CacheSize+=len;
921 fread( event->EITdata, len, 1, f);
922 evMap[ event->getEventID() ]=event;
923 tmMap[ event->getStartTime() ]=event;
926 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
929 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
930 #ifdef ENABLE_PRIVATE_EPG
932 fread( text2, 11, 1, f);
933 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
936 fread( &size, sizeof(int), 1, f);
941 fread( &key, sizeof(uniqueEPGKey), 1, f);
942 eventMap &evMap=eventDB[key].first;
943 fread( &size, sizeof(int), 1, f);
948 fread( &content_id, sizeof(int), 1, f);
949 fread( &size, sizeof(int), 1, f);
954 fread( &time1, sizeof(time_t), 1, f);
955 fread( &time2, sizeof(time_t), 1, f);
956 fread( &event_id, sizeof(__u16), 1, f);
957 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
958 eventMap::iterator it =
959 evMap.find(event_id);
960 if (it != evMap.end())
961 it->second->type = PRIVATE;
966 #endif // ENABLE_PRIVATE_EPG
969 eDebug("[EPGC] don't read old epg database");
975 void eEPGCache::save()
979 if (statfs("/hdd", &s)<0)
987 // prevent writes to builtin flash
988 if ( tmp < 1024*1024*50 ) // storage size < 50MB
991 // check for enough free space on storage
994 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
997 FILE *f = fopen("/hdd/epg.dat", "w");
1001 unsigned int magic = 0x98765432;
1002 fwrite( &magic, sizeof(int), 1, f);
1003 const char *text = "ENIGMA_EPG_V7";
1004 fwrite( text, 13, 1, f );
1005 int size = eventDB.size();
1006 fwrite( &size, sizeof(int), 1, f );
1007 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1009 timeMap &timemap = service_it->second.second;
1010 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1011 size = timemap.size();
1012 fwrite( &size, sizeof(int), 1, f);
1013 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1015 __u8 len = time_it->second->ByteSize;
1016 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1017 fwrite( &len, sizeof(__u8), 1, f);
1018 fwrite( time_it->second->EITdata, len, 1, f);
1022 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
1024 #ifdef ENABLE_PRIVATE_EPG
1025 const char* text3 = "PRIVATE_EPG";
1026 fwrite( text3, 11, 1, f );
1027 size = content_time_tables.size();
1028 fwrite( &size, sizeof(int), 1, f);
1029 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1031 contentMap &content_time_table = a->second;
1032 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1033 int size = content_time_table.size();
1034 fwrite( &size, sizeof(int), 1, f);
1035 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1037 int size = i->second.size();
1038 fwrite( &i->first, sizeof(int), 1, f);
1039 fwrite( &size, sizeof(int), 1, f);
1040 for ( contentTimeMap::iterator it(i->second.begin());
1041 it != i->second.end(); ++it )
1043 fwrite( &it->first, sizeof(time_t), 1, f);
1044 fwrite( &it->second.first, sizeof(time_t), 1, f);
1045 fwrite( &it->second.second, sizeof(__u16), 1, f);
1052 unsigned char md5[16];
1053 if (!md5_file("/hdd/epg.dat", 1, md5))
1055 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1058 fwrite( md5, 16, 1, f);
1066 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1068 ,abortTimer(ml), zapTimer(ml), state(0)
1069 ,isRunning(0), haveData(0)
1070 #ifdef ENABLE_PRIVATE_EPG
1071 ,startPrivateTimer(ml)
1073 #ifdef ENABLE_MHW_EPG
1074 ,m_MHWTimeoutTimer(ml)
1077 #ifdef ENABLE_MHW_EPG
1078 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1080 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1081 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1082 #ifdef ENABLE_PRIVATE_EPG
1083 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1085 pthread_mutex_init(&channel_active, 0);
1088 bool eEPGCache::channel_data::finishEPG()
1090 if (!isRunning) // epg ready
1092 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1093 zapTimer.start(UPDATE_INTERVAL, 1);
1094 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1095 for (int i=0; i < 3; ++i)
1097 seenSections[i].clear();
1098 calcedSections[i].clear();
1100 singleLock l(cache->cache_lock);
1101 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1102 #ifdef ENABLE_MHW_EPG
1110 void eEPGCache::channel_data::startEPG()
1112 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1115 for (int i=0; i < 3; ++i)
1117 seenSections[i].clear();
1118 calcedSections[i].clear();
1121 eDVBSectionFilterMask mask;
1122 memset(&mask, 0, sizeof(mask));
1124 #ifdef ENABLE_MHW_EPG
1126 mask.data[0] = 0x91;
1127 mask.mask[0] = 0xFF;
1128 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1129 m_MHWReader->start(mask);
1131 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1134 mask.data[0] = 0xC8;
1135 mask.mask[0] = 0xFF;
1137 mask.mask[1] = 0xFF;
1138 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1139 m_MHWReader2->start(mask);
1141 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1147 mask.flags = eDVBSectionFilterMask::rfCRC;
1149 mask.data[0] = 0x4E;
1150 mask.mask[0] = 0xFE;
1151 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1152 m_NowNextReader->start(mask);
1153 isRunning |= NOWNEXT;
1155 mask.data[0] = 0x50;
1156 mask.mask[0] = 0xF0;
1157 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1158 m_ScheduleReader->start(mask);
1159 isRunning |= SCHEDULE;
1161 mask.data[0] = 0x60;
1162 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1163 m_ScheduleOtherReader->start(mask);
1164 isRunning |= SCHEDULE_OTHER;
1166 abortTimer.start(7000,true);
1169 void eEPGCache::channel_data::abortNonAvail()
1173 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1175 eDebug("[EPGC] abort non avail nownext reading");
1176 isRunning &= ~NOWNEXT;
1177 m_NowNextReader->stop();
1180 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1182 eDebug("[EPGC] abort non avail schedule reading");
1183 isRunning &= ~SCHEDULE;
1184 m_ScheduleReader->stop();
1187 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1189 eDebug("[EPGC] abort non avail schedule_other reading");
1190 isRunning &= ~SCHEDULE_OTHER;
1191 m_ScheduleOtherReader->stop();
1192 m_ScheduleOtherConn=0;
1194 #ifdef ENABLE_MHW_EPG
1195 if ( !(haveData&MHW) && (isRunning&MHW) )
1197 eDebug("[EPGC] abort non avail mhw reading");
1199 m_MHWReader->stop();
1201 m_MHWReader2->stop();
1206 abortTimer.start(90000, true);
1210 for (int i=0; i < 3; ++i)
1212 seenSections[i].clear();
1213 calcedSections[i].clear();
1220 void eEPGCache::channel_data::startChannel()
1222 pthread_mutex_lock(&channel_active);
1223 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1225 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1227 if (update < ZAP_DELAY)
1230 zapTimer.start(update, 1);
1231 if (update >= 60000)
1232 eDebug("[EPGC] next update in %i min", update/60000);
1233 else if (update >= 1000)
1234 eDebug("[EPGC] next update in %i sec", update/1000);
1237 void eEPGCache::channel_data::abortEPG()
1239 for (int i=0; i < 3; ++i)
1241 seenSections[i].clear();
1242 calcedSections[i].clear();
1248 eDebug("[EPGC] abort caching events !!");
1249 if (isRunning & SCHEDULE)
1251 isRunning &= ~SCHEDULE;
1252 m_ScheduleReader->stop();
1255 if (isRunning & NOWNEXT)
1257 isRunning &= ~NOWNEXT;
1258 m_NowNextReader->stop();
1261 if (isRunning & SCHEDULE_OTHER)
1263 isRunning &= ~SCHEDULE_OTHER;
1264 m_ScheduleOtherReader->stop();
1265 m_ScheduleOtherConn=0;
1267 #ifdef ENABLE_MHW_EPG
1268 if (isRunning & MHW)
1271 m_MHWReader->stop();
1273 m_MHWReader2->stop();
1278 #ifdef ENABLE_PRIVATE_EPG
1279 if (m_PrivateReader)
1280 m_PrivateReader->stop();
1284 pthread_mutex_unlock(&channel_active);
1287 void eEPGCache::channel_data::readData( const __u8 *data)
1291 iDVBSectionReader *reader=NULL;
1295 reader=m_NowNextReader;
1300 reader=m_ScheduleReader;
1305 reader=m_ScheduleOtherReader;
1306 source=SCHEDULE_OTHER;
1310 eDebug("[EPGC] unknown table_id !!!");
1313 tidMap &seenSections = this->seenSections[map];
1314 tidMap &calcedSections = this->calcedSections[map];
1315 if ( state == 1 && calcedSections == seenSections || state > 1 )
1317 eDebugNoNewLine("[EPGC] ");
1322 eDebugNoNewLine("nownext");
1326 eDebugNoNewLine("schedule");
1328 case SCHEDULE_OTHER:
1329 m_ScheduleOtherConn=0;
1330 eDebugNoNewLine("schedule other");
1332 default: eDebugNoNewLine("unknown");break;
1334 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1337 isRunning &= ~source;
1343 eit_t *eit = (eit_t*) data;
1344 __u32 sectionNo = data[0] << 24;
1345 sectionNo |= data[3] << 16;
1346 sectionNo |= data[4] << 8;
1347 sectionNo |= eit->section_number;
1349 tidMap::iterator it =
1350 seenSections.find(sectionNo);
1352 if ( it == seenSections.end() )
1354 seenSections.insert(sectionNo);
1355 calcedSections.insert(sectionNo);
1356 __u32 tmpval = sectionNo & 0xFFFFFF00;
1357 __u8 incr = source == NOWNEXT ? 1 : 8;
1358 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1360 if ( i == eit->section_number )
1362 for (int x=i; x <= eit->segment_last_section_number; ++x)
1363 calcedSections.insert(tmpval|(x&0xFF));
1366 calcedSections.insert(tmpval|(i&0xFF));
1368 cache->sectionRead(data, source, this);
1373 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1374 // if t == -1 we search the current event...
1376 singleLock s(cache_lock);
1377 uniqueEPGKey key(handleGroup(service));
1379 // check if EPG for this service is ready...
1380 eventCache::iterator It = eventDB.find( key );
1381 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1384 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1385 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1386 It->second.second.upper_bound(t); // just >
1387 if ( i != It->second.second.end() )
1389 if ( direction < 0 || (direction == 0 && i->first > t) )
1391 timeMap::iterator x = i;
1393 if ( x != It->second.second.end() )
1395 time_t start_time = x->first;
1400 if (t > (start_time+x->second->getDuration()))
1415 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1417 singleLock s(cache_lock);
1418 const eventData *data=0;
1419 RESULT ret = lookupEventTime(service, t, data, direction);
1421 result = data->get();
1425 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1427 singleLock s(cache_lock);
1428 const eventData *data=0;
1429 RESULT ret = lookupEventTime(service, t, data, direction);
1431 result = new Event((uint8_t*)data->get());
1435 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1437 singleLock s(cache_lock);
1438 const eventData *data=0;
1439 RESULT ret = lookupEventTime(service, t, data, direction);
1442 Event ev((uint8_t*)data->get());
1443 result = new eServiceEvent();
1444 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1445 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1450 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1452 singleLock s(cache_lock);
1453 uniqueEPGKey key(handleGroup(service));
1455 eventCache::iterator It = eventDB.find( key );
1456 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1458 eventMap::iterator i( It->second.first.find( event_id ));
1459 if ( i != It->second.first.end() )
1467 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1473 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1475 singleLock s(cache_lock);
1476 const eventData *data=0;
1477 RESULT ret = lookupEventId(service, event_id, data);
1479 result = data->get();
1483 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1485 singleLock s(cache_lock);
1486 const eventData *data=0;
1487 RESULT ret = lookupEventId(service, event_id, data);
1489 result = new Event((uint8_t*)data->get());
1493 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1495 singleLock s(cache_lock);
1496 const eventData *data=0;
1497 RESULT ret = lookupEventId(service, event_id, data);
1500 Event ev((uint8_t*)data->get());
1501 result = new eServiceEvent();
1502 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1503 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1508 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1510 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1512 begin = eDVBLocalTimeHandler::getInstance()->nowTime();
1514 eventCache::iterator It = eventDB.find(ref);
1515 if ( It != eventDB.end() && It->second.second.size() )
1517 m_timemap_cursor = It->second.second.lower_bound(begin);
1518 if ( m_timemap_cursor != It->second.second.end() )
1520 if ( m_timemap_cursor->first != begin )
1522 timeMap::iterator x = m_timemap_cursor;
1524 if ( x != It->second.second.end() )
1526 time_t start_time = x->first;
1527 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1528 m_timemap_cursor = x;
1534 m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1536 m_timemap_end = It->second.second.end();
1538 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1546 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1548 if ( m_timemap_cursor != m_timemap_end )
1550 result = m_timemap_cursor++->second;
1556 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1558 if ( m_timemap_cursor != m_timemap_end )
1560 result = m_timemap_cursor++->second->get();
1566 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1568 if ( m_timemap_cursor != m_timemap_end )
1570 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1576 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1578 if ( m_timemap_cursor != m_timemap_end )
1580 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1581 result = new eServiceEvent();
1582 return result->parseFrom(&ev, currentQueryTsidOnid);
1587 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1591 while(pos < argcount)
1593 bool inc_refcount=false;
1594 switch(argstring[pos])
1596 case '0': // PyLong 0
1597 tmp = PyLong_FromLong(0);
1599 case 'I': // Event Id
1600 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1602 case 'B': // Event Begin Time
1603 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1605 case 'D': // Event Duration
1606 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1608 case 'T': // Event Title
1609 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1611 case 'S': // Event Short Description
1612 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1614 case 'E': // Event Extended Description
1615 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1617 case 'C': // Current Time
1619 inc_refcount = true;
1621 case 'R': // service reference string
1623 inc_refcount = true;
1625 case 'n': // short service name
1626 case 'N': // service name
1628 inc_refcount = true;
1633 inc_refcount = true;
1637 PyTuple_SET_ITEM(tuple, pos++, tmp);
1641 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1645 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1646 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1650 Py_DECREF(service_name);
1653 Py_DECREF(convertFuncArgs);
1654 Py_DECREF(dest_list);
1655 PyErr_SetString(PyExc_StandardError,
1656 "error in convertFunc execute");
1657 eDebug("error in convertFunc execute");
1660 PyList_Append(dest_list, result);
1665 ePyObject tuple = PyTuple_New(argcount);
1666 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1667 PyList_Append(dest_list, tuple);
1673 // here we get a python list
1674 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1677 // B = Event Begin Time
1678 // D = Event Duration
1680 // S = Event Short Description
1681 // E = Event Extended Description
1683 // R = Service Reference
1685 // n = Short Service Name
1686 // then for each service follows a tuple
1687 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1688 // the second is the type of query
1690 // -1 = event before given start_time
1691 // 0 = event intersects given start_time
1692 // +1 = event after given start_time
1694 // when type is eventid it is the event_id
1695 // when type is time then it is the start_time ( -1 for now_time )
1696 // the fourth is the end_time .. ( optional .. for query all events in time range)
1698 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1700 ePyObject convertFuncArgs;
1702 char *argstring=NULL;
1703 if (!PyList_Check(list))
1705 PyErr_SetString(PyExc_StandardError,
1711 int listSize=PyList_Size(list);
1714 PyErr_SetString(PyExc_StandardError,
1715 "not params given");
1716 eDebug("not params given");
1721 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1722 if (PyString_Check(argv))
1724 argstring = PyString_AS_STRING(argv);
1728 argstring = "I"; // just event id as default
1729 argcount = strlen(argstring);
1730 // eDebug("have %d args('%s')", argcount, argstring);
1734 if (!PyCallable_Check(convertFunc))
1736 PyErr_SetString(PyExc_StandardError,
1737 "convertFunc must be callable");
1738 eDebug("convertFunc is not callable");
1741 convertFuncArgs = PyTuple_New(argcount);
1744 ePyObject nowTime = strchr(argstring, 'C') ?
1745 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1748 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1751 ePyObject dest_list=PyList_New(0);
1752 while(listSize > listIt)
1754 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1755 if (PyTuple_Check(item))
1757 bool service_changed=false;
1762 int tupleSize=PyTuple_Size(item);
1765 while(tupleSize > tupleIt) // parse query args
1767 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1772 if (!PyString_Check(entry))
1774 eDebug("tuple entry 0 is no a string");
1781 type=PyInt_AsLong(entry);
1782 if (type < -1 || type > 2)
1784 eDebug("unknown type %d", type);
1789 event_id=stime=PyInt_AsLong(entry);
1792 minutes=PyInt_AsLong(entry);
1795 eDebug("unneeded extra argument");
1800 if (minutes && stime == -1)
1801 stime = eDVBLocalTimeHandler::getInstance()->nowTime();
1803 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1804 if (ref.type != eServiceReference::idDVB)
1806 eDebug("service reference for epg query is not valid");
1810 // redirect subservice querys to parent service
1811 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1812 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1814 eServiceCenterPtr service_center;
1815 if (!eServiceCenter::getPrivInstance(service_center))
1817 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1818 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1819 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1820 dvb_ref.setParentServiceID(eServiceID(0));
1822 service = PyString_FromString(dvb_ref.toString().c_str());
1823 service_changed = true;
1827 ePyObject service_name;
1828 if (must_get_service_name)
1830 ePtr<iStaticServiceInformation> sptr;
1831 eServiceCenterPtr service_center;
1832 eServiceCenter::getPrivInstance(service_center);
1835 service_center->info(ref, sptr);
1839 sptr->getName(ref, name);
1841 if (must_get_service_name == 1)
1844 // filter short name brakets
1845 while((pos = name.find("\xc2\x86")) != std::string::npos)
1847 while((pos = name.find("\xc2\x87")) != std::string::npos)
1851 name = buildShortName(name);
1854 service_name = PyString_FromString(name.c_str());
1858 service_name = PyString_FromString("<n/a>");
1863 if (!startTimeQuery(ref, stime, minutes))
1865 while ( m_timemap_cursor != m_timemap_end )
1867 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1869 evt.parseFrom(&ev, currentQueryTsidOnid);
1870 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1878 handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1888 lookupEventId(ref, event_id, ev);
1890 lookupEventTime(ref, stime, ev, type);
1893 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
1894 evt.parseFrom(ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
1897 if (handleEvent(ev ? &evt : 0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1900 if (service_changed)
1903 Py_DECREF(service_name);
1908 if (convertFuncArgs)
1909 Py_DECREF(convertFuncArgs);
1915 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
1919 while(pos < argcount)
1921 bool inc_refcount=false;
1922 switch(argstring[pos])
1924 case '0': // PyLong 0
1925 tmp = PyLong_FromLong(0);
1927 case 'I': // Event Id
1928 tmp = PyLong_FromLong(evData->getEventID());
1930 case 'B': // Event Begin Time
1932 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1934 tmp = PyLong_FromLong(evData->getStartTime());
1936 case 'D': // Event Duration
1938 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1940 tmp = PyLong_FromLong(evData->getDuration());
1942 case 'T': // Event Title
1943 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1945 case 'S': // Event Short Description
1946 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1948 case 'E': // Event Extended Description
1949 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1951 case 'R': // service reference string
1952 tmp = service_reference;
1953 inc_refcount = true;
1955 case 'n': // short service name
1956 case 'N': // service name
1958 inc_refcount = true;
1964 inc_refcount = true;
1968 PyTuple_SET_ITEM(tuple, pos++, tmp);
1972 // here we get a python tuple
1973 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1975 // B = Event Begin Time
1976 // D = Event Duration
1978 // S = Event Short Description
1979 // E = Event Extended Description
1980 // R = Service Reference
1982 // n = Short Service Name
1983 // the second tuple entry is the MAX matches value
1984 // the third tuple entry is the type of query
1985 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1986 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1987 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1988 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1989 // the fourth is the servicereference string
1990 // the fifth is the eventid
1991 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1992 // the fourth is the search text
1994 // 0 = case sensitive (CASE_CHECK)
1995 // 1 = case insensitive (NO_CASECHECK)
1997 PyObject *eEPGCache::search(ePyObject arg)
2003 const char *argstring=0;
2007 bool needServiceEvent=false;
2010 if (PyTuple_Check(arg))
2012 int tuplesize=PyTuple_Size(arg);
2015 ePyObject obj = PyTuple_GET_ITEM(arg,0);
2016 if (PyString_Check(obj))
2018 argcount = PyString_GET_SIZE(obj);
2019 argstring = PyString_AS_STRING(obj);
2020 for (int i=0; i < argcount; ++i)
2021 switch(argstring[i])
2026 needServiceEvent=true;
2033 PyErr_SetString(PyExc_StandardError,
2035 eDebug("tuple arg 0 is not a string");
2040 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2043 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2044 if (tuplesize > 4 && querytype == 0)
2046 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2047 if (PyString_Check(obj))
2049 refstr = PyString_AS_STRING(obj);
2050 eServiceReferenceDVB ref(refstr);
2053 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2054 singleLock s(cache_lock);
2055 const eventData *evData = 0;
2056 lookupEventId(ref, eventid, evData);
2059 __u8 *data = evData->EITdata;
2060 int tmp = evData->ByteSize-10;
2061 __u32 *p = (__u32*)(data+10);
2062 // search short and extended event descriptors
2066 descriptorMap::iterator it =
2067 eventData::descriptors.find(crc);
2068 if (it != eventData::descriptors.end())
2070 __u8 *descr_data = it->second.second;
2071 switch(descr_data[0])
2074 descr[++descridx]=crc;
2083 eDebug("event not found");
2087 PyErr_SetString(PyExc_StandardError,
2089 eDebug("tuple arg 4 is not a valid service reference string");
2095 PyErr_SetString(PyExc_StandardError,
2097 eDebug("tuple arg 4 is not a string");
2101 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2103 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2104 if (PyString_Check(obj))
2106 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2107 const char *str = PyString_AS_STRING(obj);
2108 int textlen = PyString_GET_SIZE(obj);
2110 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2112 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2113 singleLock s(cache_lock);
2114 for (descriptorMap::iterator it(eventData::descriptors.begin());
2115 it != eventData::descriptors.end() && descridx < 511; ++it)
2117 __u8 *data = it->second.second;
2118 if ( data[0] == 0x4D ) // short event descriptor
2120 int title_len = data[5];
2121 if ( querytype == 1 )
2123 if (title_len > textlen)
2125 else if (title_len < textlen)
2129 if ( !strncasecmp((const char*)data+6, str, title_len) )
2131 // std::string s((const char*)data+6, title_len);
2132 // eDebug("match1 %s %s", str, s.c_str() );
2133 descr[++descridx] = it->first;
2136 else if ( !strncmp((const char*)data+6, str, title_len) )
2138 // std::string s((const char*)data+6, title_len);
2139 // eDebug("match2 %s %s", str, s.c_str() );
2140 descr[++descridx] = it->first;
2146 while((title_len-idx) >= textlen)
2150 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2152 descr[++descridx] = it->first;
2153 // std::string s((const char*)data+6, title_len);
2154 // eDebug("match 3 %s %s", str, s.c_str() );
2157 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2159 descr[++descridx] = it->first;
2160 // std::string s((const char*)data+6, title_len);
2161 // eDebug("match 4 %s %s", str, s.c_str() );
2173 PyErr_SetString(PyExc_StandardError,
2175 eDebug("tuple arg 4 is not a string");
2181 PyErr_SetString(PyExc_StandardError,
2183 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2189 PyErr_SetString(PyExc_StandardError,
2191 eDebug("not enough args in tuple");
2197 PyErr_SetString(PyExc_StandardError,
2199 eDebug("arg 0 is not a tuple");
2205 int maxcount=maxmatches;
2206 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2207 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2208 // in this case we start searching with the base service
2209 bool first = ref.valid() ? true : false;
2210 singleLock s(cache_lock);
2211 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2212 while(cit != eventDB.end() && maxcount)
2214 if ( ref.valid() && !first && cit->first == ref )
2216 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2220 ePyObject service_name;
2221 ePyObject service_reference;
2222 timeMap &evmap = cit->second.second;
2224 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2226 int evid = evit->second->getEventID();
2227 if ( evid == eventid)
2229 __u8 *data = evit->second->EITdata;
2230 int tmp = evit->second->ByteSize-10;
2231 __u32 *p = (__u32*)(data+10);
2232 // check if any of our descriptor used by this event
2237 for ( int i=0; i <= descridx; ++i)
2239 if (descr[i] == crc32) // found...
2244 if ( (querytype == 0 && cnt == descridx) ||
2245 ((querytype == 1 || querytype == 2) && cnt != -1) )
2247 const uniqueEPGKey &service = cit->first;
2248 eServiceReference ref =
2249 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2252 // create servive event
2255 if (needServiceEvent)
2257 if (lookupEventId(ref, evid, ev))
2258 eDebug("event not found !!!!!!!!!!!");
2261 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2262 ptr.parseFrom(ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2265 // create service name
2268 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
2269 if (must_get_service_name)
2271 ePtr<iStaticServiceInformation> sptr;
2272 eServiceCenterPtr service_center;
2273 eServiceCenter::getPrivInstance(service_center);
2276 service_center->info(ref, sptr);
2280 sptr->getName(ref, name);
2282 if (must_get_service_name == 1)
2285 // filter short name brakets
2286 while((pos = name.find("\xc2\x86")) != std::string::npos)
2288 while((pos = name.find("\xc2\x87")) != std::string::npos)
2292 name = buildShortName(name);
2295 service_name = PyString_FromString(name.c_str());
2299 service_name = PyString_FromString("<n/a>");
2302 // create servicereference string
2303 if (!service_reference && strchr(argstring,'R'))
2304 service_reference = PyString_FromString(ref.toString().c_str());
2307 ret = PyList_New(0);
2309 ePyObject tuple = PyTuple_New(argcount);
2311 fillTuple2(tuple, argstring, argcount, evit->second, ev ? &ptr : 0, service_name, service_reference);
2312 PyList_Append(ret, tuple);
2319 Py_DECREF(service_name);
2320 if (service_reference)
2321 Py_DECREF(service_reference);
2324 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2326 cit=eventDB.begin();
2339 #ifdef ENABLE_PRIVATE_EPG
2340 #include <dvbsi++/descriptor_tag.h>
2341 #include <dvbsi++/unknown_descriptor.h>
2342 #include <dvbsi++/private_data_specifier_descriptor.h>
2344 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2346 ePtr<eTable<ProgramMapSection> > ptr;
2347 if (!pmthandler->getPMT(ptr) && ptr)
2349 std::vector<ProgramMapSection*>::const_iterator i;
2350 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2352 const ProgramMapSection &pmt = **i;
2354 ElementaryStreamInfoConstIterator es;
2355 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2358 switch ((*es)->getType())
2360 case 0x05: // private
2361 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2362 desc != (*es)->getDescriptors()->end(); ++desc)
2364 switch ((*desc)->getTag())
2366 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2367 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2372 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2373 int descr_len = descr->getLength();
2376 uint8_t data[descr_len+2];
2377 descr->writeToBuffer(data);
2378 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2392 eServiceReferenceDVB ref;
2393 if (!pmthandler->getServiceReference(ref))
2395 int pid = (*es)->getPid();
2396 messages.send(Message(Message::got_private_pid, ref, pid));
2404 eDebug("PMTready but no pmt!!");
2411 date_time( const date_time &a )
2413 memcpy(data, a.data, 5);
2416 date_time( const __u8 data[5])
2418 memcpy(this->data, data, 5);
2419 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2424 const __u8& operator[](int pos) const
2430 struct less_datetime
2432 bool operator()( const date_time &a, const date_time &b ) const
2434 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2438 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2440 contentMap &content_time_table = content_time_tables[current_service];
2441 singleLock s(cache_lock);
2442 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2443 eventMap &evMap = eventDB[current_service].first;
2444 timeMap &tmMap = eventDB[current_service].second;
2446 int content_id = data[ptr++] << 24;
2447 content_id |= data[ptr++] << 16;
2448 content_id |= data[ptr++] << 8;
2449 content_id |= data[ptr++];
2451 contentTimeMap &time_event_map =
2452 content_time_table[content_id];
2453 for ( contentTimeMap::iterator it( time_event_map.begin() );
2454 it != time_event_map.end(); ++it )
2456 eventMap::iterator evIt( evMap.find(it->second.second) );
2457 if ( evIt != evMap.end() )
2459 delete evIt->second;
2462 tmMap.erase(it->second.first);
2464 time_event_map.clear();
2467 memcpy(duration, data+ptr, 3);
2470 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2472 const __u8 *descriptors[65];
2473 const __u8 **pdescr = descriptors;
2475 int descriptors_length = (data[ptr++]&0x0F) << 8;
2476 descriptors_length |= data[ptr++];
2477 while ( descriptors_length > 1 )
2479 int descr_type = data[ptr];
2480 int descr_len = data[ptr+1];
2481 descriptors_length -= 2;
2482 if (descriptors_length >= descr_len)
2484 descriptors_length -= descr_len;
2485 if ( descr_type == 0xf2 && descr_len > 5)
2488 int tsid = data[ptr++] << 8;
2489 tsid |= data[ptr++];
2490 int onid = data[ptr++] << 8;
2491 onid |= data[ptr++];
2492 int sid = data[ptr++] << 8;
2495 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2498 switch( (tsid << 16) | sid )
2500 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2501 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2502 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2503 case 0x0300f5: sid = 0xdc; break;
2504 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2505 case 0x1100d3: sid = 0xe3; break;
2506 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2509 ////////////////////////////////////////////
2511 uniqueEPGKey service( sid, onid, tsid );
2513 while( descr_len > 2 )
2516 datetime[0] = data[ptr++];
2517 datetime[1] = data[ptr++];
2518 int tmp_len = data[ptr++];
2520 if (descr_len >= tmp_len)
2522 descr_len -= tmp_len;
2523 while( tmp_len > 2 )
2525 memcpy(datetime+2, data+ptr, 3);
2528 start_times[datetime].push_back(service);
2541 ASSERT(pdescr <= &descriptors[65])
2543 eit_event_struct *ev_struct = (eit_event_struct*) event;
2544 ev_struct->running_status = 0;
2545 ev_struct->free_CA_mode = 1;
2546 memcpy(event+7, duration, 3);
2548 const __u8 **d=descriptors;
2549 while ( d < pdescr )
2551 memcpy(event+ptr, *d, ((*d)[1])+2);
2555 ASSERT(ptr <= 4098);
2556 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2558 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2559 if ( (it->first.tm + duration_sec) < now )
2561 memcpy(event+2, it->first.data, 5);
2564 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2566 event[bptr++] = 0x4A;
2567 __u8 *len = event+(bptr++);
2568 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2569 event[bptr++] = (i->tsid & 0xFF);
2570 event[bptr++] = (i->onid & 0xFF00) >> 8;
2571 event[bptr++] = (i->onid & 0xFF);
2572 event[bptr++] = (i->sid & 0xFF00) >> 8;
2573 event[bptr++] = (i->sid & 0xFF);
2574 event[bptr++] = 0xB0;
2575 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2576 *len = ((event+bptr) - len)-1;
2578 int llen = bptr - 12;
2579 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2580 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2582 time_t stime = it->first.tm;
2583 while( tmMap.find(stime) != tmMap.end() )
2585 event[6] += (stime - it->first.tm);
2587 while( evMap.find(event_id) != evMap.end() )
2589 event[0] = (event_id & 0xFF00) >> 8;
2590 event[1] = (event_id & 0xFF);
2591 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2592 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2593 evMap[event_id] = d;
2595 ASSERT(bptr <= 4098);
2599 void eEPGCache::channel_data::startPrivateReader()
2601 eDVBSectionFilterMask mask;
2602 memset(&mask, 0, sizeof(mask));
2603 mask.pid = m_PrivatePid;
2604 mask.flags = eDVBSectionFilterMask::rfCRC;
2605 mask.data[0] = 0xA0;
2606 mask.mask[0] = 0xFF;
2607 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2608 if (m_PrevVersion != -1)
2610 mask.data[3] = m_PrevVersion << 1;
2611 mask.mask[3] = 0x3E;
2612 mask.mode[3] = 0x3E;
2614 seenPrivateSections.clear();
2616 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2617 m_PrivateReader->start(mask);
2620 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2622 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2624 cache->privateSectionRead(m_PrivateService, data);
2625 seenPrivateSections.insert(data[6]);
2627 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2629 eDebug("[EPGC] private finished");
2630 eDVBChannelID chid = channel->getChannelID();
2631 int tmp = chid.original_network_id.get();
2632 tmp |= 0x80000000; // we use highest bit as private epg indicator
2633 chid.original_network_id = tmp;
2634 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2635 m_PrevVersion = (data[5] & 0x3E) >> 1;
2636 startPrivateReader();
2640 #endif // ENABLE_PRIVATE_EPG
2642 #ifdef ENABLE_MHW_EPG
2643 void eEPGCache::channel_data::cleanup()
2648 m_program_ids.clear();
2651 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2653 // Names in mhw structs are not strings as they are not '\0' terminated.
2654 // This function converts the mhw name into a string.
2655 // Constraint: "length of out" = "length of in" + 1.
2657 for ( i=0; i < len_in; i++ )
2661 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2668 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2671 return_time[0] = toBCD( hours );
2672 return_time[1] = toBCD( minutes );
2676 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2678 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2681 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2682 // For date plus time of day
2684 // Remove offset in mhw time.
2685 __u8 local_hours = hours;
2688 else if ( hours >= 8 )
2691 // As far as we know all mhw time data is sent in central Europe time zone.
2692 // So, temporarily set timezone to western europe
2693 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2695 char *old_tz = getenv( "TZ" );
2696 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2700 localtime_r(&dt, &localnow);
2704 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2706 if (local_hours <= 5)
2709 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2710 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2713 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2715 if ( old_tz == NULL )
2721 // Calculate MJD according to annex in ETSI EN 300 468
2723 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2725 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2726 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2728 return_time[0] = (mjd & 0xFF00)>>8;
2729 return_time[1] = mjd & 0xFF;
2731 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2734 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2735 // data is borrowed from calling proc to save memory space.
2739 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2740 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2741 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2743 eit_t *packet = (eit_t *) data;
2744 packet->table_id = 0x50;
2745 packet->section_syntax_indicator = 1;
2747 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2748 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2749 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2750 packet->current_next_indicator = 0;
2751 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2752 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2753 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2754 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2755 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2756 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2757 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2758 packet->segment_last_table_id = 0x50;
2760 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2761 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2762 int prog_title_length = prog_title.length();
2764 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2765 prog_title_length + 1;
2767 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2768 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2769 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2773 u_char *data = (u_char*) event_data;
2774 data[2] = itTitle->second.mhw2_mjd_hi;
2775 data[3] = itTitle->second.mhw2_mjd_lo;
2776 data[4] = itTitle->second.mhw2_hours;
2777 data[5] = itTitle->second.mhw2_minutes;
2778 data[6] = itTitle->second.mhw2_seconds;
2779 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2783 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2784 (u_char *) event_data + 2 );
2785 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2788 event_data->running_status = 0;
2789 event_data->free_CA_mode = 0;
2790 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2792 eit_short_event_descriptor_struct *short_event_descriptor =
2793 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2794 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2795 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2796 prog_title_length - 1;
2797 short_event_descriptor->language_code_1 = 'e';
2798 short_event_descriptor->language_code_2 = 'n';
2799 short_event_descriptor->language_code_3 = 'g';
2800 short_event_descriptor->event_name_length = prog_title_length;
2801 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2802 memcpy(event_name, prog_title.c_str(), prog_title_length);
2805 event_name[prog_title_length] = 0;
2807 if ( sumText.length() > 0 )
2808 // There is summary info
2810 unsigned int sum_length = sumText.length();
2811 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2812 // Store summary in short event descriptor
2814 // Increase all relevant lengths
2815 event_name[prog_title_length] = sum_length;
2816 short_event_descriptor->descriptor_length += sum_length;
2817 packet_length += sum_length;
2818 descr_ll += sum_length;
2819 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2822 // Store summary in extended event descriptors
2824 int remaining_sum_length = sumText.length();
2825 int nbr_descr = int(remaining_sum_length/247) + 1;
2826 for ( int i=0; i < nbr_descr; i++)
2827 // Loop once per extended event descriptor
2829 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2830 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2831 remaining_sum_length -= sum_length;
2832 packet_length += 8 + sum_length;
2833 descr_ll += 8 + sum_length;
2835 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2836 ext_event_descriptor->descriptor_length = sum_length + 6;
2837 ext_event_descriptor->descriptor_number = i;
2838 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2839 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2840 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2841 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2842 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2844 the_text[-1] = sum_length;
2845 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2852 // Add content descriptor
2853 u_char *descriptor = (u_char *) data + packet_length;
2858 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2859 if ( content_descr.find( "FILM" ) != std::string::npos )
2861 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2864 descriptor[0] = 0x54;
2866 descriptor[2] = content_id;
2870 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2871 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2873 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2874 packet->section_length_lo = (packet_length - 3)&0xff;
2876 // Feed the data to eEPGCache::sectionRead()
2877 cache->sectionRead( data, MHW, this );
2880 void eEPGCache::channel_data::startTimeout(int msec)
2882 m_MHWTimeoutTimer.start(msec,true);
2883 m_MHWTimeoutet=false;
2886 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2888 m_MHWFilterMask.pid = pid;
2889 m_MHWFilterMask.data[0] = tid;
2890 m_MHWReader->start(m_MHWFilterMask);
2891 // eDebug("start 0x%02x 0x%02x", pid, tid);
2894 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2896 m_MHWFilterMask2.pid = pid;
2897 m_MHWFilterMask2.data[0] = tid;
2900 m_MHWFilterMask2.data[1] = ext;
2901 m_MHWFilterMask2.mask[1] = 0xFF;
2902 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2906 m_MHWFilterMask2.data[1] = 0;
2907 m_MHWFilterMask2.mask[1] = 0;
2908 // eDebug("start 0x%02x 0x%02x", pid, tid);
2910 m_MHWReader2->start(m_MHWFilterMask2);
2913 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2916 m_MHWReader2->stop();
2918 if ( state > 1 || // aborted
2919 // have si data.. so we dont read mhw data
2920 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2922 eDebug("[EPGC] mhw aborted %d", state);
2924 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2927 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2928 int record_size = sizeof( mhw_channel_name_t );
2929 int nbr_records = int (len/record_size);
2931 m_channels.resize(nbr_records);
2932 for ( int i = 0; i < nbr_records; i++ )
2934 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2935 m_channels[i]=*channel;
2939 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2941 // Channels table has been read, start reading the themes table.
2942 startMHWReader(0xD3, 0x92);
2945 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2948 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2949 int record_size = sizeof( mhw_theme_name_t );
2950 int nbr_records = int (len/record_size);
2952 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2955 for ( int i = 0; i < nbr_records; i++ )
2957 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2958 if ( i >= next_idx )
2962 next_idx = (__u8) *(data + 3 + idx_ptr);
2968 m_themes[idx+sub_idx] = *theme;
2970 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2971 // Themes table has been read, start reading the titles table.
2972 startMHWReader(0xD2, 0x90);
2976 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2979 mhw_title_t *title = (mhw_title_t*) data;
2981 if ( title->channel_id == 0xFF ) // Separator
2982 return; // Continue reading of the current table.
2985 // Create unique key per title
2986 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2987 (title->ms.minutes);
2988 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2989 ((title->program_id_ml)<<8)|(title->program_id_lo);
2991 if ( m_titles.find( title_id ) == m_titles.end() )
2994 title->mhw2_mjd_hi = 0;
2995 title->mhw2_mjd_lo = 0;
2996 title->mhw2_duration_hi = 0;
2997 title->mhw2_duration_lo = 0;
2998 m_titles[ title_id ] = *title;
2999 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3000 // program_ids will be used to gather summaries.
3001 m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3002 return; // Continue reading of the current table.
3004 else if (!checkTimeout())
3007 if ( !m_program_ids.empty())
3009 // Titles table has been read, there are summaries to read.
3010 // Start reading summaries, store corresponding titles on the fly.
3011 startMHWReader(0xD3, 0x90);
3012 eDebug("[EPGC] mhw %d titles(%d with summary) found",
3014 m_program_ids.size());
3019 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3022 mhw_summary_t *summary = (mhw_summary_t*) data;
3024 // Create unique key per record
3025 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3026 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3027 int len = ((data[1]&0xf)<<8) + data[2];
3029 // ugly workaround to convert const __u8* to char*
3031 memcpy(&tmp, &data, sizeof(void*));
3032 tmp[len+3] = 0; // Terminate as a string.
3034 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3035 if ( itProgid == m_program_ids.end() )
3036 { /* This part is to prevent to looping forever if some summaries are not received yet.
3037 There is a timeout of 4 sec. after the last successfully read summary. */
3038 if (!m_program_ids.empty() && !checkTimeout())
3039 return; // Continue reading of the current table.
3043 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3046 while((pos = the_text.find("\r\n")) != std::string::npos)
3047 the_text.replace(pos, 2, " ");
3049 // Find corresponding title, store title and summary in epgcache.
3050 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3051 if ( itTitle != m_titles.end() )
3054 storeTitle( itTitle, the_text, data );
3055 m_titles.erase( itTitle );
3057 m_program_ids.erase( itProgid );
3058 if ( !m_program_ids.empty() )
3059 return; // Continue reading of the current table.
3062 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3063 eDVBLocalTimeHandler::getInstance()->nowTime(),
3064 m_program_ids.size());
3065 // Summaries have been read, titles that have summaries have been stored.
3066 // Now store titles that do not have summaries.
3067 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3068 storeTitle( itTitle, "", data );
3072 m_MHWReader->stop();
3077 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3079 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3082 m_MHWReader->stop();
3084 if ( state > 1 || // aborted
3085 // have si data.. so we dont read mhw data
3086 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
3088 eDebug("[EPGC] mhw2 aborted %d", state);
3090 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3093 int num_channels = data[119];
3094 m_channels.resize(num_channels);
3097 int ptr = 120 + 8 * num_channels;
3100 for( int chid = 0; chid < num_channels; ++chid )
3102 ptr += ( data[ptr] & 0x0f ) + 1;
3112 // data seems consistent...
3113 const __u8 *tmp = data+120;
3114 for (int i=0; i < num_channels; ++i)
3116 mhw_channel_name_t channel;
3117 channel.network_id_hi = *(tmp++);
3118 channel.network_id_lo = *(tmp++);
3119 channel.transport_stream_id_hi = *(tmp++);
3120 channel.transport_stream_id_lo = *(tmp++);
3121 channel.channel_id_hi = *(tmp++);
3122 channel.channel_id_lo = *(tmp++);
3123 m_channels[i]=channel;
3126 for (int i=0; i < num_channels; ++i)
3128 mhw_channel_name_t &channel = m_channels[i];
3129 int channel_name_len=*(tmp++)&0x0f;
3131 for (; x < channel_name_len; ++x)
3132 channel.name[x]=*(tmp++);
3133 channel.name[x+1]=0;
3136 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3138 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3141 eDebug("[EPGC] mhw2 themes nyi");
3143 else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3148 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3150 if(data[dataLen-1] != 0xff)
3152 while( pos < dataLen )
3161 if( data[pos] > 0xc0 )
3163 pos += ( data[pos] - 0xc0 );
3167 if( data[pos] == 0xff )
3183 // data seems consistent...
3188 title.channel_id = data[pos]+1;
3189 title.program_id_ml = data[pos+1];
3190 title.program_id_lo = data[pos+2];
3191 title.mhw2_mjd_hi = data[pos+3];
3192 title.mhw2_mjd_lo = data[pos+4];
3193 title.mhw2_hours = data[pos+5];
3194 title.mhw2_minutes = data[pos+6];
3195 title.mhw2_seconds = data[pos+7];
3196 int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3197 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3198 title.mhw2_duration_lo = duration&0xFF;
3199 __u8 slen = data[pos+10] & 0x3f;
3200 __u8 *dest = ((__u8*)title.title)-4;
3201 memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3202 memset(dest+slen, 0, 33-slen);
3204 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3205 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3207 // Create unique key per title
3208 __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3212 std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3213 if ( it == m_titles.end() )
3216 m_titles[ title_id ] = title;
3217 if (summary_id != 0xFFFF)
3220 std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3221 while (it != m_program_ids.end() && it->first == summary_id)
3223 if (it->second == title_id) {
3230 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3235 if ( !checkTimeout() )
3236 continue; // Continue reading of the current table.
3244 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3245 if (!m_program_ids.empty())
3247 // Titles table has been read, there are summaries to read.
3248 // Start reading summaries, store corresponding titles on the fly.
3249 startMHWReader2(0x236, 0x96);
3250 startTimeout(15000);
3257 else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3260 if (!checkTimeout())
3262 int len, loop, pos, lenline;
3271 loop = data[pos] & 0x0f;
3276 for( ; loop > 0; --loop )
3278 if( dataLen > (pos+len) )
3280 lenline = data[pos+len];
3290 return; // continue reading
3293 // data seems consistent...
3294 __u32 summary_id = (data[3]<<8)|data[4];
3296 // ugly workaround to convert const __u8* to char*
3298 memcpy(&tmp, &data, sizeof(void*));
3303 loop = tmp[pos] & 0x0f;
3305 for( ; loop > 0; loop -- )
3307 lenline = tmp[pos+len];
3316 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3317 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3318 { /* This part is to prevent to looping forever if some summaries are not received yet.
3319 There is a timeout of 4 sec. after the last successfully read summary. */
3320 if ( !m_program_ids.empty() )
3321 return; // Continue reading of the current table.
3325 startTimeout(15000);
3326 std::string the_text = (char *) (data + pos + 1);
3328 while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3330 // Find corresponding title, store title and summary in epgcache.
3331 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3332 if ( itTitle != m_titles.end() )
3334 storeTitle( itTitle, the_text, data );
3335 m_titles.erase( itTitle );
3337 m_program_ids.erase( itProgId++ );
3339 if ( !m_program_ids.empty() )
3340 return; // Continue reading of the current table.
3344 return; // continue reading
3347 if (isRunning & eEPGCache::MHW)
3349 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3351 // Channels table has been read, start reading the themes table.
3352 startMHWReader2(0x231, 0xC8, 1);
3355 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3357 // Themes table has been read, start reading the titles table.
3358 startMHWReader2(0x234, 0xe6);
3363 // Summaries have been read, titles that have summaries have been stored.
3364 // Now store titles that do not have summaries.
3365 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3366 storeTitle( itTitle, "", data );
3367 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3368 eDVBLocalTimeHandler::getInstance()->nowTime(),
3369 m_program_ids.size());
3376 m_MHWReader2->stop();