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 bool eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
378 timeMap::iterator tmp = tm_it;
379 while ((tmp->first+tmp->second->getDuration()-300) > TM)
382 #ifdef ENABLE_PRIVATE_EPG
383 && tmp->second->type != PRIVATE
386 && tmp->second->type != MHW
390 __u16 event_id = tmp->second->getEventID();
391 servicemap.first.erase(event_id);
393 Event evt((uint8_t*)tmp->second->get());
395 event.parseFrom(&evt, service.sid<<16|service.onid);
396 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
397 service.sid, event_id,
398 event.getBeginTimeString().c_str(),
399 event.getEventName().c_str(),
400 event.getExtendedDescription().c_str());
403 if (tmp == servicemap.second.begin())
405 servicemap.second.erase(tmp);
409 servicemap.second.erase(tmp--);
414 if (tmp == servicemap.second.begin())
421 while(tmp->first < (TM+duration-300))
423 if (tmp->first != TM && tmp->second->type != PRIVATE)
425 __u16 event_id = tmp->second->getEventID();
426 servicemap.first.erase(event_id);
428 Event evt((uint8_t*)tmp->second->get());
430 event.parseFrom(&evt, service.sid<<16|service.onid);
431 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
432 service.sid, event_id,
433 event.getBeginTimeString().c_str(),
434 event.getEventName().c_str(),
435 event.getExtendedDescription().c_str());
438 servicemap.second.erase(tmp++);
443 if (tmp == servicemap.second.end())
449 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
451 eit_t *eit = (eit_t*) data;
453 int len=HILO(eit->section_length)-1;//+3-4;
458 // This fixed the EPG on the Multichoice irdeto systems
459 // the EIT packet is non-compliant.. their EIT packet stinks
460 if ( data[ptr-1] < 0x40 )
463 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
464 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
468 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);
469 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
471 if ( TM != 3599 && TM > -1)
472 channel->haveData |= source;
474 singleLock s(cache_lock);
475 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
476 // oder eine durch [] erzeugte
477 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
478 eventMap::iterator prevEventIt = servicemap.first.end();
479 timeMap::iterator prevTimeIt = servicemap.second.end();
483 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
485 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
487 eit_event->start_time_1,
488 eit_event->start_time_2,
489 eit_event->start_time_3,
490 eit_event->start_time_4,
491 eit_event->start_time_5);
496 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
499 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
501 __u16 event_id = HILO(eit_event->event_id);
502 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
505 int ev_erase_count = 0;
506 int tm_erase_count = 0;
508 // search in eventmap
509 eventMap::iterator ev_it =
510 servicemap.first.find(event_id);
512 // entry with this event_id is already exist ?
513 if ( ev_it != servicemap.first.end() )
515 if ( source > ev_it->second->type ) // update needed ?
516 goto next; // when not.. then skip this entry
518 // search this event in timemap
519 timeMap::iterator tm_it_tmp =
520 servicemap.second.find(ev_it->second->getStartTime());
522 if ( tm_it_tmp != servicemap.second.end() )
524 if ( tm_it_tmp->first == TM ) // just update eventdata
527 eventData *tmp = ev_it->second;
528 ev_it->second = tm_it_tmp->second =
529 new eventData(eit_event, eit_event_size, source);
530 if (FixOverlapping(servicemap, TM, duration, tm_it_tmp, service))
532 prevEventIt = servicemap.first.end();
533 prevTimeIt = servicemap.second.end();
538 else // event has new event begin time
541 // delete the found record from timemap
542 servicemap.second.erase(tm_it_tmp);
543 prevTimeIt=servicemap.second.end();
548 // search in timemap, for check of a case if new time has coincided with time of other event
549 // or event was is not found in eventmap
550 timeMap::iterator tm_it =
551 servicemap.second.find(TM);
553 if ( tm_it != servicemap.second.end() )
555 // event with same start time but another event_id...
556 if ( source > tm_it->second->type &&
557 ev_it == servicemap.first.end() )
558 goto next; // when not.. then skip this entry
560 // search this time in eventmap
561 eventMap::iterator ev_it_tmp =
562 servicemap.first.find(tm_it->second->getEventID());
564 if ( ev_it_tmp != servicemap.first.end() )
567 // delete the found record from eventmap
568 servicemap.first.erase(ev_it_tmp);
569 prevEventIt=servicemap.first.end();
572 evt = new eventData(eit_event, eit_event_size, source);
574 bool consistencyCheck=true;
576 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
579 delete ev_it->second;
580 delete tm_it->second;
584 else if (ev_erase_count == 0 && tm_erase_count > 0)
587 delete ev_it->second;
588 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
591 else if (ev_erase_count > 0 && tm_erase_count == 0)
594 delete tm_it->second;
595 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
598 else // added new eventData
601 consistencyCheck=false;
603 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
604 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
608 if ( consistencyCheck )
610 if ( tm_it->second != evt || ev_it->second != evt )
611 eFatal("tm_it->second != ev_it->second");
612 else if ( tm_it->second->getStartTime() != tm_it->first )
613 eFatal("event start_time(%d) non equal timemap key(%d)",
614 tm_it->second->getStartTime(), tm_it->first );
615 else if ( tm_it->first != TM )
616 eFatal("timemap key(%d) non equal TM(%d)",
618 else if ( ev_it->second->getEventID() != ev_it->first )
619 eFatal("event_id (%d) non equal event_map key(%d)",
620 ev_it->second->getEventID(), ev_it->first);
621 else if ( ev_it->first != event_id )
622 eFatal("eventmap key(%d) non equal event_id(%d)",
623 ev_it->first, event_id );
626 if (FixOverlapping(servicemap, TM, duration, tm_it, service))
628 prevEventIt = servicemap.first.end();
629 prevTimeIt = servicemap.second.end();
634 if ( servicemap.first.size() != servicemap.second.size() )
636 FILE *f = fopen("/hdd/event_map.txt", "w+");
638 for (eventMap::iterator it(servicemap.first.begin())
639 ; it != servicemap.first.end(); ++it )
640 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
641 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
643 f = fopen("/hdd/time_map.txt", "w+");
645 for (timeMap::iterator it(servicemap.second.begin())
646 ; it != servicemap.second.end(); ++it )
647 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
648 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
651 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
652 service.sid, service.tsid, service.onid,
653 servicemap.first.size(), servicemap.second.size() );
656 ptr += eit_event_size;
657 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
661 void eEPGCache::flushEPG(const uniqueEPGKey & s)
663 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
664 singleLock l(cache_lock);
665 if (s) // clear only this service
667 eventCache::iterator it = eventDB.find(s);
668 if ( it != eventDB.end() )
670 eventMap &evMap = it->second.first;
671 timeMap &tmMap = it->second.second;
673 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
678 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
679 #ifdef ENABLE_PRIVATE_EPG
680 contentMaps::iterator it =
681 content_time_tables.find(s);
682 if ( it != content_time_tables.end() )
685 content_time_tables.erase(it);
690 else // clear complete EPG Cache
692 for (eventCache::iterator it(eventDB.begin());
693 it != eventDB.end(); ++it)
695 eventMap &evMap = it->second.first;
696 timeMap &tmMap = it->second.second;
697 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
703 #ifdef ENABLE_PRIVATE_EPG
704 content_time_tables.clear();
706 channelLastUpdated.clear();
707 singleLock m(channel_map_lock);
708 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
709 it->second->startEPG();
711 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
714 void eEPGCache::cleanLoop()
716 singleLock s(cache_lock);
717 if (!eventDB.empty())
719 eDebug("[EPGC] start cleanloop");
721 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
723 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
725 bool updated = false;
726 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
728 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
730 // remove entry from eventMap
731 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
732 if ( b != DBIt->second.first.end() )
734 // release Heap Memory for this entry (new ....)
735 // eDebug("[EPGC] delete old event (evmap)");
736 DBIt->second.first.erase(b);
739 // remove entry from timeMap
740 // eDebug("[EPGC] release heap mem");
742 DBIt->second.second.erase(It++);
743 // eDebug("[EPGC] delete old event (timeMap)");
749 #ifdef ENABLE_PRIVATE_EPG
752 contentMaps::iterator x =
753 content_time_tables.find( DBIt->first );
754 if ( x != content_time_tables.end() )
756 timeMap &tmMap = DBIt->second.second;
757 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
759 for ( contentTimeMap::iterator it(i->second.begin());
760 it != i->second.end(); )
762 if ( tmMap.find(it->second.first) == tmMap.end() )
763 i->second.erase(it++);
767 if ( i->second.size() )
770 x->second.erase(i++);
776 eDebug("[EPGC] stop cleanloop");
777 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
779 cleanTimer.start(CLEAN_INTERVAL,true);
782 eEPGCache::~eEPGCache()
784 messages.send(Message::quit);
785 kill(); // waiting for thread shutdown
786 singleLock s(cache_lock);
787 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
788 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
792 void eEPGCache::gotMessage( const Message &msg )
797 flushEPG(msg.service);
799 case Message::startChannel:
801 singleLock s(channel_map_lock);
802 channelMapIterator channel =
803 m_knownChannels.find(msg.channel);
804 if ( channel != m_knownChannels.end() )
805 channel->second->startChannel();
808 case Message::leaveChannel:
810 singleLock s(channel_map_lock);
811 channelMapIterator channel =
812 m_knownChannels.find(msg.channel);
813 if ( channel != m_knownChannels.end() )
814 channel->second->abortEPG();
820 #ifdef ENABLE_PRIVATE_EPG
821 case Message::got_private_pid:
823 singleLock s(channel_map_lock);
824 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
826 eDVBChannel *channel = (eDVBChannel*) it->first;
827 channel_data *data = it->second;
828 eDVBChannelID chid = channel->getChannelID();
829 if ( chid.transport_stream_id.get() == msg.service.tsid &&
830 chid.original_network_id.get() == msg.service.onid &&
831 data->m_PrivatePid == -1 )
833 data->m_PrevVersion = -1;
834 data->m_PrivatePid = msg.pid;
835 data->m_PrivateService = msg.service;
836 int onid = chid.original_network_id.get();
837 onid |= 0x80000000; // we use highest bit as private epg indicator
838 chid.original_network_id = onid;
839 updateMap::iterator It = channelLastUpdated.find( chid );
840 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
841 if (update < ZAP_DELAY)
843 data->startPrivateTimer.start(update, 1);
845 eDebug("[EPGC] next private update in %i min", update/60000);
846 else if (update >= 1000)
847 eDebug("[EPGC] next private update in %i sec", update/1000);
854 case Message::timeChanged:
858 eDebug("unhandled EPGCache Message!!");
863 void eEPGCache::thread()
873 void eEPGCache::load()
875 FILE *f = fopen("/hdd/epg.dat", "r");
878 unlink("/hdd/epg.dat");
882 unsigned char md5_saved[16];
883 unsigned char md5[16];
886 if (!md5_file("/hdd/epg.dat", 1, md5))
888 FILE *f = fopen("/hdd/epg.dat.md5", "r");
891 fread( md5_saved, 16, 1, f);
893 if ( !memcmp(md5_saved, md5, 16) )
900 unsigned int magic=0;
901 fread( &magic, sizeof(int), 1, f);
902 if (magic != 0x98765432)
904 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
909 fread( text1, 13, 1, f);
910 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
912 singleLock s(cache_lock);
913 fread( &size, sizeof(int), 1, f);
920 fread( &key, sizeof(uniqueEPGKey), 1, f);
921 fread( &size, sizeof(int), 1, f);
927 fread( &type, sizeof(__u8), 1, f);
928 fread( &len, sizeof(__u8), 1, f);
929 event = new eventData(0, len, type);
930 event->EITdata = new __u8[len];
931 eventData::CacheSize+=len;
932 fread( event->EITdata, len, 1, f);
933 evMap[ event->getEventID() ]=event;
934 tmMap[ event->getStartTime() ]=event;
937 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
940 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
941 #ifdef ENABLE_PRIVATE_EPG
943 fread( text2, 11, 1, f);
944 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
947 fread( &size, sizeof(int), 1, f);
952 fread( &key, sizeof(uniqueEPGKey), 1, f);
953 eventMap &evMap=eventDB[key].first;
954 fread( &size, sizeof(int), 1, f);
959 fread( &content_id, sizeof(int), 1, f);
960 fread( &size, sizeof(int), 1, f);
965 fread( &time1, sizeof(time_t), 1, f);
966 fread( &time2, sizeof(time_t), 1, f);
967 fread( &event_id, sizeof(__u16), 1, f);
968 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
969 eventMap::iterator it =
970 evMap.find(event_id);
971 if (it != evMap.end())
972 it->second->type = PRIVATE;
977 #endif // ENABLE_PRIVATE_EPG
980 eDebug("[EPGC] don't read old epg database");
986 void eEPGCache::save()
990 if (statfs("/hdd", &s)<0)
998 // prevent writes to builtin flash
999 if ( tmp < 1024*1024*50 ) // storage size < 50MB
1002 // check for enough free space on storage
1005 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
1008 FILE *f = fopen("/hdd/epg.dat", "w");
1012 unsigned int magic = 0x98765432;
1013 fwrite( &magic, sizeof(int), 1, f);
1014 const char *text = "ENIGMA_EPG_V7";
1015 fwrite( text, 13, 1, f );
1016 int size = eventDB.size();
1017 fwrite( &size, sizeof(int), 1, f );
1018 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1020 timeMap &timemap = service_it->second.second;
1021 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1022 size = timemap.size();
1023 fwrite( &size, sizeof(int), 1, f);
1024 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1026 __u8 len = time_it->second->ByteSize;
1027 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1028 fwrite( &len, sizeof(__u8), 1, f);
1029 fwrite( time_it->second->EITdata, len, 1, f);
1033 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
1035 #ifdef ENABLE_PRIVATE_EPG
1036 const char* text3 = "PRIVATE_EPG";
1037 fwrite( text3, 11, 1, f );
1038 size = content_time_tables.size();
1039 fwrite( &size, sizeof(int), 1, f);
1040 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1042 contentMap &content_time_table = a->second;
1043 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1044 int size = content_time_table.size();
1045 fwrite( &size, sizeof(int), 1, f);
1046 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1048 int size = i->second.size();
1049 fwrite( &i->first, sizeof(int), 1, f);
1050 fwrite( &size, sizeof(int), 1, f);
1051 for ( contentTimeMap::iterator it(i->second.begin());
1052 it != i->second.end(); ++it )
1054 fwrite( &it->first, sizeof(time_t), 1, f);
1055 fwrite( &it->second.first, sizeof(time_t), 1, f);
1056 fwrite( &it->second.second, sizeof(__u16), 1, f);
1063 unsigned char md5[16];
1064 if (!md5_file("/hdd/epg.dat", 1, md5))
1066 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1069 fwrite( md5, 16, 1, f);
1077 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1079 ,abortTimer(ml), zapTimer(ml), state(0)
1080 ,isRunning(0), haveData(0)
1081 #ifdef ENABLE_PRIVATE_EPG
1082 ,startPrivateTimer(ml)
1084 #ifdef ENABLE_MHW_EPG
1085 ,m_MHWTimeoutTimer(ml)
1088 #ifdef ENABLE_MHW_EPG
1089 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1091 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1092 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1093 #ifdef ENABLE_PRIVATE_EPG
1094 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1096 pthread_mutex_init(&channel_active, 0);
1099 bool eEPGCache::channel_data::finishEPG()
1101 if (!isRunning) // epg ready
1103 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1104 zapTimer.start(UPDATE_INTERVAL, 1);
1105 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1106 for (int i=0; i < 3; ++i)
1108 seenSections[i].clear();
1109 calcedSections[i].clear();
1111 singleLock l(cache->cache_lock);
1112 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1113 #ifdef ENABLE_MHW_EPG
1121 void eEPGCache::channel_data::startEPG()
1123 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1126 for (int i=0; i < 3; ++i)
1128 seenSections[i].clear();
1129 calcedSections[i].clear();
1132 eDVBSectionFilterMask mask;
1133 memset(&mask, 0, sizeof(mask));
1135 #ifdef ENABLE_MHW_EPG
1137 mask.data[0] = 0x91;
1138 mask.mask[0] = 0xFF;
1139 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1140 m_MHWReader->start(mask);
1142 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1145 mask.data[0] = 0xC8;
1146 mask.mask[0] = 0xFF;
1148 mask.mask[1] = 0xFF;
1149 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1150 m_MHWReader2->start(mask);
1152 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1158 mask.flags = eDVBSectionFilterMask::rfCRC;
1160 mask.data[0] = 0x4E;
1161 mask.mask[0] = 0xFE;
1162 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1163 m_NowNextReader->start(mask);
1164 isRunning |= NOWNEXT;
1166 mask.data[0] = 0x50;
1167 mask.mask[0] = 0xF0;
1168 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1169 m_ScheduleReader->start(mask);
1170 isRunning |= SCHEDULE;
1172 mask.data[0] = 0x60;
1173 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1174 m_ScheduleOtherReader->start(mask);
1175 isRunning |= SCHEDULE_OTHER;
1177 abortTimer.start(7000,true);
1180 void eEPGCache::channel_data::abortNonAvail()
1184 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1186 eDebug("[EPGC] abort non avail nownext reading");
1187 isRunning &= ~NOWNEXT;
1188 m_NowNextReader->stop();
1191 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1193 eDebug("[EPGC] abort non avail schedule reading");
1194 isRunning &= ~SCHEDULE;
1195 m_ScheduleReader->stop();
1198 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1200 eDebug("[EPGC] abort non avail schedule_other reading");
1201 isRunning &= ~SCHEDULE_OTHER;
1202 m_ScheduleOtherReader->stop();
1203 m_ScheduleOtherConn=0;
1205 #ifdef ENABLE_MHW_EPG
1206 if ( !(haveData&MHW) && (isRunning&MHW) )
1208 eDebug("[EPGC] abort non avail mhw reading");
1210 m_MHWReader->stop();
1212 m_MHWReader2->stop();
1217 abortTimer.start(90000, true);
1221 for (int i=0; i < 3; ++i)
1223 seenSections[i].clear();
1224 calcedSections[i].clear();
1231 void eEPGCache::channel_data::startChannel()
1233 pthread_mutex_lock(&channel_active);
1234 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1236 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1238 if (update < ZAP_DELAY)
1241 zapTimer.start(update, 1);
1242 if (update >= 60000)
1243 eDebug("[EPGC] next update in %i min", update/60000);
1244 else if (update >= 1000)
1245 eDebug("[EPGC] next update in %i sec", update/1000);
1248 void eEPGCache::channel_data::abortEPG()
1250 for (int i=0; i < 3; ++i)
1252 seenSections[i].clear();
1253 calcedSections[i].clear();
1259 eDebug("[EPGC] abort caching events !!");
1260 if (isRunning & SCHEDULE)
1262 isRunning &= ~SCHEDULE;
1263 m_ScheduleReader->stop();
1266 if (isRunning & NOWNEXT)
1268 isRunning &= ~NOWNEXT;
1269 m_NowNextReader->stop();
1272 if (isRunning & SCHEDULE_OTHER)
1274 isRunning &= ~SCHEDULE_OTHER;
1275 m_ScheduleOtherReader->stop();
1276 m_ScheduleOtherConn=0;
1278 #ifdef ENABLE_MHW_EPG
1279 if (isRunning & MHW)
1282 m_MHWReader->stop();
1284 m_MHWReader2->stop();
1289 #ifdef ENABLE_PRIVATE_EPG
1290 if (m_PrivateReader)
1291 m_PrivateReader->stop();
1295 pthread_mutex_unlock(&channel_active);
1298 void eEPGCache::channel_data::readData( const __u8 *data)
1302 iDVBSectionReader *reader=NULL;
1306 reader=m_NowNextReader;
1311 reader=m_ScheduleReader;
1316 reader=m_ScheduleOtherReader;
1317 source=SCHEDULE_OTHER;
1321 eDebug("[EPGC] unknown table_id !!!");
1324 tidMap &seenSections = this->seenSections[map];
1325 tidMap &calcedSections = this->calcedSections[map];
1326 if ( state == 1 && calcedSections == seenSections || state > 1 )
1328 eDebugNoNewLine("[EPGC] ");
1333 eDebugNoNewLine("nownext");
1337 eDebugNoNewLine("schedule");
1339 case SCHEDULE_OTHER:
1340 m_ScheduleOtherConn=0;
1341 eDebugNoNewLine("schedule other");
1343 default: eDebugNoNewLine("unknown");break;
1345 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1348 isRunning &= ~source;
1354 eit_t *eit = (eit_t*) data;
1355 __u32 sectionNo = data[0] << 24;
1356 sectionNo |= data[3] << 16;
1357 sectionNo |= data[4] << 8;
1358 sectionNo |= eit->section_number;
1360 tidMap::iterator it =
1361 seenSections.find(sectionNo);
1363 if ( it == seenSections.end() )
1365 seenSections.insert(sectionNo);
1366 calcedSections.insert(sectionNo);
1367 __u32 tmpval = sectionNo & 0xFFFFFF00;
1368 __u8 incr = source == NOWNEXT ? 1 : 8;
1369 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1371 if ( i == eit->section_number )
1373 for (int x=i; x <= eit->segment_last_section_number; ++x)
1374 calcedSections.insert(tmpval|(x&0xFF));
1377 calcedSections.insert(tmpval|(i&0xFF));
1379 cache->sectionRead(data, source, this);
1384 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1385 // if t == -1 we search the current event...
1387 singleLock s(cache_lock);
1388 uniqueEPGKey key(handleGroup(service));
1390 // check if EPG for this service is ready...
1391 eventCache::iterator It = eventDB.find( key );
1392 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1395 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1396 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1397 It->second.second.upper_bound(t); // just >
1398 if ( i != It->second.second.end() )
1400 if ( direction < 0 || (direction == 0 && i->first > t) )
1402 timeMap::iterator x = i;
1404 if ( x != It->second.second.end() )
1406 time_t start_time = x->first;
1411 if (t > (start_time+x->second->getDuration()))
1426 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1428 singleLock s(cache_lock);
1429 const eventData *data=0;
1430 RESULT ret = lookupEventTime(service, t, data, direction);
1432 result = data->get();
1436 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1438 singleLock s(cache_lock);
1439 const eventData *data=0;
1440 RESULT ret = lookupEventTime(service, t, data, direction);
1442 result = new Event((uint8_t*)data->get());
1446 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1448 singleLock s(cache_lock);
1449 const eventData *data=0;
1450 RESULT ret = lookupEventTime(service, t, data, direction);
1453 Event ev((uint8_t*)data->get());
1454 result = new eServiceEvent();
1455 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1456 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1461 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1463 singleLock s(cache_lock);
1464 uniqueEPGKey key(handleGroup(service));
1466 eventCache::iterator It = eventDB.find( key );
1467 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1469 eventMap::iterator i( It->second.first.find( event_id ));
1470 if ( i != It->second.first.end() )
1478 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1484 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1486 singleLock s(cache_lock);
1487 const eventData *data=0;
1488 RESULT ret = lookupEventId(service, event_id, data);
1490 result = data->get();
1494 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1496 singleLock s(cache_lock);
1497 const eventData *data=0;
1498 RESULT ret = lookupEventId(service, event_id, data);
1500 result = new Event((uint8_t*)data->get());
1504 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1506 singleLock s(cache_lock);
1507 const eventData *data=0;
1508 RESULT ret = lookupEventId(service, event_id, data);
1511 Event ev((uint8_t*)data->get());
1512 result = new eServiceEvent();
1513 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1514 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1519 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1521 singleLock s(cache_lock);
1522 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1524 begin = eDVBLocalTimeHandler::getInstance()->nowTime();
1525 eventCache::iterator It = eventDB.find(ref);
1526 if ( It != eventDB.end() && It->second.second.size() )
1528 m_timemap_cursor = It->second.second.lower_bound(begin);
1529 if ( m_timemap_cursor != It->second.second.end() )
1531 if ( m_timemap_cursor->first != begin )
1533 timeMap::iterator x = m_timemap_cursor;
1535 if ( x != It->second.second.end() )
1537 time_t start_time = x->first;
1538 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1539 m_timemap_cursor = x;
1545 m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1547 m_timemap_end = It->second.second.end();
1549 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1550 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1555 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1557 if ( m_timemap_cursor != m_timemap_end )
1559 result = m_timemap_cursor++->second;
1565 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1567 if ( m_timemap_cursor != m_timemap_end )
1569 result = m_timemap_cursor++->second->get();
1575 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1577 if ( m_timemap_cursor != m_timemap_end )
1579 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1585 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1587 if ( m_timemap_cursor != m_timemap_end )
1589 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1590 result = new eServiceEvent();
1591 return result->parseFrom(&ev, currentQueryTsidOnid);
1596 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1601 while(spos < argcount)
1603 bool inc_refcount=false;
1604 switch((c=argstring[spos++]))
1606 case '0': // PyLong 0
1607 tmp = PyLong_FromLong(0);
1609 case 'I': // Event Id
1610 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1612 case 'B': // Event Begin Time
1613 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1615 case 'D': // Event Duration
1616 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1618 case 'T': // Event Title
1619 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1621 case 'S': // Event Short Description
1622 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1624 case 'E': // Event Extended Description
1625 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1627 case 'C': // Current Time
1629 inc_refcount = true;
1631 case 'R': // service reference string
1633 inc_refcount = true;
1635 case 'n': // short service name
1636 case 'N': // service name
1638 inc_refcount = true;
1643 default: // ignore unknown
1644 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1649 inc_refcount = true;
1653 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1657 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1661 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1662 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1666 Py_DECREF(service_name);
1669 Py_DECREF(convertFuncArgs);
1670 Py_DECREF(dest_list);
1671 PyErr_SetString(PyExc_StandardError,
1672 "error in convertFunc execute");
1673 eDebug("error in convertFunc execute");
1676 PyList_Append(dest_list, result);
1681 ePyObject tuple = PyTuple_New(argcount);
1682 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1683 PyList_Append(dest_list, tuple);
1689 // here we get a python list
1690 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1693 // B = Event Begin Time
1694 // D = Event Duration
1696 // S = Event Short Description
1697 // E = Event Extended Description
1699 // R = Service Reference
1701 // n = Short Service Name
1702 // X = Return a minimum of one tuple per service in the result list... even when no event was found.
1703 // The returned tuple is filled with all available infos... non avail is filled as None
1704 // The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1705 // then for each service follows a tuple
1706 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1707 // the second is the type of query
1709 // -1 = event before given start_time
1710 // 0 = event intersects given start_time
1711 // +1 = event after given start_time
1713 // when type is eventid it is the event_id
1714 // when type is time then it is the start_time ( -1 for now_time )
1715 // the fourth is the end_time .. ( optional .. for query all events in time range)
1717 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1719 ePyObject convertFuncArgs;
1721 char *argstring=NULL;
1722 if (!PyList_Check(list))
1724 PyErr_SetString(PyExc_StandardError,
1730 int listSize=PyList_Size(list);
1733 PyErr_SetString(PyExc_StandardError,
1734 "not params given");
1735 eDebug("not params given");
1740 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1741 if (PyString_Check(argv))
1743 argstring = PyString_AS_STRING(argv);
1747 argstring = "I"; // just event id as default
1748 argcount = strlen(argstring);
1749 // eDebug("have %d args('%s')", argcount, argstring);
1752 bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1758 if (!PyCallable_Check(convertFunc))
1760 PyErr_SetString(PyExc_StandardError,
1761 "convertFunc must be callable");
1762 eDebug("convertFunc is not callable");
1765 convertFuncArgs = PyTuple_New(argcount);
1768 ePyObject nowTime = strchr(argstring, 'C') ?
1769 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1772 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1775 ePyObject dest_list=PyList_New(0);
1776 while(listSize > listIt)
1778 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1779 if (PyTuple_Check(item))
1781 bool service_changed=false;
1786 int tupleSize=PyTuple_Size(item);
1789 while(tupleSize > tupleIt) // parse query args
1791 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1796 if (!PyString_Check(entry))
1798 eDebug("tuple entry 0 is no a string");
1805 type=PyInt_AsLong(entry);
1806 if (type < -1 || type > 2)
1808 eDebug("unknown type %d", type);
1813 event_id=stime=PyInt_AsLong(entry);
1816 minutes=PyInt_AsLong(entry);
1819 eDebug("unneeded extra argument");
1824 if (minutes && stime == -1)
1825 stime = eDVBLocalTimeHandler::getInstance()->nowTime();
1827 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1828 if (ref.type != eServiceReference::idDVB)
1830 eDebug("service reference for epg query is not valid");
1834 // redirect subservice querys to parent service
1835 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1836 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1838 eServiceCenterPtr service_center;
1839 if (!eServiceCenter::getPrivInstance(service_center))
1841 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1842 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1843 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1844 dvb_ref.setParentServiceID(eServiceID(0));
1846 service = PyString_FromString(dvb_ref.toString().c_str());
1847 service_changed = true;
1851 ePyObject service_name;
1852 if (must_get_service_name)
1854 ePtr<iStaticServiceInformation> sptr;
1855 eServiceCenterPtr service_center;
1856 eServiceCenter::getPrivInstance(service_center);
1859 service_center->info(ref, sptr);
1863 sptr->getName(ref, name);
1865 if (must_get_service_name == 1)
1868 // filter short name brakets
1869 while((pos = name.find("\xc2\x86")) != std::string::npos)
1871 while((pos = name.find("\xc2\x87")) != std::string::npos)
1875 name = buildShortName(name);
1878 service_name = PyString_FromString(name.c_str());
1882 service_name = PyString_FromString("<n/a>");
1886 singleLock s(cache_lock);
1887 if (!startTimeQuery(ref, stime, minutes))
1889 while ( m_timemap_cursor != m_timemap_end )
1891 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1893 evt.parseFrom(&ev, currentQueryTsidOnid);
1894 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1898 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1907 singleLock s(cache_lock);
1909 lookupEventId(ref, event_id, ev);
1911 lookupEventTime(ref, stime, ev, type);
1914 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
1915 evt.parseFrom(ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
1920 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1923 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1926 if (service_changed)
1929 Py_DECREF(service_name);
1934 if (convertFuncArgs)
1935 Py_DECREF(convertFuncArgs);
1941 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
1945 while(pos < argcount)
1947 bool inc_refcount=false;
1948 switch(argstring[pos])
1950 case '0': // PyLong 0
1951 tmp = PyLong_FromLong(0);
1953 case 'I': // Event Id
1954 tmp = PyLong_FromLong(evData->getEventID());
1956 case 'B': // Event Begin Time
1958 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1960 tmp = PyLong_FromLong(evData->getStartTime());
1962 case 'D': // Event Duration
1964 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1966 tmp = PyLong_FromLong(evData->getDuration());
1968 case 'T': // Event Title
1969 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1971 case 'S': // Event Short Description
1972 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1974 case 'E': // Event Extended Description
1975 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1977 case 'R': // service reference string
1978 tmp = service_reference;
1979 inc_refcount = true;
1981 case 'n': // short service name
1982 case 'N': // service name
1984 inc_refcount = true;
1986 default: // ignore unknown
1987 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
1992 inc_refcount = true;
1996 PyTuple_SET_ITEM(tuple, pos++, tmp);
2000 // here we get a python tuple
2001 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2003 // B = Event Begin Time
2004 // D = Event Duration
2006 // S = Event Short Description
2007 // E = Event Extended Description
2008 // R = Service Reference
2010 // n = Short Service Name
2011 // the second tuple entry is the MAX matches value
2012 // the third tuple entry is the type of query
2013 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2014 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2015 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2016 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2017 // the fourth is the servicereference string
2018 // the fifth is the eventid
2019 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2020 // the fourth is the search text
2022 // 0 = case sensitive (CASE_CHECK)
2023 // 1 = case insensitive (NO_CASECHECK)
2025 PyObject *eEPGCache::search(ePyObject arg)
2031 const char *argstring=0;
2035 bool needServiceEvent=false;
2038 if (PyTuple_Check(arg))
2040 int tuplesize=PyTuple_Size(arg);
2043 ePyObject obj = PyTuple_GET_ITEM(arg,0);
2044 if (PyString_Check(obj))
2046 argcount = PyString_GET_SIZE(obj);
2047 argstring = PyString_AS_STRING(obj);
2048 for (int i=0; i < argcount; ++i)
2049 switch(argstring[i])
2054 needServiceEvent=true;
2061 PyErr_SetString(PyExc_StandardError,
2063 eDebug("tuple arg 0 is not a string");
2068 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2071 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2072 if (tuplesize > 4 && querytype == 0)
2074 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2075 if (PyString_Check(obj))
2077 refstr = PyString_AS_STRING(obj);
2078 eServiceReferenceDVB ref(refstr);
2081 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2082 singleLock s(cache_lock);
2083 const eventData *evData = 0;
2084 lookupEventId(ref, eventid, evData);
2087 __u8 *data = evData->EITdata;
2088 int tmp = evData->ByteSize-10;
2089 __u32 *p = (__u32*)(data+10);
2090 // search short and extended event descriptors
2094 descriptorMap::iterator it =
2095 eventData::descriptors.find(crc);
2096 if (it != eventData::descriptors.end())
2098 __u8 *descr_data = it->second.second;
2099 switch(descr_data[0])
2102 descr[++descridx]=crc;
2111 eDebug("event not found");
2115 PyErr_SetString(PyExc_StandardError, "type error");
2116 eDebug("tuple arg 4 is not a valid service reference string");
2122 PyErr_SetString(PyExc_StandardError, "type error");
2123 eDebug("tuple arg 4 is not a string");
2127 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2129 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2130 if (PyString_Check(obj))
2132 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2133 const char *str = PyString_AS_STRING(obj);
2134 int textlen = PyString_GET_SIZE(obj);
2136 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2138 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2139 singleLock s(cache_lock);
2140 for (descriptorMap::iterator it(eventData::descriptors.begin());
2141 it != eventData::descriptors.end() && descridx < 511; ++it)
2143 __u8 *data = it->second.second;
2144 if ( data[0] == 0x4D ) // short event descriptor
2146 int title_len = data[5];
2147 if ( querytype == 1 )
2149 if (title_len > textlen)
2151 else if (title_len < textlen)
2155 if ( !strncasecmp((const char*)data+6, str, title_len) )
2157 // std::string s((const char*)data+6, title_len);
2158 // eDebug("match1 %s %s", str, s.c_str() );
2159 descr[++descridx] = it->first;
2162 else if ( !strncmp((const char*)data+6, str, title_len) )
2164 // std::string s((const char*)data+6, title_len);
2165 // eDebug("match2 %s %s", str, s.c_str() );
2166 descr[++descridx] = it->first;
2172 while((title_len-idx) >= textlen)
2176 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2178 descr[++descridx] = it->first;
2179 // std::string s((const char*)data+6, title_len);
2180 // eDebug("match 3 %s %s", str, s.c_str() );
2183 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2185 descr[++descridx] = it->first;
2186 // std::string s((const char*)data+6, title_len);
2187 // eDebug("match 4 %s %s", str, s.c_str() );
2199 PyErr_SetString(PyExc_StandardError,
2201 eDebug("tuple arg 4 is not a string");
2207 PyErr_SetString(PyExc_StandardError,
2209 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2215 PyErr_SetString(PyExc_StandardError,
2217 eDebug("not enough args in tuple");
2223 PyErr_SetString(PyExc_StandardError,
2225 eDebug("arg 0 is not a tuple");
2231 int maxcount=maxmatches;
2232 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2233 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2234 // in this case we start searching with the base service
2235 bool first = ref.valid() ? true : false;
2236 singleLock s(cache_lock);
2237 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2238 while(cit != eventDB.end() && maxcount)
2240 if ( ref.valid() && !first && cit->first == ref )
2242 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2246 ePyObject service_name;
2247 ePyObject service_reference;
2248 timeMap &evmap = cit->second.second;
2250 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2252 int evid = evit->second->getEventID();
2253 if ( evid == eventid)
2255 __u8 *data = evit->second->EITdata;
2256 int tmp = evit->second->ByteSize-10;
2257 __u32 *p = (__u32*)(data+10);
2258 // check if any of our descriptor used by this event
2263 for ( int i=0; i <= descridx; ++i)
2265 if (descr[i] == crc32) // found...
2270 if ( (querytype == 0 && cnt == descridx) ||
2271 ((querytype == 1 || querytype == 2) && cnt != -1) )
2273 const uniqueEPGKey &service = cit->first;
2274 eServiceReference ref =
2275 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2278 // create servive event
2281 if (needServiceEvent)
2283 if (lookupEventId(ref, evid, ev))
2284 eDebug("event not found !!!!!!!!!!!");
2287 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2288 ptr.parseFrom(ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2291 // create service name
2294 int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
2295 if (must_get_service_name)
2297 ePtr<iStaticServiceInformation> sptr;
2298 eServiceCenterPtr service_center;
2299 eServiceCenter::getPrivInstance(service_center);
2302 service_center->info(ref, sptr);
2306 sptr->getName(ref, name);
2308 if (must_get_service_name == 1)
2311 // filter short name brakets
2312 while((pos = name.find("\xc2\x86")) != std::string::npos)
2314 while((pos = name.find("\xc2\x87")) != std::string::npos)
2318 name = buildShortName(name);
2321 service_name = PyString_FromString(name.c_str());
2325 service_name = PyString_FromString("<n/a>");
2328 // create servicereference string
2329 if (!service_reference && strchr(argstring,'R'))
2330 service_reference = PyString_FromString(ref.toString().c_str());
2333 ret = PyList_New(0);
2335 ePyObject tuple = PyTuple_New(argcount);
2337 fillTuple2(tuple, argstring, argcount, evit->second, ev ? &ptr : 0, service_name, service_reference);
2338 PyList_Append(ret, tuple);
2345 Py_DECREF(service_name);
2346 if (service_reference)
2347 Py_DECREF(service_reference);
2350 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2352 cit=eventDB.begin();
2365 #ifdef ENABLE_PRIVATE_EPG
2366 #include <dvbsi++/descriptor_tag.h>
2367 #include <dvbsi++/unknown_descriptor.h>
2368 #include <dvbsi++/private_data_specifier_descriptor.h>
2370 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2372 ePtr<eTable<ProgramMapSection> > ptr;
2373 if (!pmthandler->getPMT(ptr) && ptr)
2375 std::vector<ProgramMapSection*>::const_iterator i;
2376 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2378 const ProgramMapSection &pmt = **i;
2380 ElementaryStreamInfoConstIterator es;
2381 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2384 switch ((*es)->getType())
2386 case 0x05: // private
2387 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2388 desc != (*es)->getDescriptors()->end(); ++desc)
2390 switch ((*desc)->getTag())
2392 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2393 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2398 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2399 int descr_len = descr->getLength();
2402 uint8_t data[descr_len+2];
2403 descr->writeToBuffer(data);
2404 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2418 eServiceReferenceDVB ref;
2419 if (!pmthandler->getServiceReference(ref))
2421 int pid = (*es)->getPid();
2422 messages.send(Message(Message::got_private_pid, ref, pid));
2430 eDebug("PMTready but no pmt!!");
2437 date_time( const date_time &a )
2439 memcpy(data, a.data, 5);
2442 date_time( const __u8 data[5])
2444 memcpy(this->data, data, 5);
2445 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2450 const __u8& operator[](int pos) const
2456 struct less_datetime
2458 bool operator()( const date_time &a, const date_time &b ) const
2460 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2464 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2466 contentMap &content_time_table = content_time_tables[current_service];
2467 singleLock s(cache_lock);
2468 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2469 eventMap &evMap = eventDB[current_service].first;
2470 timeMap &tmMap = eventDB[current_service].second;
2472 int content_id = data[ptr++] << 24;
2473 content_id |= data[ptr++] << 16;
2474 content_id |= data[ptr++] << 8;
2475 content_id |= data[ptr++];
2477 contentTimeMap &time_event_map =
2478 content_time_table[content_id];
2479 for ( contentTimeMap::iterator it( time_event_map.begin() );
2480 it != time_event_map.end(); ++it )
2482 eventMap::iterator evIt( evMap.find(it->second.second) );
2483 if ( evIt != evMap.end() )
2485 delete evIt->second;
2488 tmMap.erase(it->second.first);
2490 time_event_map.clear();
2493 memcpy(duration, data+ptr, 3);
2496 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2498 const __u8 *descriptors[65];
2499 const __u8 **pdescr = descriptors;
2501 int descriptors_length = (data[ptr++]&0x0F) << 8;
2502 descriptors_length |= data[ptr++];
2503 while ( descriptors_length > 1 )
2505 int descr_type = data[ptr];
2506 int descr_len = data[ptr+1];
2507 descriptors_length -= 2;
2508 if (descriptors_length >= descr_len)
2510 descriptors_length -= descr_len;
2511 if ( descr_type == 0xf2 && descr_len > 5)
2514 int tsid = data[ptr++] << 8;
2515 tsid |= data[ptr++];
2516 int onid = data[ptr++] << 8;
2517 onid |= data[ptr++];
2518 int sid = data[ptr++] << 8;
2521 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2524 switch( (tsid << 16) | sid )
2526 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2527 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2528 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2529 case 0x0300f5: sid = 0xdc; break;
2530 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2531 case 0x1100d3: sid = 0xe3; break;
2532 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2535 ////////////////////////////////////////////
2537 uniqueEPGKey service( sid, onid, tsid );
2539 while( descr_len > 2 )
2542 datetime[0] = data[ptr++];
2543 datetime[1] = data[ptr++];
2544 int tmp_len = data[ptr++];
2546 if (descr_len >= tmp_len)
2548 descr_len -= tmp_len;
2549 while( tmp_len > 2 )
2551 memcpy(datetime+2, data+ptr, 3);
2554 start_times[datetime].push_back(service);
2567 ASSERT(pdescr <= &descriptors[65])
2569 eit_event_struct *ev_struct = (eit_event_struct*) event;
2570 ev_struct->running_status = 0;
2571 ev_struct->free_CA_mode = 1;
2572 memcpy(event+7, duration, 3);
2574 const __u8 **d=descriptors;
2575 while ( d < pdescr )
2577 memcpy(event+ptr, *d, ((*d)[1])+2);
2581 ASSERT(ptr <= 4098);
2582 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2584 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2585 if ( (it->first.tm + duration_sec) < now )
2587 memcpy(event+2, it->first.data, 5);
2590 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2592 event[bptr++] = 0x4A;
2593 __u8 *len = event+(bptr++);
2594 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2595 event[bptr++] = (i->tsid & 0xFF);
2596 event[bptr++] = (i->onid & 0xFF00) >> 8;
2597 event[bptr++] = (i->onid & 0xFF);
2598 event[bptr++] = (i->sid & 0xFF00) >> 8;
2599 event[bptr++] = (i->sid & 0xFF);
2600 event[bptr++] = 0xB0;
2601 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2602 *len = ((event+bptr) - len)-1;
2604 int llen = bptr - 12;
2605 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2606 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2608 time_t stime = it->first.tm;
2609 while( tmMap.find(stime) != tmMap.end() )
2611 event[6] += (stime - it->first.tm);
2613 while( evMap.find(event_id) != evMap.end() )
2615 event[0] = (event_id & 0xFF00) >> 8;
2616 event[1] = (event_id & 0xFF);
2617 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2618 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2619 evMap[event_id] = d;
2621 ASSERT(bptr <= 4098);
2625 void eEPGCache::channel_data::startPrivateReader()
2627 eDVBSectionFilterMask mask;
2628 memset(&mask, 0, sizeof(mask));
2629 mask.pid = m_PrivatePid;
2630 mask.flags = eDVBSectionFilterMask::rfCRC;
2631 mask.data[0] = 0xA0;
2632 mask.mask[0] = 0xFF;
2633 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2634 if (m_PrevVersion != -1)
2636 mask.data[3] = m_PrevVersion << 1;
2637 mask.mask[3] = 0x3E;
2638 mask.mode[3] = 0x3E;
2640 seenPrivateSections.clear();
2642 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2643 m_PrivateReader->start(mask);
2646 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2648 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2650 cache->privateSectionRead(m_PrivateService, data);
2651 seenPrivateSections.insert(data[6]);
2653 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2655 eDebug("[EPGC] private finished");
2656 eDVBChannelID chid = channel->getChannelID();
2657 int tmp = chid.original_network_id.get();
2658 tmp |= 0x80000000; // we use highest bit as private epg indicator
2659 chid.original_network_id = tmp;
2660 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2661 m_PrevVersion = (data[5] & 0x3E) >> 1;
2662 startPrivateReader();
2666 #endif // ENABLE_PRIVATE_EPG
2668 #ifdef ENABLE_MHW_EPG
2669 void eEPGCache::channel_data::cleanup()
2674 m_program_ids.clear();
2677 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2679 // Names in mhw structs are not strings as they are not '\0' terminated.
2680 // This function converts the mhw name into a string.
2681 // Constraint: "length of out" = "length of in" + 1.
2683 for ( i=0; i < len_in; i++ )
2687 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2694 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2697 return_time[0] = toBCD( hours );
2698 return_time[1] = toBCD( minutes );
2702 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2704 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2707 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2708 // For date plus time of day
2710 // Remove offset in mhw time.
2711 __u8 local_hours = hours;
2714 else if ( hours >= 8 )
2717 // As far as we know all mhw time data is sent in central Europe time zone.
2718 // So, temporarily set timezone to western europe
2719 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2721 char *old_tz = getenv( "TZ" );
2722 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2726 localtime_r(&dt, &localnow);
2730 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2732 if (local_hours <= 5)
2735 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2736 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2739 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2741 if ( old_tz == NULL )
2747 // Calculate MJD according to annex in ETSI EN 300 468
2749 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2751 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2752 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2754 return_time[0] = (mjd & 0xFF00)>>8;
2755 return_time[1] = mjd & 0xFF;
2757 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2760 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2761 // data is borrowed from calling proc to save memory space.
2765 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2766 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2767 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2769 eit_t *packet = (eit_t *) data;
2770 packet->table_id = 0x50;
2771 packet->section_syntax_indicator = 1;
2773 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2774 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2775 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2776 packet->current_next_indicator = 0;
2777 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2778 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2779 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2780 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2781 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2782 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2783 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2784 packet->segment_last_table_id = 0x50;
2786 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2787 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2788 int prog_title_length = prog_title.length();
2790 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2791 prog_title_length + 1;
2793 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2794 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2795 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2799 u_char *data = (u_char*) event_data;
2800 data[2] = itTitle->second.mhw2_mjd_hi;
2801 data[3] = itTitle->second.mhw2_mjd_lo;
2802 data[4] = itTitle->second.mhw2_hours;
2803 data[5] = itTitle->second.mhw2_minutes;
2804 data[6] = itTitle->second.mhw2_seconds;
2805 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2809 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2810 (u_char *) event_data + 2 );
2811 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2814 event_data->running_status = 0;
2815 event_data->free_CA_mode = 0;
2816 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2818 eit_short_event_descriptor_struct *short_event_descriptor =
2819 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2820 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2821 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2822 prog_title_length - 1;
2823 short_event_descriptor->language_code_1 = 'e';
2824 short_event_descriptor->language_code_2 = 'n';
2825 short_event_descriptor->language_code_3 = 'g';
2826 short_event_descriptor->event_name_length = prog_title_length;
2827 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2828 memcpy(event_name, prog_title.c_str(), prog_title_length);
2831 event_name[prog_title_length] = 0;
2833 if ( sumText.length() > 0 )
2834 // There is summary info
2836 unsigned int sum_length = sumText.length();
2837 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2838 // Store summary in short event descriptor
2840 // Increase all relevant lengths
2841 event_name[prog_title_length] = sum_length;
2842 short_event_descriptor->descriptor_length += sum_length;
2843 packet_length += sum_length;
2844 descr_ll += sum_length;
2845 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2848 // Store summary in extended event descriptors
2850 int remaining_sum_length = sumText.length();
2851 int nbr_descr = int(remaining_sum_length/247) + 1;
2852 for ( int i=0; i < nbr_descr; i++)
2853 // Loop once per extended event descriptor
2855 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2856 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2857 remaining_sum_length -= sum_length;
2858 packet_length += 8 + sum_length;
2859 descr_ll += 8 + sum_length;
2861 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2862 ext_event_descriptor->descriptor_length = sum_length + 6;
2863 ext_event_descriptor->descriptor_number = i;
2864 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2865 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2866 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2867 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2868 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2870 the_text[-1] = sum_length;
2871 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2878 // Add content descriptor
2879 u_char *descriptor = (u_char *) data + packet_length;
2884 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2885 if ( content_descr.find( "FILM" ) != std::string::npos )
2887 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2890 descriptor[0] = 0x54;
2892 descriptor[2] = content_id;
2896 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2897 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2899 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2900 packet->section_length_lo = (packet_length - 3)&0xff;
2902 // Feed the data to eEPGCache::sectionRead()
2903 cache->sectionRead( data, MHW, this );
2906 void eEPGCache::channel_data::startTimeout(int msec)
2908 m_MHWTimeoutTimer.start(msec,true);
2909 m_MHWTimeoutet=false;
2912 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2914 m_MHWFilterMask.pid = pid;
2915 m_MHWFilterMask.data[0] = tid;
2916 m_MHWReader->start(m_MHWFilterMask);
2917 // eDebug("start 0x%02x 0x%02x", pid, tid);
2920 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2922 m_MHWFilterMask2.pid = pid;
2923 m_MHWFilterMask2.data[0] = tid;
2926 m_MHWFilterMask2.data[1] = ext;
2927 m_MHWFilterMask2.mask[1] = 0xFF;
2928 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2932 m_MHWFilterMask2.data[1] = 0;
2933 m_MHWFilterMask2.mask[1] = 0;
2934 // eDebug("start 0x%02x 0x%02x", pid, tid);
2936 m_MHWReader2->start(m_MHWFilterMask2);
2939 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2942 m_MHWReader2->stop();
2944 if ( state > 1 || // aborted
2945 // have si data.. so we dont read mhw data
2946 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2948 eDebug("[EPGC] mhw aborted %d", state);
2950 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2953 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2954 int record_size = sizeof( mhw_channel_name_t );
2955 int nbr_records = int (len/record_size);
2957 m_channels.resize(nbr_records);
2958 for ( int i = 0; i < nbr_records; i++ )
2960 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2961 m_channels[i]=*channel;
2965 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2967 // Channels table has been read, start reading the themes table.
2968 startMHWReader(0xD3, 0x92);
2971 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2974 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2975 int record_size = sizeof( mhw_theme_name_t );
2976 int nbr_records = int (len/record_size);
2978 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2981 for ( int i = 0; i < nbr_records; i++ )
2983 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2984 if ( i >= next_idx )
2988 next_idx = (__u8) *(data + 3 + idx_ptr);
2994 m_themes[idx+sub_idx] = *theme;
2996 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2997 // Themes table has been read, start reading the titles table.
2998 startMHWReader(0xD2, 0x90);
3002 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3005 mhw_title_t *title = (mhw_title_t*) data;
3007 if ( title->channel_id == 0xFF ) // Separator
3008 return; // Continue reading of the current table.
3011 // Create unique key per title
3012 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
3013 (title->ms.minutes);
3014 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
3015 ((title->program_id_ml)<<8)|(title->program_id_lo);
3017 if ( m_titles.find( title_id ) == m_titles.end() )
3020 title->mhw2_mjd_hi = 0;
3021 title->mhw2_mjd_lo = 0;
3022 title->mhw2_duration_hi = 0;
3023 title->mhw2_duration_lo = 0;
3024 m_titles[ title_id ] = *title;
3025 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3026 // program_ids will be used to gather summaries.
3027 m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3028 return; // Continue reading of the current table.
3030 else if (!checkTimeout())
3033 if ( !m_program_ids.empty())
3035 // Titles table has been read, there are summaries to read.
3036 // Start reading summaries, store corresponding titles on the fly.
3037 startMHWReader(0xD3, 0x90);
3038 eDebug("[EPGC] mhw %d titles(%d with summary) found",
3040 m_program_ids.size());
3045 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3048 mhw_summary_t *summary = (mhw_summary_t*) data;
3050 // Create unique key per record
3051 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3052 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3053 int len = ((data[1]&0xf)<<8) + data[2];
3055 // ugly workaround to convert const __u8* to char*
3057 memcpy(&tmp, &data, sizeof(void*));
3058 tmp[len+3] = 0; // Terminate as a string.
3060 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3061 if ( itProgid == m_program_ids.end() )
3062 { /* This part is to prevent to looping forever if some summaries are not received yet.
3063 There is a timeout of 4 sec. after the last successfully read summary. */
3064 if (!m_program_ids.empty() && !checkTimeout())
3065 return; // Continue reading of the current table.
3069 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3072 while((pos = the_text.find("\r\n")) != std::string::npos)
3073 the_text.replace(pos, 2, " ");
3075 // Find corresponding title, store title and summary in epgcache.
3076 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3077 if ( itTitle != m_titles.end() )
3080 storeTitle( itTitle, the_text, data );
3081 m_titles.erase( itTitle );
3083 m_program_ids.erase( itProgid );
3084 if ( !m_program_ids.empty() )
3085 return; // Continue reading of the current table.
3088 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3089 eDVBLocalTimeHandler::getInstance()->nowTime(),
3090 m_program_ids.size());
3091 // Summaries have been read, titles that have summaries have been stored.
3092 // Now store titles that do not have summaries.
3093 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3094 storeTitle( itTitle, "", data );
3098 m_MHWReader->stop();
3103 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3105 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3108 m_MHWReader->stop();
3110 if ( state > 1 || // aborted
3111 // have si data.. so we dont read mhw data
3112 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
3114 eDebug("[EPGC] mhw2 aborted %d", state);
3116 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3119 int num_channels = data[119];
3120 m_channels.resize(num_channels);
3123 int ptr = 120 + 8 * num_channels;
3126 for( int chid = 0; chid < num_channels; ++chid )
3128 ptr += ( data[ptr] & 0x0f ) + 1;
3138 // data seems consistent...
3139 const __u8 *tmp = data+120;
3140 for (int i=0; i < num_channels; ++i)
3142 mhw_channel_name_t channel;
3143 channel.network_id_hi = *(tmp++);
3144 channel.network_id_lo = *(tmp++);
3145 channel.transport_stream_id_hi = *(tmp++);
3146 channel.transport_stream_id_lo = *(tmp++);
3147 channel.channel_id_hi = *(tmp++);
3148 channel.channel_id_lo = *(tmp++);
3149 m_channels[i]=channel;
3152 for (int i=0; i < num_channels; ++i)
3154 mhw_channel_name_t &channel = m_channels[i];
3155 int channel_name_len=*(tmp++)&0x0f;
3157 for (; x < channel_name_len; ++x)
3158 channel.name[x]=*(tmp++);
3159 channel.name[x+1]=0;
3162 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3164 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3167 eDebug("[EPGC] mhw2 themes nyi");
3169 else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3174 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3176 if(data[dataLen-1] != 0xff)
3178 while( pos < dataLen )
3187 if( data[pos] > 0xc0 )
3189 pos += ( data[pos] - 0xc0 );
3193 if( data[pos] == 0xff )
3209 // data seems consistent...
3214 title.channel_id = data[pos]+1;
3215 title.program_id_ml = data[pos+1];
3216 title.program_id_lo = data[pos+2];
3217 title.mhw2_mjd_hi = data[pos+3];
3218 title.mhw2_mjd_lo = data[pos+4];
3219 title.mhw2_hours = data[pos+5];
3220 title.mhw2_minutes = data[pos+6];
3221 title.mhw2_seconds = data[pos+7];
3222 int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3223 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3224 title.mhw2_duration_lo = duration&0xFF;
3225 __u8 slen = data[pos+10] & 0x3f;
3226 __u8 *dest = ((__u8*)title.title)-4;
3227 memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3228 memset(dest+slen, 0, 33-slen);
3230 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3231 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3233 // Create unique key per title
3234 __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3238 std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3239 if ( it == m_titles.end() )
3242 m_titles[ title_id ] = title;
3243 if (summary_id != 0xFFFF)
3246 std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3247 while (it != m_program_ids.end() && it->first == summary_id)
3249 if (it->second == title_id) {
3256 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3261 if ( !checkTimeout() )
3262 continue; // Continue reading of the current table.
3270 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3271 if (!m_program_ids.empty())
3273 // Titles table has been read, there are summaries to read.
3274 // Start reading summaries, store corresponding titles on the fly.
3275 startMHWReader2(0x236, 0x96);
3276 startTimeout(15000);
3283 else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3286 if (!checkTimeout())
3288 int len, loop, pos, lenline;
3297 loop = data[pos] & 0x0f;
3302 for( ; loop > 0; --loop )
3304 if( dataLen > (pos+len) )
3306 lenline = data[pos+len];
3316 return; // continue reading
3319 // data seems consistent...
3320 __u32 summary_id = (data[3]<<8)|data[4];
3322 // ugly workaround to convert const __u8* to char*
3324 memcpy(&tmp, &data, sizeof(void*));
3329 loop = tmp[pos] & 0x0f;
3331 for( ; loop > 0; loop -- )
3333 lenline = tmp[pos+len];
3342 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3343 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3344 { /* This part is to prevent to looping forever if some summaries are not received yet.
3345 There is a timeout of 4 sec. after the last successfully read summary. */
3346 if ( !m_program_ids.empty() )
3347 return; // Continue reading of the current table.
3351 startTimeout(15000);
3352 std::string the_text = (char *) (data + pos + 1);
3354 while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3356 // Find corresponding title, store title and summary in epgcache.
3357 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3358 if ( itTitle != m_titles.end() )
3360 storeTitle( itTitle, the_text, data );
3361 m_titles.erase( itTitle );
3363 m_program_ids.erase( itProgId++ );
3365 if ( !m_program_ids.empty() )
3366 return; // Continue reading of the current table.
3370 return; // continue reading
3373 if (isRunning & eEPGCache::MHW)
3375 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3377 // Channels table has been read, start reading the themes table.
3378 startMHWReader2(0x231, 0xC8, 1);
3381 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3383 // Themes table has been read, start reading the titles table.
3384 startMHWReader2(0x234, 0xe6);
3389 // Summaries have been read, titles that have summaries have been stored.
3390 // Now store titles that do not have summaries.
3391 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3392 storeTitle( itTitle, "", data );
3393 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3394 eDVBLocalTimeHandler::getInstance()->nowTime(),
3395 m_program_ids.size());
3402 m_MHWReader2->stop();