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->can_delete)
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 = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
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 = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
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 - ( (time(0)+eDVBLocalTimeHandler::getInstance()->difference()-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), can_delete(1)
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)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
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()] = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
1008 #ifdef ENABLE_PRIVATE_EPG
1009 if (seenPrivateSections.empty())
1017 void eEPGCache::channel_data::startEPG()
1019 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->difference()+time(0));
1023 for (int i=0; i < 3; ++i)
1025 seenSections[i].clear();
1026 calcedSections[i].clear();
1029 eDVBSectionFilterMask mask;
1030 memset(&mask, 0, sizeof(mask));
1032 mask.flags = eDVBSectionFilterMask::rfCRC;
1034 mask.data[0] = 0x4E;
1035 mask.mask[0] = 0xFE;
1036 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1037 m_NowNextReader->start(mask);
1038 isRunning |= NOWNEXT;
1040 mask.data[0] = 0x50;
1041 mask.mask[0] = 0xF0;
1042 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1043 m_ScheduleReader->start(mask);
1044 isRunning |= SCHEDULE;
1046 mask.data[0] = 0x60;
1047 mask.mask[0] = 0xF0;
1048 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1049 m_ScheduleOtherReader->start(mask);
1050 isRunning |= SCHEDULE_OTHER;
1052 abortTimer.start(7000,true);
1055 void eEPGCache::channel_data::abortNonAvail()
1059 if ( !(haveData&eEPGCache::NOWNEXT) && (isRunning&eEPGCache::NOWNEXT) )
1061 eDebug("[EPGC] abort non avail nownext reading");
1062 isRunning &= ~eEPGCache::NOWNEXT;
1063 m_NowNextReader->stop();
1066 if ( !(haveData&eEPGCache::SCHEDULE) && (isRunning&eEPGCache::SCHEDULE) )
1068 eDebug("[EPGC] abort non avail schedule reading");
1069 isRunning &= ~SCHEDULE;
1070 m_ScheduleReader->stop();
1073 if ( !(haveData&eEPGCache::SCHEDULE_OTHER) && (isRunning&eEPGCache::SCHEDULE_OTHER) )
1075 eDebug("[EPGC] abort non avail schedule_other reading");
1076 isRunning &= ~SCHEDULE_OTHER;
1077 m_ScheduleOtherReader->stop();
1078 m_ScheduleOtherConn=0;
1081 abortTimer.start(90000, true);
1085 for (int i=0; i < 3; ++i)
1087 seenSections[i].clear();
1088 calcedSections[i].clear();
1090 #ifdef ENABLE_PRIVATE_EPG
1091 if (seenPrivateSections.empty())
1099 void eEPGCache::channel_data::startChannel()
1101 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1103 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (time(0)+eDVBLocalTimeHandler::getInstance()->difference()-It->second) * 1000 ) ) : ZAP_DELAY );
1105 if (update < ZAP_DELAY)
1108 zapTimer.start(update, 1);
1109 if (update >= 60000)
1110 eDebug("[EPGC] next update in %i min", update/60000);
1111 else if (update >= 1000)
1112 eDebug("[EPGC] next update in %i sec", update/1000);
1115 void eEPGCache::channel_data::abortEPG()
1117 for (int i=0; i < 3; ++i)
1119 seenSections[i].clear();
1120 calcedSections[i].clear();
1126 eDebug("[EPGC] abort caching events !!");
1127 if (isRunning & eEPGCache::SCHEDULE)
1129 isRunning &= ~eEPGCache::SCHEDULE;
1130 m_ScheduleReader->stop();
1133 if (isRunning & eEPGCache::NOWNEXT)
1135 isRunning &= ~eEPGCache::NOWNEXT;
1136 m_NowNextReader->stop();
1139 if (isRunning & SCHEDULE_OTHER)
1141 isRunning &= ~eEPGCache::SCHEDULE_OTHER;
1142 m_ScheduleOtherReader->stop();
1143 m_ScheduleOtherConn=0;
1146 #ifdef ENABLE_PRIVATE_EPG
1147 if (m_PrivateReader)
1148 m_PrivateReader->stop();
1155 void eEPGCache::channel_data::readData( const __u8 *data)
1158 eDebug("get Null pointer from section reader !!");
1163 iDVBSectionReader *reader=NULL;
1167 reader=m_NowNextReader;
1168 source=eEPGCache::NOWNEXT;
1172 reader=m_ScheduleReader;
1173 source=eEPGCache::SCHEDULE;
1177 reader=m_ScheduleOtherReader;
1178 source=eEPGCache::SCHEDULE_OTHER;
1182 eDebug("[EPGC] unknown table_id !!!");
1185 tidMap &seenSections = this->seenSections[map];
1186 tidMap &calcedSections = this->calcedSections[map];
1187 if ( state == 1 && calcedSections == seenSections || state > 1 )
1189 eDebugNoNewLine("[EPGC] ");
1192 case eEPGCache::NOWNEXT:
1194 eDebugNoNewLine("nownext");
1196 case eEPGCache::SCHEDULE:
1198 eDebugNoNewLine("schedule");
1200 case eEPGCache::SCHEDULE_OTHER:
1201 m_ScheduleOtherConn=0;
1202 eDebugNoNewLine("schedule other");
1204 default: eDebugNoNewLine("unknown");break;
1206 eDebug(" finished(%ld)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
1209 isRunning &= ~source;
1215 eit_t *eit = (eit_t*) data;
1216 __u32 sectionNo = data[0] << 24;
1217 sectionNo |= data[3] << 16;
1218 sectionNo |= data[4] << 8;
1219 sectionNo |= eit->section_number;
1221 tidMap::iterator it =
1222 seenSections.find(sectionNo);
1224 if ( it == seenSections.end() )
1226 seenSections.insert(sectionNo);
1227 calcedSections.insert(sectionNo);
1228 __u32 tmpval = sectionNo & 0xFFFFFF00;
1229 __u8 incr = source == NOWNEXT ? 1 : 8;
1230 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1232 if ( i == eit->section_number )
1234 for (int x=i; x <= eit->segment_last_section_number; ++x)
1235 calcedSections.insert(tmpval|(x&0xFF));
1238 calcedSections.insert(tmpval|(i&0xFF));
1240 cache->sectionRead(data, source, this);
1246 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1247 // if t == -1 we search the current event...
1249 singleLock s(cache_lock);
1250 uniqueEPGKey key(service);
1252 // check if EPG for this service is ready...
1253 eventCache::iterator It = eventDB.find( key );
1254 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1257 t = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
1258 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1259 It->second.second.upper_bound(t); // just >
1260 if ( i != It->second.second.end() )
1262 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1264 timeMap::iterator x = i;
1266 if ( x != It->second.second.end() )
1268 time_t start_time = x->second->getStartTime();
1273 if (t > (start_time+x->second->getDuration()))
1288 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1290 singleLock s(cache_lock);
1291 const eventData *data=0;
1292 RESULT ret = lookupEventTime(service, t, data, direction);
1294 result = data->get();
1298 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1300 singleLock s(cache_lock);
1301 const eventData *data=0;
1302 RESULT ret = lookupEventTime(service, t, data, direction);
1304 result = new Event((uint8_t*)data->get());
1308 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1310 singleLock s(cache_lock);
1311 const eventData *data=0;
1312 RESULT ret = lookupEventTime(service, t, data, direction);
1315 Event ev((uint8_t*)data->get());
1316 result = new eServiceEvent();
1317 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1318 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1323 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1325 singleLock s(cache_lock);
1326 uniqueEPGKey key( service );
1328 eventCache::iterator It = eventDB.find( key );
1329 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1331 eventMap::iterator i( It->second.first.find( event_id ));
1332 if ( i != It->second.first.end() )
1340 eDebug("event %04x not found in epgcache", event_id);
1346 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1348 singleLock s(cache_lock);
1349 const eventData *data=0;
1350 RESULT ret = lookupEventId(service, event_id, data);
1352 result = data->get();
1356 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1358 singleLock s(cache_lock);
1359 const eventData *data=0;
1360 RESULT ret = lookupEventId(service, event_id, data);
1362 result = new Event((uint8_t*)data->get());
1366 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1368 singleLock s(cache_lock);
1369 const eventData *data=0;
1370 RESULT ret = lookupEventId(service, event_id, data);
1373 Event ev((uint8_t*)data->get());
1374 result = new eServiceEvent();
1375 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1376 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1381 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1383 eventCache::iterator It = eventDB.find( service );
1384 if ( It != eventDB.end() && It->second.second.size() )
1386 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1389 m_timemap_cursor = It->second.second.lower_bound(begin);
1390 if ( m_timemap_cursor != It->second.second.end() )
1392 if ( m_timemap_cursor->second->getStartTime() != begin )
1394 timeMap::iterator x = m_timemap_cursor;
1396 if ( x != It->second.second.end() )
1398 time_t start_time = x->second->getStartTime();
1399 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1400 m_timemap_cursor = x;
1406 m_timemap_cursor = It->second.second.begin();
1407 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1408 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1414 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1416 if ( m_timemap_cursor != m_timemap_end )
1418 result = m_timemap_cursor++->second;
1424 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1426 if ( m_timemap_cursor != m_timemap_end )
1428 result = m_timemap_cursor++->second->get();
1434 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1436 if ( m_timemap_cursor != m_timemap_end )
1438 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1444 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1446 if ( m_timemap_cursor != m_timemap_end )
1448 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1449 result = new eServiceEvent();
1450 return result->parseFrom(&ev, currentQueryTsidOnid);
1455 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1459 while(pos < argcount)
1461 bool inc_refcount=false;
1462 switch(argstring[pos])
1464 case '0': // PyLong 0
1465 tmp = PyLong_FromLong(0);
1467 case 'I': // Event Id
1468 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1470 case 'B': // Event Begin Time
1471 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1473 case 'D': // Event Duration
1474 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1476 case 'T': // Event Title
1477 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1479 case 'S': // Event Short Description
1480 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1482 case 'E': // Event Extended Description
1483 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1485 case 'C': // Current Time
1487 inc_refcount = true;
1489 case 'R': // service reference string
1491 inc_refcount = true;
1493 case 'N': // service name
1495 inc_refcount = true;
1500 inc_refcount = true;
1504 PyTuple_SET_ITEM(tuple, pos++, tmp);
1508 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1512 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1513 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1517 Py_DECREF(service_name);
1520 Py_DECREF(convertFuncArgs);
1521 Py_DECREF(dest_list);
1524 PyList_Append(dest_list, result);
1529 PyObject *tuple = PyTuple_New(argcount);
1530 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1531 PyList_Append(dest_list, tuple);
1537 // here we get a python list
1538 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1541 // B = Event Begin Time
1542 // D = Event Duration
1544 // S = Event Short Description
1545 // E = Event Extended Description
1547 // R = Service Reference
1549 // then for each service follows a tuple
1550 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1551 // the second is the type of query
1553 // -1 = event before given start_time
1554 // 0 = event intersects given start_time
1555 // +1 = event after given start_time
1557 // when type is eventid it is the event_id
1558 // when type is time then it is the start_time ( 0 for now_time )
1559 // the fourth is the end_time .. ( optional .. for query all events in time range)
1561 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1563 PyObject *convertFuncArgs=NULL;
1565 char *argstring=NULL;
1566 if (!PyList_Check(list))
1568 PyErr_SetString(PyExc_StandardError,
1574 int listSize=PyList_Size(list);
1577 PyErr_SetString(PyExc_StandardError,
1578 "not params given");
1579 eDebug("not params given");
1584 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1585 if (PyString_Check(argv))
1587 argstring = PyString_AS_STRING(argv);
1591 argstring = "I"; // just event id as default
1592 argcount = strlen(argstring);
1593 // eDebug("have %d args('%s')", argcount, argstring);
1597 if (!PyCallable_Check(convertFunc))
1599 PyErr_SetString(PyExc_StandardError,
1600 "convertFunc must be callable");
1601 eDebug("convertFunc is not callable");
1604 convertFuncArgs = PyTuple_New(argcount);
1607 PyObject *nowTime = strchr(argstring, 'C') ?
1608 PyLong_FromLong(time(0)+eDVBLocalTimeHandler::getInstance()->difference()) :
1611 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1614 PyObject *dest_list=PyList_New(0);
1615 while(listSize > listIt)
1617 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1618 if (PyTuple_Check(item))
1620 bool service_changed=false;
1625 int tupleSize=PyTuple_Size(item);
1627 PyObject *service=NULL;
1628 while(tupleSize > tupleIt) // parse query args
1630 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1635 if (!PyString_Check(entry))
1637 eDebug("tuple entry 0 is no a string");
1644 type=PyInt_AsLong(entry);
1645 if (type < -1 || type > 2)
1647 eDebug("unknown type %d", type);
1652 event_id=stime=PyInt_AsLong(entry);
1655 minutes=PyInt_AsLong(entry);
1658 eDebug("unneeded extra argument");
1662 eServiceReference ref(PyString_AS_STRING(service));
1663 if (ref.type != eServiceReference::idDVB)
1665 eDebug("service reference for epg query is not valid");
1669 // redirect subservice querys to parent service
1670 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1671 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1673 eServiceCenterPtr service_center;
1674 if (!eServiceCenter::getPrivInstance(service_center))
1676 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1677 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1678 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1679 dvb_ref.setParentServiceID(eServiceID(0));
1681 service = PyString_FromString(dvb_ref.toString().c_str());
1682 service_changed = true;
1686 PyObject *service_name=NULL;
1687 if (must_get_service_name)
1689 ePtr<iStaticServiceInformation> sptr;
1690 eServiceCenterPtr service_center;
1691 eServiceCenter::getPrivInstance(service_center);
1694 service_center->info(ref, sptr);
1698 sptr->getName(ref, name);
1700 service_name = PyString_FromString(name.c_str());
1704 service_name = PyString_FromString("<n/a>");
1709 if (!startTimeQuery(ref, stime, minutes))
1711 ePtr<eServiceEvent> ptr;
1712 while (!getNextTimeEntry(ptr))
1714 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1723 ePtr<eServiceEvent> ptr;
1727 lookupEventId(ref, event_id, ptr);
1729 lookupEventTime(ref, stime, ptr, type);
1731 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1735 if (service_changed)
1738 Py_DECREF(service_name);
1743 if (convertFuncArgs)
1744 Py_DECREF(convertFuncArgs);
1750 void fillTuple2(PyObject *tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, PyObject *service_name, PyObject *service_reference)
1754 while(pos < argcount)
1756 bool inc_refcount=false;
1757 switch(argstring[pos])
1759 case '0': // PyLong 0
1760 tmp = PyLong_FromLong(0);
1762 case 'I': // Event Id
1763 tmp = PyLong_FromLong(evData->getEventID());
1765 case 'B': // Event Begin Time
1767 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1769 tmp = PyLong_FromLong(evData->getStartTime());
1771 case 'D': // Event Duration
1773 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1775 tmp = PyLong_FromLong(evData->getDuration());
1777 case 'T': // Event Title
1778 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1780 case 'S': // Event Short Description
1781 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1783 case 'E': // Event Extended Description
1784 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1786 case 'R': // service reference string
1787 tmp = service_reference;
1788 inc_refcount = true;
1790 case 'N': // service name
1792 inc_refcount = true;
1798 inc_refcount = true;
1802 PyTuple_SET_ITEM(tuple, pos++, tmp);
1806 // here we get a python tuple
1807 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1809 // B = Event Begin Time
1810 // D = Event Duration
1812 // S = Event Short Description
1813 // E = Event Extended Description
1814 // R = Service Reference
1816 // the second tuple entry is the MAX matches value
1817 // the third tuple entry is the type of query
1818 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1819 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1820 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1821 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1822 // the fourth is the servicereference string
1823 // the fifth is the eventid
1824 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1825 // the fourth is the search text
1827 // 0 = case sensitive (CASE_CHECK)
1828 // 1 = case insensitive (NO_CASECHECK)
1830 PyObject *eEPGCache::search(PyObject *arg)
1836 const char *argstring=0;
1840 bool needServiceEvent=false;
1843 if (PyTuple_Check(arg))
1845 int tuplesize=PyTuple_Size(arg);
1848 PyObject *obj = PyTuple_GET_ITEM(arg,0);
1849 if (PyString_Check(obj))
1851 argcount = PyString_GET_SIZE(obj);
1852 argstring = PyString_AS_STRING(obj);
1853 for (int i=0; i < argcount; ++i)
1854 switch(argstring[i])
1859 needServiceEvent=true;
1866 PyErr_SetString(PyExc_StandardError,
1868 eDebug("tuple arg 0 is not a string");
1873 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1876 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1877 if (tuplesize > 4 && querytype == 0)
1879 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1880 if (PyString_Check(obj))
1882 refstr = PyString_AS_STRING(obj);
1883 eServiceReferenceDVB ref(refstr);
1886 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1887 singleLock s(cache_lock);
1888 const eventData *evData = 0;
1889 lookupEventId(ref, eventid, evData);
1892 __u8 *data = evData->EITdata;
1893 int tmp = evData->ByteSize-12;
1894 __u32 *p = (__u32*)(data+12);
1895 // search short and extended event descriptors
1899 descriptorMap::iterator it =
1900 eventData::descriptors.find(crc);
1901 if (it != eventData::descriptors.end())
1903 __u8 *descr_data = it->second.second;
1904 switch(descr_data[0])
1907 descr[++descridx]=crc;
1916 eDebug("event not found");
1920 PyErr_SetString(PyExc_StandardError,
1922 eDebug("tuple arg 4 is not a valid service reference string");
1928 PyErr_SetString(PyExc_StandardError,
1930 eDebug("tuple arg 4 is not a string");
1934 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
1936 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1937 if (PyString_Check(obj))
1939 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1940 const char *str = PyString_AS_STRING(obj);
1941 int textlen = PyString_GET_SIZE(obj);
1943 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
1945 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
1946 singleLock s(cache_lock);
1947 for (descriptorMap::iterator it(eventData::descriptors.begin());
1948 it != eventData::descriptors.end() && descridx < 511; ++it)
1950 __u8 *data = it->second.second;
1951 if ( data[0] == 0x4D ) // short event descriptor
1953 int title_len = data[5];
1954 if ( querytype == 1 )
1956 if (title_len > textlen)
1958 else if (title_len < textlen)
1962 if ( !strncasecmp((const char*)data+6, str, title_len) )
1964 // std::string s((const char*)data+6, title_len);
1965 // eDebug("match1 %s %s", str, s.c_str() );
1966 descr[++descridx] = it->first;
1969 else if ( !strncmp((const char*)data+6, str, title_len) )
1971 // std::string s((const char*)data+6, title_len);
1972 // eDebug("match2 %s %s", str, s.c_str() );
1973 descr[++descridx] = it->first;
1979 while((title_len-idx) >= textlen)
1983 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
1985 descr[++descridx] = it->first;
1986 // std::string s((const char*)data+6, title_len);
1987 // eDebug("match 3 %s %s", str, s.c_str() );
1990 else if (!strncmp((const char*)data+6+idx, str, textlen) )
1992 descr[++descridx] = it->first;
1993 // std::string s((const char*)data+6, title_len);
1994 // eDebug("match 4 %s %s", str, s.c_str() );
2006 PyErr_SetString(PyExc_StandardError,
2008 eDebug("tuple arg 4 is not a string");
2014 PyErr_SetString(PyExc_StandardError,
2016 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2022 PyErr_SetString(PyExc_StandardError,
2024 eDebug("not enough args in tuple");
2030 PyErr_SetString(PyExc_StandardError,
2032 eDebug("arg 0 is not a tuple");
2038 int maxcount=maxmatches;
2039 eServiceReferenceDVB ref(refstr?refstr:"");
2040 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2041 // in this case we start searching with the base service
2042 bool first = ref.valid() ? true : false;
2043 singleLock s(cache_lock);
2044 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2045 while(cit != eventDB.end() && maxcount)
2047 if ( ref.valid() && !first && cit->first == ref )
2049 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2053 PyObject *service_name=0;
2054 PyObject *service_reference=0;
2055 timeMap &evmap = cit->second.second;
2057 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2059 if (evit->second->getEventID() == eventid)
2061 __u8 *data = evit->second->EITdata;
2062 int tmp = evit->second->ByteSize-12;
2063 __u32 *p = (__u32*)(data+12);
2064 // check if any of our descriptor used by this event
2069 for ( int i=0; i <= descridx; ++i)
2071 if (descr[i] == crc32) // found...
2076 if ( (querytype == 0 && cnt == descridx) ||
2077 ((querytype == 1 || querytype == 2) && cnt != -1) )
2079 const uniqueEPGKey &service = cit->first;
2080 eServiceReference ref =
2081 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2084 // create servive event
2085 ePtr<eServiceEvent> ptr;
2086 if (needServiceEvent)
2088 lookupEventId(ref, evit->first, ptr);
2090 eDebug("event not found !!!!!!!!!!!");
2092 // create service name
2093 if (!service_name && strchr(argstring,'N'))
2095 ePtr<iStaticServiceInformation> sptr;
2096 eServiceCenterPtr service_center;
2097 eServiceCenter::getPrivInstance(service_center);
2100 service_center->info(ref, sptr);
2104 sptr->getName(ref, name);
2106 service_name = PyString_FromString(name.c_str());
2110 service_name = PyString_FromString("<n/a>");
2112 // create servicereference string
2113 if (!service_reference && strchr(argstring,'R'))
2114 service_reference = PyString_FromString(ref.toString().c_str());
2117 ret = PyList_New(0);
2119 PyObject *tuple = PyTuple_New(argcount);
2121 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2122 PyList_Append(ret, tuple);
2129 Py_DECREF(service_name);
2130 if (service_reference)
2131 Py_DECREF(service_reference);
2134 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2136 cit=eventDB.begin();
2152 #ifdef ENABLE_PRIVATE_EPG
2153 #include <dvbsi++/descriptor_tag.h>
2154 #include <dvbsi++/unknown_descriptor.h>
2155 #include <dvbsi++/private_data_specifier_descriptor.h>
2157 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2159 ePtr<eTable<ProgramMapSection> > ptr;
2160 if (!pmthandler->getPMT(ptr) && ptr)
2162 std::vector<ProgramMapSection*>::const_iterator i;
2163 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2165 const ProgramMapSection &pmt = **i;
2167 ElementaryStreamInfoConstIterator es;
2168 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2171 switch ((*es)->getType())
2173 case 0x05: // private
2174 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2175 desc != (*es)->getDescriptors()->end(); ++desc)
2177 switch ((*desc)->getTag())
2179 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2180 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2185 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2186 int descr_len = descr->getLength();
2189 uint8_t data[descr_len+2];
2190 descr->writeToBuffer(data);
2191 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2205 eServiceReferenceDVB ref;
2206 if (!pmthandler->getServiceReference(ref))
2208 int pid = (*es)->getPid();
2209 messages.send(Message(Message::got_private_pid, ref, pid));
2217 eDebug("PMTready but no pmt!!");
2224 date_time( const date_time &a )
2226 memcpy(data, a.data, 5);
2229 date_time( const __u8 data[5])
2231 memcpy(this->data, data, 5);
2232 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2237 const __u8& operator[](int pos) const
2243 struct less_datetime
2245 bool operator()( const date_time &a, const date_time &b ) const
2247 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2251 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2253 contentMap &content_time_table = content_time_tables[current_service];
2254 singleLock s(cache_lock);
2255 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2256 eventMap &evMap = eventDB[current_service].first;
2257 timeMap &tmMap = eventDB[current_service].second;
2259 int content_id = data[ptr++] << 24;
2260 content_id |= data[ptr++] << 16;
2261 content_id |= data[ptr++] << 8;
2262 content_id |= data[ptr++];
2264 contentTimeMap &time_event_map =
2265 content_time_table[content_id];
2266 for ( contentTimeMap::iterator it( time_event_map.begin() );
2267 it != time_event_map.end(); ++it )
2269 eventMap::iterator evIt( evMap.find(it->second.second) );
2270 if ( evIt != evMap.end() )
2272 delete evIt->second;
2275 tmMap.erase(it->second.first);
2277 time_event_map.clear();
2280 memcpy(duration, data+ptr, 3);
2283 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2285 const __u8 *descriptors[65];
2286 const __u8 **pdescr = descriptors;
2288 int descriptors_length = (data[ptr++]&0x0F) << 8;
2289 descriptors_length |= data[ptr++];
2290 while ( descriptors_length > 0 )
2292 int descr_type = data[ptr];
2293 int descr_len = data[ptr+1];
2294 descriptors_length -= (descr_len+2);
2295 if ( descr_type == 0xf2 )
2298 int tsid = data[ptr++] << 8;
2299 tsid |= data[ptr++];
2300 int onid = data[ptr++] << 8;
2301 onid |= data[ptr++];
2302 int sid = data[ptr++] << 8;
2305 // WORKAROUND for wrong transmitted epg data
2306 if ( onid == 0x85 && tsid == 0x11 && sid == 0xd3 ) // premiere sends wrong tsid here
2308 else if ( onid == 0x85 && tsid == 0x3 && sid == 0xf5 ) // premiere sends wrong sid here
2310 ////////////////////////////////////////////
2312 uniqueEPGKey service( sid, onid, tsid );
2314 while( descr_len > 0 )
2317 datetime[0] = data[ptr++];
2318 datetime[1] = data[ptr++];
2319 int tmp_len = data[ptr++];
2321 while( tmp_len > 0 )
2323 memcpy(datetime+2, data+ptr, 3);
2327 start_times[datetime].push_back(service);
2339 eit_event_struct *ev_struct = (eit_event_struct*) event;
2340 ev_struct->running_status = 0;
2341 ev_struct->free_CA_mode = 1;
2342 memcpy(event+7, duration, 3);
2344 const __u8 **d=descriptors;
2345 while ( d < pdescr )
2347 memcpy(event+ptr, *d, ((*d)[1])+2);
2351 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2353 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2354 if ( (it->first.tm + duration_sec) < now )
2356 memcpy(event+2, it->first.data, 5);
2359 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2361 event[bptr++] = 0x4A;
2362 __u8 *len = event+(bptr++);
2363 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2364 event[bptr++] = (i->tsid & 0xFF);
2365 event[bptr++] = (i->onid & 0xFF00) >> 8;
2366 event[bptr++] = (i->onid & 0xFF);
2367 event[bptr++] = (i->sid & 0xFF00) >> 8;
2368 event[bptr++] = (i->sid & 0xFF);
2369 event[bptr++] = 0xB0;
2370 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2371 *len = ((event+bptr) - len)-1;
2373 int llen = bptr - 12;
2374 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2375 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2377 time_t stime = it->first.tm;
2378 while( tmMap.find(stime) != tmMap.end() )
2380 event[6] += (stime - it->first.tm);
2382 while( evMap.find(event_id) != evMap.end() )
2384 event[0] = (event_id & 0xFF00) >> 8;
2385 event[1] = (event_id & 0xFF);
2386 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2387 eventData *d = new eventData( ev_struct, bptr, eEPGCache::PRIVATE );
2388 evMap[event_id] = d;
2393 void eEPGCache::channel_data::startPrivateReader()
2395 eDVBSectionFilterMask mask;
2396 memset(&mask, 0, sizeof(mask));
2397 mask.pid = m_PrivatePid;
2398 mask.flags = eDVBSectionFilterMask::rfCRC;
2399 mask.data[0] = 0xA0;
2400 mask.mask[0] = 0xFF;
2401 eDebug("start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2402 if (m_PrevVersion != -1)
2404 mask.data[3] = m_PrevVersion << 1;
2405 mask.mask[3] = 0x3E;
2406 mask.mode[3] = 0x3E;
2408 seenPrivateSections.clear();
2409 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2410 m_PrivateReader->start(mask);
2413 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2416 eDebug("get Null pointer from section reader !!");
2419 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2421 #ifdef NEED_DEMUX_WORKAROUND
2422 int version = data[5];
2423 version = ((version & 0x3E) >> 1);
2425 if ( m_PrevVersion != version )
2427 cache->privateSectionRead(m_PrivateService, data);
2428 seenPrivateSections.insert(data[6]);
2434 cache->privateSectionRead(m_PrivateService, data);
2435 seenPrivateSections.insert(data[6]);
2438 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2440 eDebug("[EPGC] private finished");
2443 m_PrevVersion = (data[5] & 0x3E) >> 1;
2444 startPrivateReader();
2449 #endif // ENABLE_PRIVATE_EPG