1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
7 #include <lib/service/event.h>
11 #include <unistd.h> // for usleep
12 #include <sys/vfs.h> // for statfs
13 // #include <libmd5sum.h>
14 #include <lib/base/eerror.h>
15 #include <lib/dvb/pmt.h>
16 #include <lib/dvb/db.h>
19 int eventData::CacheSize=0;
20 descriptorMap eventData::descriptors;
21 __u8 eventData::data[4108];
22 extern const uint32_t crc32_table[256];
24 eventData::eventData(const eit_event_struct* e, int size, int type)
25 :ByteSize(size&0xFF), type(type&0xFF)
33 __u8 *data = (__u8*)e;
35 int descriptors_length = (data[ptr++]&0x0F) << 8;
36 descriptors_length |= data[ptr++];
37 while ( descriptors_length > 0 )
39 __u8 *descr = data+ptr;
40 int descr_len = descr[1]+2;
44 while(cnt++ < descr_len)
45 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
47 descriptorMap::iterator it =
48 descriptors.find(crc);
49 if ( it == descriptors.end() )
52 __u8 *d = new __u8[descr_len];
53 memcpy(d, descr, descr_len);
54 descriptors[crc] = descriptorPair(1, d);
60 descriptors_length -= descr_len;
62 ByteSize = 12+((pdescr-descr)*4);
63 EITdata = new __u8[ByteSize];
65 memcpy(EITdata, (__u8*) e, 12);
66 memcpy(EITdata+12, descr, ByteSize-12);
69 const eit_event_struct* eventData::get() const
72 int tmp = ByteSize-12;
73 memcpy(data, EITdata, 12);
74 __u32 *p = (__u32*)(EITdata+12);
77 descriptorMap::iterator it =
78 descriptors.find(*p++);
79 if ( it != descriptors.end() )
81 int b = it->second.second[1]+2;
82 memcpy(data+pos, it->second.second, b );
88 return (const eit_event_struct*)data;
91 eventData::~eventData()
97 __u32 *d = (__u32*)(EITdata+12);
100 descriptorMap::iterator it =
101 descriptors.find(*d++);
102 if ( it != descriptors.end() )
104 descriptorPair &p = it->second;
105 if (!--p.first) // no more used descriptor
107 CacheSize -= it->second.second[1];
108 delete [] it->second.second; // free descriptor memory
109 descriptors.erase(it); // remove entry from descriptor map
118 void eventData::load(FILE *f)
124 fread(&size, sizeof(int), 1, f);
127 fread(&id, sizeof(__u32), 1, f);
128 fread(&p.first, sizeof(int), 1, f);
129 fread(header, 2, 1, f);
130 int bytes = header[1]+2;
131 p.second = new __u8[bytes];
132 p.second[0] = header[0];
133 p.second[1] = header[1];
134 fread(p.second+2, bytes-2, 1, f);
141 void eventData::save(FILE *f)
143 int size=descriptors.size();
144 descriptorMap::iterator it(descriptors.begin());
145 fwrite(&size, sizeof(int), 1, f);
148 fwrite(&it->first, sizeof(__u32), 1, f);
149 fwrite(&it->second.first, sizeof(int), 1, f);
150 fwrite(it->second.second, it->second.second[1]+2, 1, f);
156 eEPGCache* eEPGCache::instance;
157 pthread_mutex_t eEPGCache::cache_lock=
158 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
159 pthread_mutex_t eEPGCache::channel_map_lock=
160 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
162 DEFINE_REF(eEPGCache)
164 eEPGCache::eEPGCache()
165 :messages(this,1), cleanTimer(this)//, paused(0)
167 eDebug("[EPGC] Initialized EPGCache");
169 CONNECT(messages.recv_msg, eEPGCache::gotMessage);
170 CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
171 CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
173 ePtr<eDVBResourceManager> res_mgr;
174 eDVBResourceManager::getInstance(res_mgr);
176 eDebug("[eEPGCache] no resource manager !!!!!!!");
178 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
182 void eEPGCache::timeUpdated()
186 eDebug("[EPGC] time updated.. start EPG Mainloop");
189 messages.send(Message(Message::timeChanged));
192 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
196 // eDebug("[eEPGCache] add channel %p", chan);
197 channel_data *data = new channel_data(this);
198 data->channel = chan;
199 data->prevChannelState = -1;
200 #ifdef ENABLE_PRIVATE_EPG
201 data->m_PrivatePid = -1;
203 singleLock s(channel_map_lock);
204 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
205 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
209 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
211 singleLock s(channel_map_lock);
212 channelMapIterator it =
213 m_knownChannels.find(chan);
214 if ( it == m_knownChannels.end() )
215 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
218 channel_data &data = *it->second;
219 ePtr<eDVBResourceManager> res_mgr;
220 if ( eDVBResourceManager::getInstance( res_mgr ) )
221 eDebug("[eEPGCache] no res manager!!");
224 ePtr<iDVBDemux> demux;
225 if ( data.channel->getDemux(demux, 0) )
227 eDebug("[eEPGCache] no demux!!");
232 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
235 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
239 res = demux->createSectionReader( this, data.m_ScheduleReader );
242 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
246 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
249 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
252 #ifdef ENABLE_PRIVATE_EPG
253 res = demux->createSectionReader( this, data.m_PrivateReader );
256 eDebug("[eEPGCache] couldnt initialize private reader!!");
260 messages.send(Message(Message::startChannel, chan));
261 // -> gotMessage -> changedService
267 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
269 channelMapIterator it =
270 m_knownChannels.find(chan);
271 if ( it != m_knownChannels.end() )
274 chan->getState(state);
275 if ( it->second->prevChannelState != state )
279 case iDVBChannel::state_ok:
281 eDebug("[eEPGCache] channel %p running", chan);
282 DVBChannelRunning(chan);
285 case iDVBChannel::state_release:
287 eDebug("[eEPGCache] remove channel %p", chan);
288 messages.send(Message(Message::leaveChannel, chan));
289 while(!it->second->canDelete())
292 m_knownChannels.erase(it);
293 // -> gotMessage -> abortEPG
296 default: // ignore all other events
299 it->second->prevChannelState = state;
304 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
306 timeMap::iterator tmp = tm_it;
307 while ((tmp->first+tmp->second->getDuration()-300) > TM)
309 if(tmp->first != TM && tmp->second->type != PRIVATE)
311 __u16 event_id = tmp->second->getEventID();
312 servicemap.first.erase(event_id);
314 Event evt((uint8_t*)tmp->second->get());
316 event.parseFrom(&evt, service.sid<<16|service.onid);
317 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
318 service.sid, event_id,
319 event.getBeginTimeString().c_str(),
320 event.getEventName().c_str(),
321 event.getExtendedDescription().c_str());
324 if (tmp == servicemap.second.begin())
326 servicemap.second.erase(tmp);
330 servicemap.second.erase(tmp--);
334 if (tmp == servicemap.second.begin())
341 while(tmp->first < (TM+duration-300))
343 if (tmp->first != TM && tmp->second->type != PRIVATE)
345 __u16 event_id = tmp->second->getEventID();
346 servicemap.first.erase(event_id);
348 Event evt((uint8_t*)tmp->second->get());
350 event.parseFrom(&evt, service.sid<<16|service.onid);
351 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
352 service.sid, event_id,
353 event.getBeginTimeString().c_str(),
354 event.getEventName().c_str(),
355 event.getExtendedDescription().c_str());
358 servicemap.second.erase(tmp++);
362 if (tmp == servicemap.second.end())
367 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
369 eit_t *eit = (eit_t*) data;
371 int len=HILO(eit->section_length)-1;//+3-4;
376 // This fixed the EPG on the Multichoice irdeto systems
377 // the EIT packet is non-compliant.. their EIT packet stinks
378 if ( data[ptr-1] < 0x40 )
381 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
382 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
386 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);
387 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
389 if ( TM != 3599 && TM > -1)
390 channel->haveData |= source;
392 singleLock s(cache_lock);
393 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
394 // oder eine durch [] erzeugte
395 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
396 eventMap::iterator prevEventIt = servicemap.first.end();
397 timeMap::iterator prevTimeIt = servicemap.second.end();
401 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
403 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
405 eit_event->start_time_1,
406 eit_event->start_time_2,
407 eit_event->start_time_3,
408 eit_event->start_time_4,
409 eit_event->start_time_5);
414 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
417 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
419 __u16 event_id = HILO(eit_event->event_id);
420 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
423 int ev_erase_count = 0;
424 int tm_erase_count = 0;
426 // search in eventmap
427 eventMap::iterator ev_it =
428 servicemap.first.find(event_id);
430 // entry with this event_id is already exist ?
431 if ( ev_it != servicemap.first.end() )
433 if ( source > ev_it->second->type ) // update needed ?
434 goto next; // when not.. then skip this entry
436 // search this event in timemap
437 timeMap::iterator tm_it_tmp =
438 servicemap.second.find(ev_it->second->getStartTime());
440 if ( tm_it_tmp != servicemap.second.end() )
442 if ( tm_it_tmp->first == TM ) // just update eventdata
445 delete ev_it->second;
446 ev_it->second = tm_it_tmp->second =
447 new eventData(eit_event, eit_event_size, source);
448 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
451 else // event has new event begin time
454 // delete the found record from timemap
455 servicemap.second.erase(tm_it_tmp);
456 prevTimeIt=servicemap.second.end();
461 // search in timemap, for check of a case if new time has coincided with time of other event
462 // or event was is not found in eventmap
463 timeMap::iterator tm_it =
464 servicemap.second.find(TM);
466 if ( tm_it != servicemap.second.end() )
468 // event with same start time but another event_id...
469 if ( source > tm_it->second->type &&
470 ev_it == servicemap.first.end() )
471 goto next; // when not.. then skip this entry
473 // search this time in eventmap
474 eventMap::iterator ev_it_tmp =
475 servicemap.first.find(tm_it->second->getEventID());
477 if ( ev_it_tmp != servicemap.first.end() )
480 // delete the found record from eventmap
481 servicemap.first.erase(ev_it_tmp);
482 prevEventIt=servicemap.first.end();
486 evt = new eventData(eit_event, eit_event_size, source);
488 bool consistencyCheck=true;
490 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
493 delete ev_it->second;
494 delete tm_it->second;
498 else if (ev_erase_count == 0 && tm_erase_count > 0)
501 delete ev_it->second;
502 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
505 else if (ev_erase_count > 0 && tm_erase_count == 0)
508 delete tm_it->second;
509 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
512 else // added new eventData
515 consistencyCheck=false;
517 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
518 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
521 FixOverlapping(servicemap, TM, duration, tm_it, service);
524 if ( consistencyCheck )
526 if ( tm_it->second != evt || ev_it->second != evt )
527 eFatal("tm_it->second != ev_it->second");
528 else if ( tm_it->second->getStartTime() != tm_it->first )
529 eFatal("event start_time(%d) non equal timemap key(%d)",
530 tm_it->second->getStartTime(), tm_it->first );
531 else if ( tm_it->first != TM )
532 eFatal("timemap key(%d) non equal TM(%d)",
534 else if ( ev_it->second->getEventID() != ev_it->first )
535 eFatal("event_id (%d) non equal event_map key(%d)",
536 ev_it->second->getEventID(), ev_it->first);
537 else if ( ev_it->first != event_id )
538 eFatal("eventmap key(%d) non equal event_id(%d)",
539 ev_it->first, event_id );
545 if ( servicemap.first.size() != servicemap.second.size() )
547 FILE *f = fopen("/hdd/event_map.txt", "w+");
549 for (eventMap::iterator it(servicemap.first.begin())
550 ; it != servicemap.first.end(); ++it )
551 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
552 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
554 f = fopen("/hdd/time_map.txt", "w+");
556 for (timeMap::iterator it(servicemap.second.begin())
557 ; it != servicemap.second.end(); ++it )
558 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
559 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
562 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
563 service.sid, service.tsid, service.onid,
564 servicemap.first.size(), servicemap.second.size() );
567 ptr += eit_event_size;
568 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
572 void eEPGCache::flushEPG(const uniqueEPGKey & s)
574 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
575 singleLock l(cache_lock);
576 if (s) // clear only this service
578 eventCache::iterator it = eventDB.find(s);
579 if ( it != eventDB.end() )
581 eventMap &evMap = it->second.first;
582 timeMap &tmMap = it->second.second;
584 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
589 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
590 #ifdef ENABLE_PRIVATE_EPG
591 contentMaps::iterator it =
592 content_time_tables.find(s);
593 if ( it != content_time_tables.end() )
596 content_time_tables.erase(it);
601 else // clear complete EPG Cache
603 for (eventCache::iterator it(eventDB.begin());
604 it != eventDB.end(); ++it)
606 eventMap &evMap = it->second.first;
607 timeMap &tmMap = it->second.second;
608 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
614 #ifdef ENABLE_PRIVATE_EPG
615 content_time_tables.clear();
617 channelLastUpdated.clear();
618 singleLock m(channel_map_lock);
619 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
620 it->second->startEPG();
622 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
625 void eEPGCache::cleanLoop()
627 singleLock s(cache_lock);
628 if (!eventDB.empty())
630 eDebug("[EPGC] start cleanloop");
632 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
634 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
636 bool updated = false;
637 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
639 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
641 // remove entry from eventMap
642 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
643 if ( b != DBIt->second.first.end() )
645 // release Heap Memory for this entry (new ....)
646 // eDebug("[EPGC] delete old event (evmap)");
647 DBIt->second.first.erase(b);
650 // remove entry from timeMap
651 // eDebug("[EPGC] release heap mem");
653 DBIt->second.second.erase(It++);
654 // eDebug("[EPGC] delete old event (timeMap)");
660 #ifdef ENABLE_PRIVATE_EPG
663 contentMaps::iterator x =
664 content_time_tables.find( DBIt->first );
665 if ( x != content_time_tables.end() )
667 timeMap &tmMap = eventDB[DBIt->first].second;
668 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
670 for ( contentTimeMap::iterator it(i->second.begin());
671 it != i->second.end(); )
673 if ( tmMap.find(it->second.first) == tmMap.end() )
674 i->second.erase(it++);
678 if ( i->second.size() )
681 x->second.erase(i++);
687 eDebug("[EPGC] stop cleanloop");
688 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
690 cleanTimer.start(CLEAN_INTERVAL,true);
693 eEPGCache::~eEPGCache()
695 messages.send(Message::quit);
696 kill(); // waiting for thread shutdown
697 singleLock s(cache_lock);
698 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
699 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
703 void eEPGCache::gotMessage( const Message &msg )
708 flushEPG(msg.service);
710 case Message::startChannel:
712 singleLock s(channel_map_lock);
713 channelMapIterator channel =
714 m_knownChannels.find(msg.channel);
715 if ( channel != m_knownChannels.end() )
716 channel->second->startChannel();
719 case Message::leaveChannel:
721 singleLock s(channel_map_lock);
722 channelMapIterator channel =
723 m_knownChannels.find(msg.channel);
724 if ( channel != m_knownChannels.end() )
725 channel->second->abortEPG();
731 #ifdef ENABLE_PRIVATE_EPG
732 case Message::got_private_pid:
734 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
736 eDVBChannel *channel = (eDVBChannel*) it->first;
737 channel_data *data = it->second;
738 eDVBChannelID chid = channel->getChannelID();
739 if ( chid.transport_stream_id.get() == msg.service.tsid &&
740 chid.original_network_id.get() == msg.service.onid &&
741 data->m_PrivatePid == -1 )
743 data->m_PrevVersion = -1;
744 data->m_PrivatePid = msg.pid;
745 data->m_PrivateService = msg.service;
746 updateMap::iterator It = channelLastUpdated.find( channel->getChannelID() );
747 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
748 if (update < ZAP_DELAY)
750 data->startPrivateTimer.start(update, 1);
752 eDebug("[EPGC] next private update in %i min", update/60000);
753 else if (update >= 1000)
754 eDebug("[EPGC] next private update in %i sec", update/1000);
761 case Message::timeChanged:
765 eDebug("unhandled EPGCache Message!!");
770 void eEPGCache::thread()
780 void eEPGCache::load()
782 singleLock s(cache_lock);
783 FILE *f = fopen("/hdd/epg.dat", "r");
789 unsigned char md5_saved[16];
790 unsigned char md5[16];
793 if (!md5_file("/hdd/epg.dat", 1, md5))
795 FILE *f = fopen("/hdd/epg.dat.md5", "r");
798 fread( md5_saved, 16, 1, f);
800 if ( !memcmp(md5_saved, md5, 16) )
807 unsigned int magic=0;
808 fread( &magic, sizeof(int), 1, f);
809 if (magic != 0x98765432)
811 eDebug("epg file has incorrect byte order.. dont read it");
816 fread( text1, 13, 1, f);
817 if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
819 fread( &size, sizeof(int), 1, f);
826 fread( &key, sizeof(uniqueEPGKey), 1, f);
827 fread( &size, sizeof(int), 1, f);
833 fread( &type, sizeof(__u8), 1, f);
834 fread( &len, sizeof(__u8), 1, f);
835 event = new eventData(0, len, type);
836 event->EITdata = new __u8[len];
837 eventData::CacheSize+=len;
838 fread( event->EITdata, len, 1, f);
839 evMap[ event->getEventID() ]=event;
840 tmMap[ event->getStartTime() ]=event;
843 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
846 eDebug("%d events read from /hdd/epg.dat", cnt);
847 #ifdef ENABLE_PRIVATE_EPG
849 fread( text2, 11, 1, f);
850 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
853 fread( &size, sizeof(int), 1, f);
858 fread( &key, sizeof(uniqueEPGKey), 1, f);
859 eventMap &evMap=eventDB[key].first;
860 fread( &size, sizeof(int), 1, f);
865 fread( &content_id, sizeof(int), 1, f);
866 fread( &size, sizeof(int), 1, f);
871 fread( &time1, sizeof(time_t), 1, f);
872 fread( &time2, sizeof(time_t), 1, f);
873 fread( &event_id, sizeof(__u16), 1, f);
874 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
875 eventMap::iterator it =
876 evMap.find(event_id);
877 if (it != evMap.end())
878 it->second->type = PRIVATE;
883 #endif // ENABLE_PRIVATE_EPG
886 eDebug("[EPGC] don't read old epg database");
892 void eEPGCache::save()
896 if (statfs("/hdd", &s)<0)
904 // prevent writes to builtin flash
905 if ( tmp < 1024*1024*50 ) // storage size < 50MB
908 // check for enough free space on storage
911 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
914 FILE *f = fopen("/hdd/epg.dat", "w");
918 unsigned int magic = 0x98765432;
919 fwrite( &magic, sizeof(int), 1, f);
920 const char *text = "ENIGMA_EPG_V5";
921 fwrite( text, 13, 1, f );
922 int size = eventDB.size();
923 fwrite( &size, sizeof(int), 1, f );
924 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
926 timeMap &timemap = service_it->second.second;
927 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
928 size = timemap.size();
929 fwrite( &size, sizeof(int), 1, f);
930 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
932 __u8 len = time_it->second->ByteSize;
933 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
934 fwrite( &len, sizeof(__u8), 1, f);
935 fwrite( time_it->second->EITdata, len, 1, f);
939 eDebug("%d events written to /hdd/epg.dat", cnt);
941 #ifdef ENABLE_PRIVATE_EPG
942 const char* text3 = "PRIVATE_EPG";
943 fwrite( text3, 11, 1, f );
944 size = content_time_tables.size();
945 fwrite( &size, sizeof(int), 1, f);
946 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
948 contentMap &content_time_table = a->second;
949 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
950 int size = content_time_table.size();
951 fwrite( &size, sizeof(int), 1, f);
952 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
954 int size = i->second.size();
955 fwrite( &i->first, sizeof(int), 1, f);
956 fwrite( &size, sizeof(int), 1, f);
957 for ( contentTimeMap::iterator it(i->second.begin());
958 it != i->second.end(); ++it )
960 fwrite( &it->first, sizeof(time_t), 1, f);
961 fwrite( &it->second.first, sizeof(time_t), 1, f);
962 fwrite( &it->second.second, sizeof(__u16), 1, f);
969 unsigned char md5[16];
970 if (!md5_file("/hdd/epg.dat", 1, md5))
972 FILE *f = fopen("/hdd/epg.dat.md5", "w");
975 fwrite( md5, 16, 1, f);
983 eEPGCache::channel_data::channel_data(eEPGCache *ml)
985 ,abortTimer(ml), zapTimer(ml),state(0)
986 ,isRunning(0), haveData(0)
987 ,startPrivateTimer(ml)
989 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
990 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
991 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
994 bool eEPGCache::channel_data::finishEPG()
996 if (!isRunning) // epg ready
998 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
999 zapTimer.start(UPDATE_INTERVAL, 1);
1000 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1001 for (int i=0; i < 3; ++i)
1003 seenSections[i].clear();
1004 calcedSections[i].clear();
1006 singleLock l(cache->cache_lock);
1007 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1013 void eEPGCache::channel_data::startEPG()
1015 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1018 for (int i=0; i < 3; ++i)
1020 seenSections[i].clear();
1021 calcedSections[i].clear();
1024 eDVBSectionFilterMask mask;
1025 memset(&mask, 0, sizeof(mask));
1027 mask.flags = eDVBSectionFilterMask::rfCRC;
1029 mask.data[0] = 0x4E;
1030 mask.mask[0] = 0xFE;
1031 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1032 m_NowNextReader->start(mask);
1033 isRunning |= NOWNEXT;
1035 mask.data[0] = 0x50;
1036 mask.mask[0] = 0xF0;
1037 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1038 m_ScheduleReader->start(mask);
1039 isRunning |= SCHEDULE;
1041 mask.data[0] = 0x60;
1042 mask.mask[0] = 0xF0;
1043 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1044 m_ScheduleOtherReader->start(mask);
1045 isRunning |= SCHEDULE_OTHER;
1047 abortTimer.start(7000,true);
1050 void eEPGCache::channel_data::abortNonAvail()
1054 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1056 eDebug("[EPGC] abort non avail nownext reading");
1057 isRunning &= ~NOWNEXT;
1058 m_NowNextReader->stop();
1061 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1063 eDebug("[EPGC] abort non avail schedule reading");
1064 isRunning &= ~SCHEDULE;
1065 m_ScheduleReader->stop();
1068 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1070 eDebug("[EPGC] abort non avail schedule_other reading");
1071 isRunning &= ~SCHEDULE_OTHER;
1072 m_ScheduleOtherReader->stop();
1073 m_ScheduleOtherConn=0;
1076 abortTimer.start(90000, true);
1080 for (int i=0; i < 3; ++i)
1082 seenSections[i].clear();
1083 calcedSections[i].clear();
1090 void eEPGCache::channel_data::startChannel()
1092 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1094 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1096 if (update < ZAP_DELAY)
1099 zapTimer.start(update, 1);
1100 if (update >= 60000)
1101 eDebug("[EPGC] next update in %i min", update/60000);
1102 else if (update >= 1000)
1103 eDebug("[EPGC] next update in %i sec", update/1000);
1106 void eEPGCache::channel_data::abortEPG()
1108 for (int i=0; i < 3; ++i)
1110 seenSections[i].clear();
1111 calcedSections[i].clear();
1117 eDebug("[EPGC] abort caching events !!");
1118 if (isRunning & SCHEDULE)
1120 isRunning &= ~SCHEDULE;
1121 m_ScheduleReader->stop();
1124 if (isRunning & NOWNEXT)
1126 isRunning &= ~NOWNEXT;
1127 m_NowNextReader->stop();
1130 if (isRunning & SCHEDULE_OTHER)
1132 isRunning &= ~SCHEDULE_OTHER;
1133 m_ScheduleOtherReader->stop();
1134 m_ScheduleOtherConn=0;
1137 #ifdef ENABLE_PRIVATE_EPG
1138 if (m_PrivateReader)
1139 m_PrivateReader->stop();
1145 void eEPGCache::channel_data::readData( const __u8 *data)
1148 eDebug("get Null pointer from section reader !!");
1153 iDVBSectionReader *reader=NULL;
1157 reader=m_NowNextReader;
1162 reader=m_ScheduleReader;
1167 reader=m_ScheduleOtherReader;
1168 source=SCHEDULE_OTHER;
1172 eDebug("[EPGC] unknown table_id !!!");
1175 tidMap &seenSections = this->seenSections[map];
1176 tidMap &calcedSections = this->calcedSections[map];
1177 if ( state == 1 && calcedSections == seenSections || state > 1 )
1179 eDebugNoNewLine("[EPGC] ");
1184 eDebugNoNewLine("nownext");
1188 eDebugNoNewLine("schedule");
1190 case SCHEDULE_OTHER:
1191 m_ScheduleOtherConn=0;
1192 eDebugNoNewLine("schedule other");
1194 default: eDebugNoNewLine("unknown");break;
1196 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1199 isRunning &= ~source;
1205 eit_t *eit = (eit_t*) data;
1206 __u32 sectionNo = data[0] << 24;
1207 sectionNo |= data[3] << 16;
1208 sectionNo |= data[4] << 8;
1209 sectionNo |= eit->section_number;
1211 tidMap::iterator it =
1212 seenSections.find(sectionNo);
1214 if ( it == seenSections.end() )
1216 seenSections.insert(sectionNo);
1217 calcedSections.insert(sectionNo);
1218 __u32 tmpval = sectionNo & 0xFFFFFF00;
1219 __u8 incr = source == NOWNEXT ? 1 : 8;
1220 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1222 if ( i == eit->section_number )
1224 for (int x=i; x <= eit->segment_last_section_number; ++x)
1225 calcedSections.insert(tmpval|(x&0xFF));
1228 calcedSections.insert(tmpval|(i&0xFF));
1230 cache->sectionRead(data, source, this);
1236 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1237 // if t == -1 we search the current event...
1239 singleLock s(cache_lock);
1240 uniqueEPGKey key(service);
1242 // check if EPG for this service is ready...
1243 eventCache::iterator It = eventDB.find( key );
1244 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1247 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1248 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1249 It->second.second.upper_bound(t); // just >
1250 if ( i != It->second.second.end() )
1252 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1254 timeMap::iterator x = i;
1256 if ( x != It->second.second.end() )
1258 time_t start_time = x->second->getStartTime();
1263 if (t > (start_time+x->second->getDuration()))
1278 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1280 singleLock s(cache_lock);
1281 const eventData *data=0;
1282 RESULT ret = lookupEventTime(service, t, data, direction);
1284 result = data->get();
1288 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1290 singleLock s(cache_lock);
1291 const eventData *data=0;
1292 RESULT ret = lookupEventTime(service, t, data, direction);
1294 result = new Event((uint8_t*)data->get());
1298 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1300 singleLock s(cache_lock);
1301 const eventData *data=0;
1302 RESULT ret = lookupEventTime(service, t, data, direction);
1305 Event ev((uint8_t*)data->get());
1306 result = new eServiceEvent();
1307 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1308 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1313 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1315 singleLock s(cache_lock);
1316 uniqueEPGKey key( service );
1318 eventCache::iterator It = eventDB.find( key );
1319 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1321 eventMap::iterator i( It->second.first.find( event_id ));
1322 if ( i != It->second.first.end() )
1330 eDebug("event %04x not found in epgcache", event_id);
1336 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1338 singleLock s(cache_lock);
1339 const eventData *data=0;
1340 RESULT ret = lookupEventId(service, event_id, data);
1342 result = data->get();
1346 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1348 singleLock s(cache_lock);
1349 const eventData *data=0;
1350 RESULT ret = lookupEventId(service, event_id, data);
1352 result = new Event((uint8_t*)data->get());
1356 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1358 singleLock s(cache_lock);
1359 const eventData *data=0;
1360 RESULT ret = lookupEventId(service, event_id, data);
1363 Event ev((uint8_t*)data->get());
1364 result = new eServiceEvent();
1365 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1366 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1371 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1373 eventCache::iterator It = eventDB.find( service );
1374 if ( It != eventDB.end() && It->second.second.size() )
1376 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1379 m_timemap_cursor = It->second.second.lower_bound(begin);
1380 if ( m_timemap_cursor != It->second.second.end() )
1382 if ( m_timemap_cursor->second->getStartTime() != begin )
1384 timeMap::iterator x = m_timemap_cursor;
1386 if ( x != It->second.second.end() )
1388 time_t start_time = x->second->getStartTime();
1389 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1390 m_timemap_cursor = x;
1396 m_timemap_cursor = It->second.second.begin();
1397 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1398 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1404 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1406 if ( m_timemap_cursor != m_timemap_end )
1408 result = m_timemap_cursor++->second;
1414 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1416 if ( m_timemap_cursor != m_timemap_end )
1418 result = m_timemap_cursor++->second->get();
1424 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1426 if ( m_timemap_cursor != m_timemap_end )
1428 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1434 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1436 if ( m_timemap_cursor != m_timemap_end )
1438 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1439 result = new eServiceEvent();
1440 return result->parseFrom(&ev, currentQueryTsidOnid);
1445 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1449 while(pos < argcount)
1451 bool inc_refcount=false;
1452 switch(argstring[pos])
1454 case '0': // PyLong 0
1455 tmp = PyLong_FromLong(0);
1457 case 'I': // Event Id
1458 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1460 case 'B': // Event Begin Time
1461 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1463 case 'D': // Event Duration
1464 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1466 case 'T': // Event Title
1467 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1469 case 'S': // Event Short Description
1470 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1472 case 'E': // Event Extended Description
1473 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1475 case 'C': // Current Time
1477 inc_refcount = true;
1479 case 'R': // service reference string
1481 inc_refcount = true;
1483 case 'N': // service name
1485 inc_refcount = true;
1490 inc_refcount = true;
1494 PyTuple_SET_ITEM(tuple, pos++, tmp);
1498 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1502 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1503 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1507 Py_DECREF(service_name);
1510 Py_DECREF(convertFuncArgs);
1511 Py_DECREF(dest_list);
1514 PyList_Append(dest_list, result);
1519 PyObject *tuple = PyTuple_New(argcount);
1520 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1521 PyList_Append(dest_list, tuple);
1527 // here we get a python list
1528 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1531 // B = Event Begin Time
1532 // D = Event Duration
1534 // S = Event Short Description
1535 // E = Event Extended Description
1537 // R = Service Reference
1539 // then for each service follows a tuple
1540 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1541 // the second is the type of query
1543 // -1 = event before given start_time
1544 // 0 = event intersects given start_time
1545 // +1 = event after given start_time
1547 // when type is eventid it is the event_id
1548 // when type is time then it is the start_time ( 0 for now_time )
1549 // the fourth is the end_time .. ( optional .. for query all events in time range)
1551 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1553 PyObject *convertFuncArgs=NULL;
1555 char *argstring=NULL;
1556 if (!PyList_Check(list))
1558 PyErr_SetString(PyExc_StandardError,
1564 int listSize=PyList_Size(list);
1567 PyErr_SetString(PyExc_StandardError,
1568 "not params given");
1569 eDebug("not params given");
1574 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1575 if (PyString_Check(argv))
1577 argstring = PyString_AS_STRING(argv);
1581 argstring = "I"; // just event id as default
1582 argcount = strlen(argstring);
1583 // eDebug("have %d args('%s')", argcount, argstring);
1587 if (!PyCallable_Check(convertFunc))
1589 PyErr_SetString(PyExc_StandardError,
1590 "convertFunc must be callable");
1591 eDebug("convertFunc is not callable");
1594 convertFuncArgs = PyTuple_New(argcount);
1597 PyObject *nowTime = strchr(argstring, 'C') ?
1598 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1601 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1604 PyObject *dest_list=PyList_New(0);
1605 while(listSize > listIt)
1607 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1608 if (PyTuple_Check(item))
1610 bool service_changed=false;
1615 int tupleSize=PyTuple_Size(item);
1617 PyObject *service=NULL;
1618 while(tupleSize > tupleIt) // parse query args
1620 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1625 if (!PyString_Check(entry))
1627 eDebug("tuple entry 0 is no a string");
1634 type=PyInt_AsLong(entry);
1635 if (type < -1 || type > 2)
1637 eDebug("unknown type %d", type);
1642 event_id=stime=PyInt_AsLong(entry);
1645 minutes=PyInt_AsLong(entry);
1648 eDebug("unneeded extra argument");
1652 eServiceReference ref(PyString_AS_STRING(service));
1653 if (ref.type != eServiceReference::idDVB)
1655 eDebug("service reference for epg query is not valid");
1659 // redirect subservice querys to parent service
1660 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1661 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1663 eServiceCenterPtr service_center;
1664 if (!eServiceCenter::getPrivInstance(service_center))
1666 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1667 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1668 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1669 dvb_ref.setParentServiceID(eServiceID(0));
1671 service = PyString_FromString(dvb_ref.toString().c_str());
1672 service_changed = true;
1676 PyObject *service_name=NULL;
1677 if (must_get_service_name)
1679 ePtr<iStaticServiceInformation> sptr;
1680 eServiceCenterPtr service_center;
1681 eServiceCenter::getPrivInstance(service_center);
1684 service_center->info(ref, sptr);
1688 sptr->getName(ref, name);
1690 service_name = PyString_FromString(name.c_str());
1694 service_name = PyString_FromString("<n/a>");
1699 if (!startTimeQuery(ref, stime, minutes))
1701 ePtr<eServiceEvent> ptr;
1702 while (!getNextTimeEntry(ptr))
1704 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1713 ePtr<eServiceEvent> ptr;
1717 lookupEventId(ref, event_id, ptr);
1719 lookupEventTime(ref, stime, ptr, type);
1721 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1725 if (service_changed)
1728 Py_DECREF(service_name);
1733 if (convertFuncArgs)
1734 Py_DECREF(convertFuncArgs);
1740 void fillTuple2(PyObject *tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, PyObject *service_name, PyObject *service_reference)
1744 while(pos < argcount)
1746 bool inc_refcount=false;
1747 switch(argstring[pos])
1749 case '0': // PyLong 0
1750 tmp = PyLong_FromLong(0);
1752 case 'I': // Event Id
1753 tmp = PyLong_FromLong(evData->getEventID());
1755 case 'B': // Event Begin Time
1757 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1759 tmp = PyLong_FromLong(evData->getStartTime());
1761 case 'D': // Event Duration
1763 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1765 tmp = PyLong_FromLong(evData->getDuration());
1767 case 'T': // Event Title
1768 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1770 case 'S': // Event Short Description
1771 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1773 case 'E': // Event Extended Description
1774 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1776 case 'R': // service reference string
1777 tmp = service_reference;
1778 inc_refcount = true;
1780 case 'N': // service name
1782 inc_refcount = true;
1788 inc_refcount = true;
1792 PyTuple_SET_ITEM(tuple, pos++, tmp);
1796 // here we get a python tuple
1797 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1799 // B = Event Begin Time
1800 // D = Event Duration
1802 // S = Event Short Description
1803 // E = Event Extended Description
1804 // R = Service Reference
1806 // the second tuple entry is the MAX matches value
1807 // the third tuple entry is the type of query
1808 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1809 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1810 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1811 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1812 // the fourth is the servicereference string
1813 // the fifth is the eventid
1814 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1815 // the fourth is the search text
1817 // 0 = case sensitive (CASE_CHECK)
1818 // 1 = case insensitive (NO_CASECHECK)
1820 PyObject *eEPGCache::search(PyObject *arg)
1826 const char *argstring=0;
1830 bool needServiceEvent=false;
1833 if (PyTuple_Check(arg))
1835 int tuplesize=PyTuple_Size(arg);
1838 PyObject *obj = PyTuple_GET_ITEM(arg,0);
1839 if (PyString_Check(obj))
1841 argcount = PyString_GET_SIZE(obj);
1842 argstring = PyString_AS_STRING(obj);
1843 for (int i=0; i < argcount; ++i)
1844 switch(argstring[i])
1849 needServiceEvent=true;
1856 PyErr_SetString(PyExc_StandardError,
1858 eDebug("tuple arg 0 is not a string");
1863 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1866 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1867 if (tuplesize > 4 && querytype == 0)
1869 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1870 if (PyString_Check(obj))
1872 refstr = PyString_AS_STRING(obj);
1873 eServiceReferenceDVB ref(refstr);
1876 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1877 singleLock s(cache_lock);
1878 const eventData *evData = 0;
1879 lookupEventId(ref, eventid, evData);
1882 __u8 *data = evData->EITdata;
1883 int tmp = evData->ByteSize-12;
1884 __u32 *p = (__u32*)(data+12);
1885 // search short and extended event descriptors
1889 descriptorMap::iterator it =
1890 eventData::descriptors.find(crc);
1891 if (it != eventData::descriptors.end())
1893 __u8 *descr_data = it->second.second;
1894 switch(descr_data[0])
1897 descr[++descridx]=crc;
1906 eDebug("event not found");
1910 PyErr_SetString(PyExc_StandardError,
1912 eDebug("tuple arg 4 is not a valid service reference string");
1918 PyErr_SetString(PyExc_StandardError,
1920 eDebug("tuple arg 4 is not a string");
1924 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
1926 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1927 if (PyString_Check(obj))
1929 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1930 const char *str = PyString_AS_STRING(obj);
1931 int textlen = PyString_GET_SIZE(obj);
1933 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
1935 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
1936 singleLock s(cache_lock);
1937 for (descriptorMap::iterator it(eventData::descriptors.begin());
1938 it != eventData::descriptors.end() && descridx < 511; ++it)
1940 __u8 *data = it->second.second;
1941 if ( data[0] == 0x4D ) // short event descriptor
1943 int title_len = data[5];
1944 if ( querytype == 1 )
1946 if (title_len > textlen)
1948 else if (title_len < textlen)
1952 if ( !strncasecmp((const char*)data+6, str, title_len) )
1954 // std::string s((const char*)data+6, title_len);
1955 // eDebug("match1 %s %s", str, s.c_str() );
1956 descr[++descridx] = it->first;
1959 else if ( !strncmp((const char*)data+6, str, title_len) )
1961 // std::string s((const char*)data+6, title_len);
1962 // eDebug("match2 %s %s", str, s.c_str() );
1963 descr[++descridx] = it->first;
1969 while((title_len-idx) >= textlen)
1973 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
1975 descr[++descridx] = it->first;
1976 // std::string s((const char*)data+6, title_len);
1977 // eDebug("match 3 %s %s", str, s.c_str() );
1980 else if (!strncmp((const char*)data+6+idx, str, textlen) )
1982 descr[++descridx] = it->first;
1983 // std::string s((const char*)data+6, title_len);
1984 // eDebug("match 4 %s %s", str, s.c_str() );
1996 PyErr_SetString(PyExc_StandardError,
1998 eDebug("tuple arg 4 is not a string");
2004 PyErr_SetString(PyExc_StandardError,
2006 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2012 PyErr_SetString(PyExc_StandardError,
2014 eDebug("not enough args in tuple");
2020 PyErr_SetString(PyExc_StandardError,
2022 eDebug("arg 0 is not a tuple");
2028 int maxcount=maxmatches;
2029 eServiceReferenceDVB ref(refstr?refstr:"");
2030 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2031 // in this case we start searching with the base service
2032 bool first = ref.valid() ? true : false;
2033 singleLock s(cache_lock);
2034 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2035 while(cit != eventDB.end() && maxcount)
2037 if ( ref.valid() && !first && cit->first == ref )
2039 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2043 PyObject *service_name=0;
2044 PyObject *service_reference=0;
2045 timeMap &evmap = cit->second.second;
2047 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2049 if (evit->second->getEventID() == eventid)
2051 __u8 *data = evit->second->EITdata;
2052 int tmp = evit->second->ByteSize-12;
2053 __u32 *p = (__u32*)(data+12);
2054 // check if any of our descriptor used by this event
2059 for ( int i=0; i <= descridx; ++i)
2061 if (descr[i] == crc32) // found...
2066 if ( (querytype == 0 && cnt == descridx) ||
2067 ((querytype == 1 || querytype == 2) && cnt != -1) )
2069 const uniqueEPGKey &service = cit->first;
2070 eServiceReference ref =
2071 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2074 // create servive event
2075 ePtr<eServiceEvent> ptr;
2076 if (needServiceEvent)
2078 lookupEventId(ref, evit->first, ptr);
2080 eDebug("event not found !!!!!!!!!!!");
2082 // create service name
2083 if (!service_name && strchr(argstring,'N'))
2085 ePtr<iStaticServiceInformation> sptr;
2086 eServiceCenterPtr service_center;
2087 eServiceCenter::getPrivInstance(service_center);
2090 service_center->info(ref, sptr);
2094 sptr->getName(ref, name);
2096 service_name = PyString_FromString(name.c_str());
2100 service_name = PyString_FromString("<n/a>");
2102 // create servicereference string
2103 if (!service_reference && strchr(argstring,'R'))
2104 service_reference = PyString_FromString(ref.toString().c_str());
2107 ret = PyList_New(0);
2109 PyObject *tuple = PyTuple_New(argcount);
2111 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2112 PyList_Append(ret, tuple);
2119 Py_DECREF(service_name);
2120 if (service_reference)
2121 Py_DECREF(service_reference);
2124 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2126 cit=eventDB.begin();
2142 #ifdef ENABLE_PRIVATE_EPG
2143 #include <dvbsi++/descriptor_tag.h>
2144 #include <dvbsi++/unknown_descriptor.h>
2145 #include <dvbsi++/private_data_specifier_descriptor.h>
2147 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2149 ePtr<eTable<ProgramMapSection> > ptr;
2150 if (!pmthandler->getPMT(ptr) && ptr)
2152 std::vector<ProgramMapSection*>::const_iterator i;
2153 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2155 const ProgramMapSection &pmt = **i;
2157 ElementaryStreamInfoConstIterator es;
2158 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2161 switch ((*es)->getType())
2163 case 0x05: // private
2164 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2165 desc != (*es)->getDescriptors()->end(); ++desc)
2167 switch ((*desc)->getTag())
2169 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2170 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2175 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2176 int descr_len = descr->getLength();
2179 uint8_t data[descr_len+2];
2180 descr->writeToBuffer(data);
2181 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2195 eServiceReferenceDVB ref;
2196 if (!pmthandler->getServiceReference(ref))
2198 int pid = (*es)->getPid();
2199 messages.send(Message(Message::got_private_pid, ref, pid));
2207 eDebug("PMTready but no pmt!!");
2214 date_time( const date_time &a )
2216 memcpy(data, a.data, 5);
2219 date_time( const __u8 data[5])
2221 memcpy(this->data, data, 5);
2222 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2227 const __u8& operator[](int pos) const
2233 struct less_datetime
2235 bool operator()( const date_time &a, const date_time &b ) const
2237 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2241 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2243 contentMap &content_time_table = content_time_tables[current_service];
2244 singleLock s(cache_lock);
2245 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2246 eventMap &evMap = eventDB[current_service].first;
2247 timeMap &tmMap = eventDB[current_service].second;
2249 int content_id = data[ptr++] << 24;
2250 content_id |= data[ptr++] << 16;
2251 content_id |= data[ptr++] << 8;
2252 content_id |= data[ptr++];
2254 contentTimeMap &time_event_map =
2255 content_time_table[content_id];
2256 for ( contentTimeMap::iterator it( time_event_map.begin() );
2257 it != time_event_map.end(); ++it )
2259 eventMap::iterator evIt( evMap.find(it->second.second) );
2260 if ( evIt != evMap.end() )
2262 delete evIt->second;
2265 tmMap.erase(it->second.first);
2267 time_event_map.clear();
2270 memcpy(duration, data+ptr, 3);
2273 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2275 const __u8 *descriptors[65];
2276 const __u8 **pdescr = descriptors;
2278 int descriptors_length = (data[ptr++]&0x0F) << 8;
2279 descriptors_length |= data[ptr++];
2280 while ( descriptors_length > 0 )
2282 int descr_type = data[ptr];
2283 int descr_len = data[ptr+1];
2284 descriptors_length -= (descr_len+2);
2285 if ( descr_type == 0xf2 )
2288 int tsid = data[ptr++] << 8;
2289 tsid |= data[ptr++];
2290 int onid = data[ptr++] << 8;
2291 onid |= data[ptr++];
2292 int sid = data[ptr++] << 8;
2295 // WORKAROUND for wrong transmitted epg data
2296 if ( onid == 0x85 && tsid == 0x11 && sid == 0xd3 ) // premiere sends wrong tsid here
2298 else if ( onid == 0x85 && tsid == 0x3 && sid == 0xf5 ) // premiere sends wrong sid here
2300 ////////////////////////////////////////////
2302 uniqueEPGKey service( sid, onid, tsid );
2304 while( descr_len > 0 )
2307 datetime[0] = data[ptr++];
2308 datetime[1] = data[ptr++];
2309 int tmp_len = data[ptr++];
2311 while( tmp_len > 0 )
2313 memcpy(datetime+2, data+ptr, 3);
2317 start_times[datetime].push_back(service);
2329 eit_event_struct *ev_struct = (eit_event_struct*) event;
2330 ev_struct->running_status = 0;
2331 ev_struct->free_CA_mode = 1;
2332 memcpy(event+7, duration, 3);
2334 const __u8 **d=descriptors;
2335 while ( d < pdescr )
2337 memcpy(event+ptr, *d, ((*d)[1])+2);
2341 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2343 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2344 if ( (it->first.tm + duration_sec) < now )
2346 memcpy(event+2, it->first.data, 5);
2349 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2351 event[bptr++] = 0x4A;
2352 __u8 *len = event+(bptr++);
2353 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2354 event[bptr++] = (i->tsid & 0xFF);
2355 event[bptr++] = (i->onid & 0xFF00) >> 8;
2356 event[bptr++] = (i->onid & 0xFF);
2357 event[bptr++] = (i->sid & 0xFF00) >> 8;
2358 event[bptr++] = (i->sid & 0xFF);
2359 event[bptr++] = 0xB0;
2360 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2361 *len = ((event+bptr) - len)-1;
2363 int llen = bptr - 12;
2364 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2365 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2367 time_t stime = it->first.tm;
2368 while( tmMap.find(stime) != tmMap.end() )
2370 event[6] += (stime - it->first.tm);
2372 while( evMap.find(event_id) != evMap.end() )
2374 event[0] = (event_id & 0xFF00) >> 8;
2375 event[1] = (event_id & 0xFF);
2376 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2377 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2378 evMap[event_id] = d;
2383 void eEPGCache::channel_data::startPrivateReader()
2385 eDVBSectionFilterMask mask;
2386 memset(&mask, 0, sizeof(mask));
2387 mask.pid = m_PrivatePid;
2388 mask.flags = eDVBSectionFilterMask::rfCRC;
2389 mask.data[0] = 0xA0;
2390 mask.mask[0] = 0xFF;
2391 eDebug("start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2392 if (m_PrevVersion != -1)
2394 mask.data[3] = m_PrevVersion << 1;
2395 mask.mask[3] = 0x3E;
2396 mask.mode[3] = 0x3E;
2398 seenPrivateSections.clear();
2400 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2401 m_PrivateReader->start(mask);
2404 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2407 eDebug("get Null pointer from section reader !!");
2410 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2412 cache->privateSectionRead(m_PrivateService, data);
2413 seenPrivateSections.insert(data[6]);
2415 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2417 eDebug("[EPGC] private finished");
2418 m_PrevVersion = (data[5] & 0x3E) >> 1;
2419 startPrivateReader();
2424 #endif // ENABLE_PRIVATE_EPG