1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
7 #include <lib/service/event.h>
11 #include <unistd.h> // for usleep
12 #include <sys/vfs.h> // for statfs
13 // #include <libmd5sum.h>
14 #include <lib/base/eerror.h>
15 #include <lib/dvb/pmt.h>
16 #include <lib/dvb/db.h>
17 #include <lib/python/python.h>
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 channelMapIterator it =
212 m_knownChannels.find(chan);
213 if ( it == m_knownChannels.end() )
214 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
217 channel_data &data = *it->second;
218 ePtr<eDVBResourceManager> res_mgr;
219 if ( eDVBResourceManager::getInstance( res_mgr ) )
220 eDebug("[eEPGCache] no res manager!!");
223 ePtr<iDVBDemux> demux;
224 if ( data.channel->getDemux(demux, 0) )
226 eDebug("[eEPGCache] no demux!!");
231 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
234 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
238 res = demux->createSectionReader( this, data.m_ScheduleReader );
241 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
245 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
248 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
251 #ifdef ENABLE_PRIVATE_EPG
252 res = demux->createSectionReader( this, data.m_PrivateReader );
255 eDebug("[eEPGCache] couldnt initialize private reader!!");
259 #ifdef ENABLE_MHW_EPG
260 res = demux->createSectionReader( this, data.m_MHWReader );
263 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
266 res = demux->createSectionReader( this, data.m_MHWReader2 );
269 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
273 messages.send(Message(Message::startChannel, chan));
274 // -> gotMessage -> changedService
280 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
282 channelMapIterator it =
283 m_knownChannels.find(chan);
284 if ( it != m_knownChannels.end() )
287 chan->getState(state);
288 if ( it->second->prevChannelState != state )
292 case iDVBChannel::state_ok:
294 eDebug("[eEPGCache] channel %p running", chan);
295 DVBChannelRunning(chan);
298 case iDVBChannel::state_release:
300 eDebug("[eEPGCache] remove channel %p", chan);
301 messages.send(Message(Message::leaveChannel, chan));
302 pthread_mutex_lock(&it->second->channel_active);
303 singleLock s(channel_map_lock);
304 m_knownChannels.erase(it);
305 pthread_mutex_unlock(&it->second->channel_active);
308 // -> gotMessage -> abortEPG
311 default: // ignore all other events
315 it->second->prevChannelState = state;
320 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
322 timeMap::iterator tmp = tm_it;
323 while ((tmp->first+tmp->second->getDuration()-300) > TM)
326 #ifdef ENABLE_PRIVATE_EPG
327 && tmp->second->type != PRIVATE
330 && tmp->second->type != MHW
334 __u16 event_id = tmp->second->getEventID();
335 servicemap.first.erase(event_id);
337 Event evt((uint8_t*)tmp->second->get());
339 event.parseFrom(&evt, service.sid<<16|service.onid);
340 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
341 service.sid, event_id,
342 event.getBeginTimeString().c_str(),
343 event.getEventName().c_str(),
344 event.getExtendedDescription().c_str());
347 if (tmp == servicemap.second.begin())
349 servicemap.second.erase(tmp);
353 servicemap.second.erase(tmp--);
357 if (tmp == servicemap.second.begin())
364 while(tmp->first < (TM+duration-300))
366 if (tmp->first != TM && tmp->second->type != PRIVATE)
368 __u16 event_id = tmp->second->getEventID();
369 servicemap.first.erase(event_id);
371 Event evt((uint8_t*)tmp->second->get());
373 event.parseFrom(&evt, service.sid<<16|service.onid);
374 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
375 service.sid, event_id,
376 event.getBeginTimeString().c_str(),
377 event.getEventName().c_str(),
378 event.getExtendedDescription().c_str());
381 servicemap.second.erase(tmp++);
385 if (tmp == servicemap.second.end())
390 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
392 eit_t *eit = (eit_t*) data;
394 int len=HILO(eit->section_length)-1;//+3-4;
399 // This fixed the EPG on the Multichoice irdeto systems
400 // the EIT packet is non-compliant.. their EIT packet stinks
401 if ( data[ptr-1] < 0x40 )
404 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
405 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
409 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);
410 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
412 if ( TM != 3599 && TM > -1)
413 channel->haveData |= source;
415 singleLock s(cache_lock);
416 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
417 // oder eine durch [] erzeugte
418 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
419 eventMap::iterator prevEventIt = servicemap.first.end();
420 timeMap::iterator prevTimeIt = servicemap.second.end();
424 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
426 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
428 eit_event->start_time_1,
429 eit_event->start_time_2,
430 eit_event->start_time_3,
431 eit_event->start_time_4,
432 eit_event->start_time_5);
437 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
440 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
442 __u16 event_id = HILO(eit_event->event_id);
443 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
446 int ev_erase_count = 0;
447 int tm_erase_count = 0;
449 // search in eventmap
450 eventMap::iterator ev_it =
451 servicemap.first.find(event_id);
453 // entry with this event_id is already exist ?
454 if ( ev_it != servicemap.first.end() )
456 if ( source > ev_it->second->type ) // update needed ?
457 goto next; // when not.. then skip this entry
459 // search this event in timemap
460 timeMap::iterator tm_it_tmp =
461 servicemap.second.find(ev_it->second->getStartTime());
463 if ( tm_it_tmp != servicemap.second.end() )
465 if ( tm_it_tmp->first == TM ) // just update eventdata
468 delete ev_it->second;
469 ev_it->second = tm_it_tmp->second =
470 new eventData(eit_event, eit_event_size, source);
471 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
474 else // event has new event begin time
477 // delete the found record from timemap
478 servicemap.second.erase(tm_it_tmp);
479 prevTimeIt=servicemap.second.end();
484 // search in timemap, for check of a case if new time has coincided with time of other event
485 // or event was is not found in eventmap
486 timeMap::iterator tm_it =
487 servicemap.second.find(TM);
489 if ( tm_it != servicemap.second.end() )
491 // event with same start time but another event_id...
492 if ( source > tm_it->second->type &&
493 ev_it == servicemap.first.end() )
494 goto next; // when not.. then skip this entry
496 // search this time in eventmap
497 eventMap::iterator ev_it_tmp =
498 servicemap.first.find(tm_it->second->getEventID());
500 if ( ev_it_tmp != servicemap.first.end() )
503 // delete the found record from eventmap
504 servicemap.first.erase(ev_it_tmp);
505 prevEventIt=servicemap.first.end();
509 evt = new eventData(eit_event, eit_event_size, source);
511 bool consistencyCheck=true;
513 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
516 delete ev_it->second;
517 delete tm_it->second;
521 else if (ev_erase_count == 0 && tm_erase_count > 0)
524 delete ev_it->second;
525 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
528 else if (ev_erase_count > 0 && tm_erase_count == 0)
531 delete tm_it->second;
532 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
535 else // added new eventData
538 consistencyCheck=false;
540 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
541 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
544 FixOverlapping(servicemap, TM, duration, tm_it, service);
547 if ( consistencyCheck )
549 if ( tm_it->second != evt || ev_it->second != evt )
550 eFatal("tm_it->second != ev_it->second");
551 else if ( tm_it->second->getStartTime() != tm_it->first )
552 eFatal("event start_time(%d) non equal timemap key(%d)",
553 tm_it->second->getStartTime(), tm_it->first );
554 else if ( tm_it->first != TM )
555 eFatal("timemap key(%d) non equal TM(%d)",
557 else if ( ev_it->second->getEventID() != ev_it->first )
558 eFatal("event_id (%d) non equal event_map key(%d)",
559 ev_it->second->getEventID(), ev_it->first);
560 else if ( ev_it->first != event_id )
561 eFatal("eventmap key(%d) non equal event_id(%d)",
562 ev_it->first, event_id );
568 if ( servicemap.first.size() != servicemap.second.size() )
570 FILE *f = fopen("/hdd/event_map.txt", "w+");
572 for (eventMap::iterator it(servicemap.first.begin())
573 ; it != servicemap.first.end(); ++it )
574 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
575 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
577 f = fopen("/hdd/time_map.txt", "w+");
579 for (timeMap::iterator it(servicemap.second.begin())
580 ; it != servicemap.second.end(); ++it )
581 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
582 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
585 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
586 service.sid, service.tsid, service.onid,
587 servicemap.first.size(), servicemap.second.size() );
590 ptr += eit_event_size;
591 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
595 void eEPGCache::flushEPG(const uniqueEPGKey & s)
597 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
598 singleLock l(cache_lock);
599 if (s) // clear only this service
601 eventCache::iterator it = eventDB.find(s);
602 if ( it != eventDB.end() )
604 eventMap &evMap = it->second.first;
605 timeMap &tmMap = it->second.second;
607 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
612 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
613 #ifdef ENABLE_PRIVATE_EPG
614 contentMaps::iterator it =
615 content_time_tables.find(s);
616 if ( it != content_time_tables.end() )
619 content_time_tables.erase(it);
624 else // clear complete EPG Cache
626 for (eventCache::iterator it(eventDB.begin());
627 it != eventDB.end(); ++it)
629 eventMap &evMap = it->second.first;
630 timeMap &tmMap = it->second.second;
631 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
637 #ifdef ENABLE_PRIVATE_EPG
638 content_time_tables.clear();
640 channelLastUpdated.clear();
641 singleLock m(channel_map_lock);
642 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
643 it->second->startEPG();
645 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
648 void eEPGCache::cleanLoop()
650 singleLock s(cache_lock);
651 if (!eventDB.empty())
653 eDebug("[EPGC] start cleanloop");
655 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
657 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
659 bool updated = false;
660 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
662 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
664 // remove entry from eventMap
665 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
666 if ( b != DBIt->second.first.end() )
668 // release Heap Memory for this entry (new ....)
669 // eDebug("[EPGC] delete old event (evmap)");
670 DBIt->second.first.erase(b);
673 // remove entry from timeMap
674 // eDebug("[EPGC] release heap mem");
676 DBIt->second.second.erase(It++);
677 // eDebug("[EPGC] delete old event (timeMap)");
683 #ifdef ENABLE_PRIVATE_EPG
686 contentMaps::iterator x =
687 content_time_tables.find( DBIt->first );
688 if ( x != content_time_tables.end() )
690 timeMap &tmMap = eventDB[DBIt->first].second;
691 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
693 for ( contentTimeMap::iterator it(i->second.begin());
694 it != i->second.end(); )
696 if ( tmMap.find(it->second.first) == tmMap.end() )
697 i->second.erase(it++);
701 if ( i->second.size() )
704 x->second.erase(i++);
710 eDebug("[EPGC] stop cleanloop");
711 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
713 cleanTimer.start(CLEAN_INTERVAL,true);
716 eEPGCache::~eEPGCache()
718 messages.send(Message::quit);
719 kill(); // waiting for thread shutdown
720 singleLock s(cache_lock);
721 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
722 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
726 void eEPGCache::gotMessage( const Message &msg )
731 flushEPG(msg.service);
733 case Message::startChannel:
735 singleLock s(channel_map_lock);
736 channelMapIterator channel =
737 m_knownChannels.find(msg.channel);
738 if ( channel != m_knownChannels.end() )
739 channel->second->startChannel();
742 case Message::leaveChannel:
744 singleLock s(channel_map_lock);
745 channelMapIterator channel =
746 m_knownChannels.find(msg.channel);
747 if ( channel != m_knownChannels.end() )
748 channel->second->abortEPG();
754 #ifdef ENABLE_PRIVATE_EPG
755 case Message::got_private_pid:
757 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
759 eDVBChannel *channel = (eDVBChannel*) it->first;
760 channel_data *data = it->second;
761 eDVBChannelID chid = channel->getChannelID();
762 if ( chid.transport_stream_id.get() == msg.service.tsid &&
763 chid.original_network_id.get() == msg.service.onid &&
764 data->m_PrivatePid == -1 )
766 data->m_PrevVersion = -1;
767 data->m_PrivatePid = msg.pid;
768 data->m_PrivateService = msg.service;
769 int onid = chid.original_network_id.get();
770 onid |= 0x80000000; // we use highest bit as private epg indicator
771 chid.original_network_id = onid;
772 updateMap::iterator It = channelLastUpdated.find( chid );
773 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
774 if (update < ZAP_DELAY)
776 data->startPrivateTimer.start(update, 1);
778 eDebug("[EPGC] next private update in %i min", update/60000);
779 else if (update >= 1000)
780 eDebug("[EPGC] next private update in %i sec", update/1000);
787 case Message::timeChanged:
791 eDebug("unhandled EPGCache Message!!");
796 void eEPGCache::thread()
806 void eEPGCache::load()
808 singleLock s(cache_lock);
809 FILE *f = fopen("/hdd/epg.dat", "r");
815 unsigned char md5_saved[16];
816 unsigned char md5[16];
819 if (!md5_file("/hdd/epg.dat", 1, md5))
821 FILE *f = fopen("/hdd/epg.dat.md5", "r");
824 fread( md5_saved, 16, 1, f);
826 if ( !memcmp(md5_saved, md5, 16) )
833 unsigned int magic=0;
834 fread( &magic, sizeof(int), 1, f);
835 if (magic != 0x98765432)
837 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
842 fread( text1, 13, 1, f);
843 if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
845 fread( &size, sizeof(int), 1, f);
852 fread( &key, sizeof(uniqueEPGKey), 1, f);
853 fread( &size, sizeof(int), 1, f);
859 fread( &type, sizeof(__u8), 1, f);
860 fread( &len, sizeof(__u8), 1, f);
861 event = new eventData(0, len, type);
862 event->EITdata = new __u8[len];
863 eventData::CacheSize+=len;
864 fread( event->EITdata, len, 1, f);
865 evMap[ event->getEventID() ]=event;
866 tmMap[ event->getStartTime() ]=event;
869 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
872 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
873 #ifdef ENABLE_PRIVATE_EPG
875 fread( text2, 11, 1, f);
876 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
879 fread( &size, sizeof(int), 1, f);
884 fread( &key, sizeof(uniqueEPGKey), 1, f);
885 eventMap &evMap=eventDB[key].first;
886 fread( &size, sizeof(int), 1, f);
891 fread( &content_id, sizeof(int), 1, f);
892 fread( &size, sizeof(int), 1, f);
897 fread( &time1, sizeof(time_t), 1, f);
898 fread( &time2, sizeof(time_t), 1, f);
899 fread( &event_id, sizeof(__u16), 1, f);
900 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
901 eventMap::iterator it =
902 evMap.find(event_id);
903 if (it != evMap.end())
904 it->second->type = PRIVATE;
909 #endif // ENABLE_PRIVATE_EPG
912 eDebug("[EPGC] don't read old epg database");
918 void eEPGCache::save()
922 if (statfs("/hdd", &s)<0)
930 // prevent writes to builtin flash
931 if ( tmp < 1024*1024*50 ) // storage size < 50MB
934 // check for enough free space on storage
937 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
940 FILE *f = fopen("/hdd/epg.dat", "w");
944 unsigned int magic = 0x98765432;
945 fwrite( &magic, sizeof(int), 1, f);
946 const char *text = "ENIGMA_EPG_V5";
947 fwrite( text, 13, 1, f );
948 int size = eventDB.size();
949 fwrite( &size, sizeof(int), 1, f );
950 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
952 timeMap &timemap = service_it->second.second;
953 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
954 size = timemap.size();
955 fwrite( &size, sizeof(int), 1, f);
956 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
958 __u8 len = time_it->second->ByteSize;
959 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
960 fwrite( &len, sizeof(__u8), 1, f);
961 fwrite( time_it->second->EITdata, len, 1, f);
965 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
967 #ifdef ENABLE_PRIVATE_EPG
968 const char* text3 = "PRIVATE_EPG";
969 fwrite( text3, 11, 1, f );
970 size = content_time_tables.size();
971 fwrite( &size, sizeof(int), 1, f);
972 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
974 contentMap &content_time_table = a->second;
975 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
976 int size = content_time_table.size();
977 fwrite( &size, sizeof(int), 1, f);
978 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
980 int size = i->second.size();
981 fwrite( &i->first, sizeof(int), 1, f);
982 fwrite( &size, sizeof(int), 1, f);
983 for ( contentTimeMap::iterator it(i->second.begin());
984 it != i->second.end(); ++it )
986 fwrite( &it->first, sizeof(time_t), 1, f);
987 fwrite( &it->second.first, sizeof(time_t), 1, f);
988 fwrite( &it->second.second, sizeof(__u16), 1, f);
995 unsigned char md5[16];
996 if (!md5_file("/hdd/epg.dat", 1, md5))
998 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1001 fwrite( md5, 16, 1, f);
1009 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1011 ,abortTimer(ml), zapTimer(ml), state(0)
1012 ,isRunning(0), haveData(0)
1013 #ifdef ENABLE_PRIVATE_EPG
1014 ,startPrivateTimer(ml)
1016 #ifdef ENABLE_MHW_EPG
1017 ,m_MHWTimeoutTimer(ml)
1020 #ifdef ENABLE_MHW_EPG
1021 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1023 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1024 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1025 #ifdef ENABLE_PRIVATE_EPG
1026 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1028 pthread_mutex_init(&channel_active, 0);
1031 bool eEPGCache::channel_data::finishEPG()
1033 if (!isRunning) // epg ready
1035 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1036 zapTimer.start(UPDATE_INTERVAL, 1);
1037 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1038 for (int i=0; i < 3; ++i)
1040 seenSections[i].clear();
1041 calcedSections[i].clear();
1043 singleLock l(cache->cache_lock);
1044 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1045 #ifdef ENABLE_MHW_EPG
1053 void eEPGCache::channel_data::startEPG()
1055 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1058 for (int i=0; i < 3; ++i)
1060 seenSections[i].clear();
1061 calcedSections[i].clear();
1064 eDVBSectionFilterMask mask;
1065 memset(&mask, 0, sizeof(mask));
1067 #ifdef ENABLE_MHW_EPG
1069 mask.data[0] = 0x91;
1070 mask.mask[0] = 0xFF;
1071 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1072 m_MHWReader->start(mask);
1074 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1077 mask.data[0] = 0xC8;
1078 mask.mask[0] = 0xFF;
1080 mask.mask[1] = 0xFF;
1081 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1082 m_MHWReader2->start(mask);
1084 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1090 mask.flags = eDVBSectionFilterMask::rfCRC;
1092 mask.data[0] = 0x4E;
1093 mask.mask[0] = 0xFE;
1094 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1095 m_NowNextReader->start(mask);
1096 isRunning |= NOWNEXT;
1098 mask.data[0] = 0x50;
1099 mask.mask[0] = 0xF0;
1100 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1101 m_ScheduleReader->start(mask);
1102 isRunning |= SCHEDULE;
1104 mask.data[0] = 0x60;
1105 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1106 m_ScheduleOtherReader->start(mask);
1107 isRunning |= SCHEDULE_OTHER;
1109 abortTimer.start(7000,true);
1112 void eEPGCache::channel_data::abortNonAvail()
1116 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1118 eDebug("[EPGC] abort non avail nownext reading");
1119 isRunning &= ~NOWNEXT;
1120 m_NowNextReader->stop();
1123 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1125 eDebug("[EPGC] abort non avail schedule reading");
1126 isRunning &= ~SCHEDULE;
1127 m_ScheduleReader->stop();
1130 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1132 eDebug("[EPGC] abort non avail schedule_other reading");
1133 isRunning &= ~SCHEDULE_OTHER;
1134 m_ScheduleOtherReader->stop();
1135 m_ScheduleOtherConn=0;
1137 #ifdef ENABLE_MHW_EPG
1138 if ( !(haveData&MHW) && (isRunning&MHW) )
1140 eDebug("[EPGC] abort non avail mhw reading");
1142 m_MHWReader->stop();
1144 m_MHWReader2->stop();
1149 abortTimer.start(90000, true);
1153 for (int i=0; i < 3; ++i)
1155 seenSections[i].clear();
1156 calcedSections[i].clear();
1163 void eEPGCache::channel_data::startChannel()
1165 pthread_mutex_lock(&channel_active);
1166 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1168 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1170 if (update < ZAP_DELAY)
1173 zapTimer.start(update, 1);
1174 if (update >= 60000)
1175 eDebug("[EPGC] next update in %i min", update/60000);
1176 else if (update >= 1000)
1177 eDebug("[EPGC] next update in %i sec", update/1000);
1180 void eEPGCache::channel_data::abortEPG()
1182 for (int i=0; i < 3; ++i)
1184 seenSections[i].clear();
1185 calcedSections[i].clear();
1191 eDebug("[EPGC] abort caching events !!");
1192 if (isRunning & SCHEDULE)
1194 isRunning &= ~SCHEDULE;
1195 m_ScheduleReader->stop();
1198 if (isRunning & NOWNEXT)
1200 isRunning &= ~NOWNEXT;
1201 m_NowNextReader->stop();
1204 if (isRunning & SCHEDULE_OTHER)
1206 isRunning &= ~SCHEDULE_OTHER;
1207 m_ScheduleOtherReader->stop();
1208 m_ScheduleOtherConn=0;
1210 #ifdef ENABLE_MHW_EPG
1211 if (isRunning & MHW)
1214 m_MHWReader->stop();
1216 m_MHWReader2->stop();
1221 #ifdef ENABLE_PRIVATE_EPG
1222 if (m_PrivateReader)
1223 m_PrivateReader->stop();
1227 pthread_mutex_unlock(&channel_active);
1230 void eEPGCache::channel_data::readData( const __u8 *data)
1234 iDVBSectionReader *reader=NULL;
1238 reader=m_NowNextReader;
1243 reader=m_ScheduleReader;
1248 reader=m_ScheduleOtherReader;
1249 source=SCHEDULE_OTHER;
1253 eDebug("[EPGC] unknown table_id !!!");
1256 tidMap &seenSections = this->seenSections[map];
1257 tidMap &calcedSections = this->calcedSections[map];
1258 if ( state == 1 && calcedSections == seenSections || state > 1 )
1260 eDebugNoNewLine("[EPGC] ");
1265 eDebugNoNewLine("nownext");
1269 eDebugNoNewLine("schedule");
1271 case SCHEDULE_OTHER:
1272 m_ScheduleOtherConn=0;
1273 eDebugNoNewLine("schedule other");
1275 default: eDebugNoNewLine("unknown");break;
1277 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1280 isRunning &= ~source;
1286 eit_t *eit = (eit_t*) data;
1287 __u32 sectionNo = data[0] << 24;
1288 sectionNo |= data[3] << 16;
1289 sectionNo |= data[4] << 8;
1290 sectionNo |= eit->section_number;
1292 tidMap::iterator it =
1293 seenSections.find(sectionNo);
1295 if ( it == seenSections.end() )
1297 seenSections.insert(sectionNo);
1298 calcedSections.insert(sectionNo);
1299 __u32 tmpval = sectionNo & 0xFFFFFF00;
1300 __u8 incr = source == NOWNEXT ? 1 : 8;
1301 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1303 if ( i == eit->section_number )
1305 for (int x=i; x <= eit->segment_last_section_number; ++x)
1306 calcedSections.insert(tmpval|(x&0xFF));
1309 calcedSections.insert(tmpval|(i&0xFF));
1311 cache->sectionRead(data, source, this);
1316 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1317 // if t == -1 we search the current event...
1319 singleLock s(cache_lock);
1320 uniqueEPGKey key(service);
1322 // check if EPG for this service is ready...
1323 eventCache::iterator It = eventDB.find( key );
1324 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1327 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1328 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1329 It->second.second.upper_bound(t); // just >
1330 if ( i != It->second.second.end() )
1332 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1334 timeMap::iterator x = i;
1336 if ( x != It->second.second.end() )
1338 time_t start_time = x->second->getStartTime();
1343 if (t > (start_time+x->second->getDuration()))
1358 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1360 singleLock s(cache_lock);
1361 const eventData *data=0;
1362 RESULT ret = lookupEventTime(service, t, data, direction);
1364 result = data->get();
1368 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1370 singleLock s(cache_lock);
1371 const eventData *data=0;
1372 RESULT ret = lookupEventTime(service, t, data, direction);
1374 result = new Event((uint8_t*)data->get());
1378 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1380 singleLock s(cache_lock);
1381 const eventData *data=0;
1382 RESULT ret = lookupEventTime(service, t, data, direction);
1385 Event ev((uint8_t*)data->get());
1386 result = new eServiceEvent();
1387 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1388 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1393 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1395 singleLock s(cache_lock);
1396 uniqueEPGKey key( service );
1398 eventCache::iterator It = eventDB.find( key );
1399 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1401 eventMap::iterator i( It->second.first.find( event_id ));
1402 if ( i != It->second.first.end() )
1410 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1416 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1418 singleLock s(cache_lock);
1419 const eventData *data=0;
1420 RESULT ret = lookupEventId(service, event_id, data);
1422 result = data->get();
1426 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1428 singleLock s(cache_lock);
1429 const eventData *data=0;
1430 RESULT ret = lookupEventId(service, event_id, data);
1432 result = new Event((uint8_t*)data->get());
1436 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1438 singleLock s(cache_lock);
1439 const eventData *data=0;
1440 RESULT ret = lookupEventId(service, event_id, data);
1443 Event ev((uint8_t*)data->get());
1444 result = new eServiceEvent();
1445 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1446 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1451 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1453 eventCache::iterator It = eventDB.find( service );
1454 if ( It != eventDB.end() && It->second.second.size() )
1456 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1459 m_timemap_cursor = It->second.second.lower_bound(begin);
1460 if ( m_timemap_cursor != It->second.second.end() )
1462 if ( m_timemap_cursor->second->getStartTime() != begin )
1464 timeMap::iterator x = m_timemap_cursor;
1466 if ( x != It->second.second.end() )
1468 time_t start_time = x->second->getStartTime();
1469 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1470 m_timemap_cursor = x;
1476 m_timemap_cursor = It->second.second.begin();
1477 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1478 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1484 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1486 if ( m_timemap_cursor != m_timemap_end )
1488 result = m_timemap_cursor++->second;
1494 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1496 if ( m_timemap_cursor != m_timemap_end )
1498 result = m_timemap_cursor++->second->get();
1504 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1506 if ( m_timemap_cursor != m_timemap_end )
1508 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1514 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1516 if ( m_timemap_cursor != m_timemap_end )
1518 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1519 result = new eServiceEvent();
1520 return result->parseFrom(&ev, currentQueryTsidOnid);
1525 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, ePtr<eServiceEvent> &ptr, ePyObject nowTime, ePyObject service_name )
1529 while(pos < argcount)
1531 bool inc_refcount=false;
1532 switch(argstring[pos])
1534 case '0': // PyLong 0
1535 tmp = PyLong_FromLong(0);
1537 case 'I': // Event Id
1538 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1540 case 'B': // Event Begin Time
1541 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1543 case 'D': // Event Duration
1544 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1546 case 'T': // Event Title
1547 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1549 case 'S': // Event Short Description
1550 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1552 case 'E': // Event Extended Description
1553 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1555 case 'C': // Current Time
1557 inc_refcount = true;
1559 case 'R': // service reference string
1561 inc_refcount = true;
1563 case 'N': // service name
1565 inc_refcount = true;
1570 inc_refcount = true;
1574 PyTuple_SET_ITEM(tuple, pos++, tmp);
1578 int handleEvent(ePtr<eServiceEvent> &ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1582 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1583 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1587 Py_DECREF(service_name);
1590 Py_DECREF(convertFuncArgs);
1591 Py_DECREF(dest_list);
1592 PyErr_SetString(PyExc_StandardError,
1593 "error in convertFunc execute");
1594 eDebug("error in convertFunc execute");
1597 PyList_Append(dest_list, result);
1602 ePyObject tuple = PyTuple_New(argcount);
1603 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1604 PyList_Append(dest_list, tuple);
1610 // here we get a python list
1611 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1614 // B = Event Begin Time
1615 // D = Event Duration
1617 // S = Event Short Description
1618 // E = Event Extended Description
1620 // R = Service Reference
1622 // then for each service follows a tuple
1623 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1624 // the second is the type of query
1626 // -1 = event before given start_time
1627 // 0 = event intersects given start_time
1628 // +1 = event after given start_time
1630 // when type is eventid it is the event_id
1631 // when type is time then it is the start_time ( 0 for now_time )
1632 // the fourth is the end_time .. ( optional .. for query all events in time range)
1634 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1636 ePyObject convertFuncArgs;
1638 char *argstring=NULL;
1639 if (!PyList_Check(list))
1641 PyErr_SetString(PyExc_StandardError,
1647 int listSize=PyList_Size(list);
1650 PyErr_SetString(PyExc_StandardError,
1651 "not params given");
1652 eDebug("not params given");
1657 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1658 if (PyString_Check(argv))
1660 argstring = PyString_AS_STRING(argv);
1664 argstring = "I"; // just event id as default
1665 argcount = strlen(argstring);
1666 // eDebug("have %d args('%s')", argcount, argstring);
1670 if (!PyCallable_Check(convertFunc))
1672 PyErr_SetString(PyExc_StandardError,
1673 "convertFunc must be callable");
1674 eDebug("convertFunc is not callable");
1677 convertFuncArgs = PyTuple_New(argcount);
1680 ePyObject nowTime = strchr(argstring, 'C') ?
1681 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1684 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1687 ePyObject dest_list=PyList_New(0);
1688 while(listSize > listIt)
1690 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1691 if (PyTuple_Check(item))
1693 bool service_changed=false;
1698 int tupleSize=PyTuple_Size(item);
1701 while(tupleSize > tupleIt) // parse query args
1703 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1708 if (!PyString_Check(entry))
1710 eDebug("tuple entry 0 is no a string");
1717 type=PyInt_AsLong(entry);
1718 if (type < -1 || type > 2)
1720 eDebug("unknown type %d", type);
1725 event_id=stime=PyInt_AsLong(entry);
1728 minutes=PyInt_AsLong(entry);
1731 eDebug("unneeded extra argument");
1735 eServiceReference ref(PyString_AS_STRING(service));
1736 if (ref.type != eServiceReference::idDVB)
1738 eDebug("service reference for epg query is not valid");
1742 // redirect subservice querys to parent service
1743 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1744 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1746 eServiceCenterPtr service_center;
1747 if (!eServiceCenter::getPrivInstance(service_center))
1749 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1750 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1751 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1752 dvb_ref.setParentServiceID(eServiceID(0));
1754 service = PyString_FromString(dvb_ref.toString().c_str());
1755 service_changed = true;
1759 ePyObject service_name;
1760 if (must_get_service_name)
1762 ePtr<iStaticServiceInformation> sptr;
1763 eServiceCenterPtr service_center;
1764 eServiceCenter::getPrivInstance(service_center);
1767 service_center->info(ref, sptr);
1771 sptr->getName(ref, name);
1773 service_name = PyString_FromString(name.c_str());
1777 service_name = PyString_FromString("<n/a>");
1782 if (!startTimeQuery(ref, stime, minutes))
1784 ePtr<eServiceEvent> ptr;
1785 while (!getNextTimeEntry(ptr))
1787 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1798 ePtr<eServiceEvent> ptr;
1802 lookupEventId(ref, event_id, ptr);
1804 lookupEventTime(ref, stime, ptr, type);
1806 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1809 if (service_changed)
1812 Py_DECREF(service_name);
1817 if (convertFuncArgs)
1818 Py_DECREF(convertFuncArgs);
1824 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, ePyObject service_name, ePyObject service_reference)
1828 while(pos < argcount)
1830 bool inc_refcount=false;
1831 switch(argstring[pos])
1833 case '0': // PyLong 0
1834 tmp = PyLong_FromLong(0);
1836 case 'I': // Event Id
1837 tmp = PyLong_FromLong(evData->getEventID());
1839 case 'B': // Event Begin Time
1841 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1843 tmp = PyLong_FromLong(evData->getStartTime());
1845 case 'D': // Event Duration
1847 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1849 tmp = PyLong_FromLong(evData->getDuration());
1851 case 'T': // Event Title
1852 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1854 case 'S': // Event Short Description
1855 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1857 case 'E': // Event Extended Description
1858 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1860 case 'R': // service reference string
1861 tmp = service_reference;
1862 inc_refcount = true;
1864 case 'N': // service name
1866 inc_refcount = true;
1872 inc_refcount = true;
1876 PyTuple_SET_ITEM(tuple, pos++, tmp);
1880 // here we get a python tuple
1881 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1883 // B = Event Begin Time
1884 // D = Event Duration
1886 // S = Event Short Description
1887 // E = Event Extended Description
1888 // R = Service Reference
1890 // the second tuple entry is the MAX matches value
1891 // the third tuple entry is the type of query
1892 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1893 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1894 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1895 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1896 // the fourth is the servicereference string
1897 // the fifth is the eventid
1898 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1899 // the fourth is the search text
1901 // 0 = case sensitive (CASE_CHECK)
1902 // 1 = case insensitive (NO_CASECHECK)
1904 PyObject *eEPGCache::search(ePyObject arg)
1910 const char *argstring=0;
1914 bool needServiceEvent=false;
1917 if (PyTuple_Check(arg))
1919 int tuplesize=PyTuple_Size(arg);
1922 ePyObject obj = PyTuple_GET_ITEM(arg,0);
1923 if (PyString_Check(obj))
1925 argcount = PyString_GET_SIZE(obj);
1926 argstring = PyString_AS_STRING(obj);
1927 for (int i=0; i < argcount; ++i)
1928 switch(argstring[i])
1933 needServiceEvent=true;
1940 PyErr_SetString(PyExc_StandardError,
1942 eDebug("tuple arg 0 is not a string");
1947 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1950 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1951 if (tuplesize > 4 && querytype == 0)
1953 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
1954 if (PyString_Check(obj))
1956 refstr = PyString_AS_STRING(obj);
1957 eServiceReferenceDVB ref(refstr);
1960 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1961 singleLock s(cache_lock);
1962 const eventData *evData = 0;
1963 lookupEventId(ref, eventid, evData);
1966 __u8 *data = evData->EITdata;
1967 int tmp = evData->ByteSize-12;
1968 __u32 *p = (__u32*)(data+12);
1969 // search short and extended event descriptors
1973 descriptorMap::iterator it =
1974 eventData::descriptors.find(crc);
1975 if (it != eventData::descriptors.end())
1977 __u8 *descr_data = it->second.second;
1978 switch(descr_data[0])
1981 descr[++descridx]=crc;
1990 eDebug("event not found");
1994 PyErr_SetString(PyExc_StandardError,
1996 eDebug("tuple arg 4 is not a valid service reference string");
2002 PyErr_SetString(PyExc_StandardError,
2004 eDebug("tuple arg 4 is not a string");
2008 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2010 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2011 if (PyString_Check(obj))
2013 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2014 const char *str = PyString_AS_STRING(obj);
2015 int textlen = PyString_GET_SIZE(obj);
2017 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2019 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2020 singleLock s(cache_lock);
2021 for (descriptorMap::iterator it(eventData::descriptors.begin());
2022 it != eventData::descriptors.end() && descridx < 511; ++it)
2024 __u8 *data = it->second.second;
2025 if ( data[0] == 0x4D ) // short event descriptor
2027 int title_len = data[5];
2028 if ( querytype == 1 )
2030 if (title_len > textlen)
2032 else if (title_len < textlen)
2036 if ( !strncasecmp((const char*)data+6, str, title_len) )
2038 // std::string s((const char*)data+6, title_len);
2039 // eDebug("match1 %s %s", str, s.c_str() );
2040 descr[++descridx] = it->first;
2043 else if ( !strncmp((const char*)data+6, str, title_len) )
2045 // std::string s((const char*)data+6, title_len);
2046 // eDebug("match2 %s %s", str, s.c_str() );
2047 descr[++descridx] = it->first;
2053 while((title_len-idx) >= textlen)
2057 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2059 descr[++descridx] = it->first;
2060 // std::string s((const char*)data+6, title_len);
2061 // eDebug("match 3 %s %s", str, s.c_str() );
2064 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2066 descr[++descridx] = it->first;
2067 // std::string s((const char*)data+6, title_len);
2068 // eDebug("match 4 %s %s", str, s.c_str() );
2080 PyErr_SetString(PyExc_StandardError,
2082 eDebug("tuple arg 4 is not a string");
2088 PyErr_SetString(PyExc_StandardError,
2090 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2096 PyErr_SetString(PyExc_StandardError,
2098 eDebug("not enough args in tuple");
2104 PyErr_SetString(PyExc_StandardError,
2106 eDebug("arg 0 is not a tuple");
2112 int maxcount=maxmatches;
2113 eServiceReferenceDVB ref(refstr?refstr:"");
2114 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2115 // in this case we start searching with the base service
2116 bool first = ref.valid() ? true : false;
2117 singleLock s(cache_lock);
2118 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2119 while(cit != eventDB.end() && maxcount)
2121 if ( ref.valid() && !first && cit->first == ref )
2123 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2127 ePyObject service_name;
2128 ePyObject service_reference;
2129 timeMap &evmap = cit->second.second;
2131 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2133 int evid = evit->second->getEventID();
2134 if ( evid == eventid)
2136 __u8 *data = evit->second->EITdata;
2137 int tmp = evit->second->ByteSize-12;
2138 __u32 *p = (__u32*)(data+12);
2139 // check if any of our descriptor used by this event
2144 for ( int i=0; i <= descridx; ++i)
2146 if (descr[i] == crc32) // found...
2151 if ( (querytype == 0 && cnt == descridx) ||
2152 ((querytype == 1 || querytype == 2) && cnt != -1) )
2154 const uniqueEPGKey &service = cit->first;
2155 eServiceReference ref =
2156 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2159 // create servive event
2160 ePtr<eServiceEvent> ptr;
2161 if (needServiceEvent)
2163 lookupEventId(ref, evid, ptr);
2165 eDebug("event not found !!!!!!!!!!!");
2167 // create service name
2168 if (!service_name && strchr(argstring,'N'))
2170 ePtr<iStaticServiceInformation> sptr;
2171 eServiceCenterPtr service_center;
2172 eServiceCenter::getPrivInstance(service_center);
2175 service_center->info(ref, sptr);
2179 sptr->getName(ref, name);
2181 service_name = PyString_FromString(name.c_str());
2185 service_name = PyString_FromString("<n/a>");
2187 // create servicereference string
2188 if (!service_reference && strchr(argstring,'R'))
2189 service_reference = PyString_FromString(ref.toString().c_str());
2192 ret = PyList_New(0);
2194 ePyObject tuple = PyTuple_New(argcount);
2196 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2197 PyList_Append(ret, tuple);
2204 Py_DECREF(service_name);
2205 if (service_reference)
2206 Py_DECREF(service_reference);
2209 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2211 cit=eventDB.begin();
2227 #ifdef ENABLE_PRIVATE_EPG
2228 #include <dvbsi++/descriptor_tag.h>
2229 #include <dvbsi++/unknown_descriptor.h>
2230 #include <dvbsi++/private_data_specifier_descriptor.h>
2232 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2234 ePtr<eTable<ProgramMapSection> > ptr;
2235 if (!pmthandler->getPMT(ptr) && ptr)
2237 std::vector<ProgramMapSection*>::const_iterator i;
2238 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2240 const ProgramMapSection &pmt = **i;
2242 ElementaryStreamInfoConstIterator es;
2243 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2246 switch ((*es)->getType())
2248 case 0x05: // private
2249 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2250 desc != (*es)->getDescriptors()->end(); ++desc)
2252 switch ((*desc)->getTag())
2254 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2255 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2260 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2261 int descr_len = descr->getLength();
2264 uint8_t data[descr_len+2];
2265 descr->writeToBuffer(data);
2266 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2280 eServiceReferenceDVB ref;
2281 if (!pmthandler->getServiceReference(ref))
2283 int pid = (*es)->getPid();
2284 messages.send(Message(Message::got_private_pid, ref, pid));
2292 eDebug("PMTready but no pmt!!");
2299 date_time( const date_time &a )
2301 memcpy(data, a.data, 5);
2304 date_time( const __u8 data[5])
2306 memcpy(this->data, data, 5);
2307 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2312 const __u8& operator[](int pos) const
2318 struct less_datetime
2320 bool operator()( const date_time &a, const date_time &b ) const
2322 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2326 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2328 contentMap &content_time_table = content_time_tables[current_service];
2329 singleLock s(cache_lock);
2330 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2331 eventMap &evMap = eventDB[current_service].first;
2332 timeMap &tmMap = eventDB[current_service].second;
2334 int content_id = data[ptr++] << 24;
2335 content_id |= data[ptr++] << 16;
2336 content_id |= data[ptr++] << 8;
2337 content_id |= data[ptr++];
2339 contentTimeMap &time_event_map =
2340 content_time_table[content_id];
2341 for ( contentTimeMap::iterator it( time_event_map.begin() );
2342 it != time_event_map.end(); ++it )
2344 eventMap::iterator evIt( evMap.find(it->second.second) );
2345 if ( evIt != evMap.end() )
2347 delete evIt->second;
2350 tmMap.erase(it->second.first);
2352 time_event_map.clear();
2355 memcpy(duration, data+ptr, 3);
2358 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2360 const __u8 *descriptors[65];
2361 const __u8 **pdescr = descriptors;
2363 int descriptors_length = (data[ptr++]&0x0F) << 8;
2364 descriptors_length |= data[ptr++];
2365 while ( descriptors_length > 0 )
2367 int descr_type = data[ptr];
2368 int descr_len = data[ptr+1];
2369 descriptors_length -= (descr_len+2);
2370 if ( descr_type == 0xf2 )
2373 int tsid = data[ptr++] << 8;
2374 tsid |= data[ptr++];
2375 int onid = data[ptr++] << 8;
2376 onid |= data[ptr++];
2377 int sid = data[ptr++] << 8;
2380 // WORKAROUND for wrong transmitted epg data (01.08.2006)
2383 switch( (tsid << 16) | sid )
2385 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2386 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2387 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2388 case 0x0300f5: sid = 0xdc; break;
2389 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2390 case 0x1100d3: sid = 0xe3; break;
2393 ////////////////////////////////////////////
2395 uniqueEPGKey service( sid, onid, tsid );
2397 while( descr_len > 0 )
2400 datetime[0] = data[ptr++];
2401 datetime[1] = data[ptr++];
2402 int tmp_len = data[ptr++];
2404 while( tmp_len > 0 )
2406 memcpy(datetime+2, data+ptr, 3);
2410 start_times[datetime].push_back(service);
2422 eit_event_struct *ev_struct = (eit_event_struct*) event;
2423 ev_struct->running_status = 0;
2424 ev_struct->free_CA_mode = 1;
2425 memcpy(event+7, duration, 3);
2427 const __u8 **d=descriptors;
2428 while ( d < pdescr )
2430 memcpy(event+ptr, *d, ((*d)[1])+2);
2434 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2436 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2437 if ( (it->first.tm + duration_sec) < now )
2439 memcpy(event+2, it->first.data, 5);
2442 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2444 event[bptr++] = 0x4A;
2445 __u8 *len = event+(bptr++);
2446 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2447 event[bptr++] = (i->tsid & 0xFF);
2448 event[bptr++] = (i->onid & 0xFF00) >> 8;
2449 event[bptr++] = (i->onid & 0xFF);
2450 event[bptr++] = (i->sid & 0xFF00) >> 8;
2451 event[bptr++] = (i->sid & 0xFF);
2452 event[bptr++] = 0xB0;
2453 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2454 *len = ((event+bptr) - len)-1;
2456 int llen = bptr - 12;
2457 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2458 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2460 time_t stime = it->first.tm;
2461 while( tmMap.find(stime) != tmMap.end() )
2463 event[6] += (stime - it->first.tm);
2465 while( evMap.find(event_id) != evMap.end() )
2467 event[0] = (event_id & 0xFF00) >> 8;
2468 event[1] = (event_id & 0xFF);
2469 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2470 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2471 evMap[event_id] = d;
2476 void eEPGCache::channel_data::startPrivateReader()
2478 eDVBSectionFilterMask mask;
2479 memset(&mask, 0, sizeof(mask));
2480 mask.pid = m_PrivatePid;
2481 mask.flags = eDVBSectionFilterMask::rfCRC;
2482 mask.data[0] = 0xA0;
2483 mask.mask[0] = 0xFF;
2484 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2485 if (m_PrevVersion != -1)
2487 mask.data[3] = m_PrevVersion << 1;
2488 mask.mask[3] = 0x3E;
2489 mask.mode[3] = 0x3E;
2491 seenPrivateSections.clear();
2493 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2494 m_PrivateReader->start(mask);
2497 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2499 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2501 cache->privateSectionRead(m_PrivateService, data);
2502 seenPrivateSections.insert(data[6]);
2504 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2506 eDebug("[EPGC] private finished");
2507 eDVBChannelID chid = channel->getChannelID();
2508 int tmp = chid.original_network_id.get();
2509 tmp |= 0x80000000; // we use highest bit as private epg indicator
2510 chid.original_network_id = tmp;
2511 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2512 m_PrevVersion = (data[5] & 0x3E) >> 1;
2513 startPrivateReader();
2517 #endif // ENABLE_PRIVATE_EPG
2519 #ifdef ENABLE_MHW_EPG
2520 void eEPGCache::channel_data::cleanup()
2525 m_program_ids.clear();
2528 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2530 // Names in mhw structs are not strings as they are not '\0' terminated.
2531 // This function converts the mhw name into a string.
2532 // Constraint: "length of out" = "length of in" + 1.
2534 for ( i=0; i < len_in; i++ )
2538 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2545 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2548 return_time[0] = toBCD( hours );
2549 return_time[1] = toBCD( minutes );
2553 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2555 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2558 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2559 // For date plus time of day
2561 // Remove offset in mhw time.
2562 __u8 local_hours = hours;
2565 else if ( hours >= 8 )
2568 // As far as we know all mhw time data is sent in central Europe time zone.
2569 // So, temporarily set timezone to western europe
2570 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2572 char *old_tz = getenv( "TZ" );
2573 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2576 tm *localnow = localtime( &dt );
2580 if ( day + 1 < localnow->tm_wday ) // day + 1 to prevent old events to show for next week.
2582 if (local_hours <= 5)
2585 dt += 3600*24*(day - localnow->tm_wday); // Shift dt to the recording date (local time zone).
2586 dt += 3600*(local_hours - localnow->tm_hour); // Shift dt to the recording hour.
2588 tm *recdate = gmtime( &dt ); // This will also take care of DST.
2590 if ( old_tz == NULL )
2596 // Calculate MJD according to annex in ETSI EN 300 468
2598 if ( recdate->tm_mon <= 1 ) // Jan or Feb
2600 int mjd = 14956 + recdate->tm_mday + int( (recdate->tm_year - l) * 365.25) +
2601 int( (recdate->tm_mon + 2 + l * 12) * 30.6001);
2603 return_time[0] = (mjd & 0xFF00)>>8;
2604 return_time[1] = mjd & 0xFF;
2606 timeMHW2DVB( recdate->tm_hour, minutes, return_time+2 );
2609 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2610 // data is borrowed from calling proc to save memory space.
2613 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2614 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2615 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2617 eit_t *packet = (eit_t *) data;
2618 packet->table_id = 0x50;
2619 packet->section_syntax_indicator = 1;
2620 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2621 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2622 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2623 packet->current_next_indicator = 0;
2624 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2625 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2626 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2627 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2628 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2629 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2630 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2631 packet->segment_last_table_id = 0x50;
2633 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2634 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2635 int prog_title_length = prog_title.length();
2637 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2638 prog_title_length + 1;
2640 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2641 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2642 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2646 u_char *data = (u_char*) event_data;
2647 data[2] = itTitle->second.mhw2_mjd_hi;
2648 data[3] = itTitle->second.mhw2_mjd_lo;
2649 data[4] = itTitle->second.mhw2_hours;
2650 data[5] = itTitle->second.mhw2_minutes;
2651 data[6] = itTitle->second.mhw2_seconds;
2652 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2656 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2657 (u_char *) event_data + 2 );
2658 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2661 event_data->running_status = 0;
2662 event_data->free_CA_mode = 0;
2663 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2665 eit_short_event_descriptor_struct *short_event_descriptor =
2666 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2667 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2668 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2669 prog_title_length - 1;
2670 short_event_descriptor->language_code_1 = 'e';
2671 short_event_descriptor->language_code_2 = 'n';
2672 short_event_descriptor->language_code_3 = 'g';
2673 short_event_descriptor->event_name_length = prog_title_length;
2674 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2675 memcpy(event_name, prog_title.c_str(), prog_title_length);
2678 event_name[prog_title_length] = 0;
2680 if ( sumText.length() > 0 )
2681 // There is summary info
2683 unsigned int sum_length = sumText.length();
2684 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2685 // Store summary in short event descriptor
2687 // Increase all relevant lengths
2688 event_name[prog_title_length] = sum_length;
2689 short_event_descriptor->descriptor_length += sum_length;
2690 packet_length += sum_length;
2691 descr_ll += sum_length;
2692 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2695 // Store summary in extended event descriptors
2697 int remaining_sum_length = sumText.length();
2698 int nbr_descr = int(remaining_sum_length/247) + 1;
2699 for ( int i=0; i < nbr_descr; i++)
2700 // Loop once per extended event descriptor
2702 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2703 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2704 remaining_sum_length -= sum_length;
2705 packet_length += 8 + sum_length;
2706 descr_ll += 8 + sum_length;
2708 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2709 ext_event_descriptor->descriptor_length = sum_length + 6;
2710 ext_event_descriptor->descriptor_number = i;
2711 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2712 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2713 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2714 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2715 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2717 the_text[-1] = sum_length;
2718 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2725 // Add content descriptor
2726 u_char *descriptor = (u_char *) data + packet_length;
2731 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2732 if ( content_descr.find( "FILM" ) != std::string::npos )
2734 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2737 descriptor[0] = 0x54;
2739 descriptor[2] = content_id;
2743 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2744 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2746 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2747 packet->section_length_lo = (packet_length - 3)&0xff;
2749 // Feed the data to eEPGCache::sectionRead()
2750 cache->sectionRead( data, MHW, this );
2753 void eEPGCache::channel_data::startTimeout(int msec)
2755 m_MHWTimeoutTimer.start(msec,true);
2756 m_MHWTimeoutet=false;
2759 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2761 m_MHWFilterMask.pid = pid;
2762 m_MHWFilterMask.data[0] = tid;
2763 m_MHWReader->start(m_MHWFilterMask);
2764 // eDebug("start 0x%02x 0x%02x", pid, tid);
2767 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2769 m_MHWFilterMask2.pid = pid;
2770 m_MHWFilterMask2.data[0] = tid;
2773 m_MHWFilterMask2.data[1] = ext;
2774 m_MHWFilterMask2.mask[1] = 0xFF;
2775 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2779 m_MHWFilterMask2.data[1] = 0;
2780 m_MHWFilterMask2.mask[1] = 0;
2781 // eDebug("start 0x%02x 0x%02x", pid, tid);
2783 m_MHWReader2->start(m_MHWFilterMask2);
2786 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2789 m_MHWReader2->stop();
2791 if ( state > 1 || // aborted
2792 // have si data.. so we dont read mhw data
2793 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2795 eDebug("[EPGC] mhw aborted %d", state);
2797 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2800 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2801 int record_size = sizeof( mhw_channel_name_t );
2802 int nbr_records = int (len/record_size);
2804 for ( int i = 0; i < nbr_records; i++ )
2806 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2807 m_channels.push_back( *channel );
2811 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2813 // Channels table has been read, start reading the themes table.
2814 startMHWReader(0xD3, 0x92);
2817 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2820 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2821 int record_size = sizeof( mhw_theme_name_t );
2822 int nbr_records = int (len/record_size);
2824 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2827 for ( int i = 0; i < nbr_records; i++ )
2829 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2830 if ( i >= next_idx )
2834 next_idx = (__u8) *(data + 3 + idx_ptr);
2840 m_themes[idx+sub_idx] = *theme;
2842 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2843 // Themes table has been read, start reading the titles table.
2844 startMHWReader(0xD2, 0x90);
2848 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2851 mhw_title_t *title = (mhw_title_t*) data;
2853 if ( title->channel_id == 0xFF ) // Separator
2854 return; // Continue reading of the current table.
2857 // Create unique key per title
2858 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2859 (title->ms.minutes);
2860 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2861 ((title->program_id_ml)<<8)|(title->program_id_lo);
2863 if ( m_titles.find( title_id ) == m_titles.end() )
2866 title->mhw2_mjd_hi = 0;
2867 title->mhw2_mjd_lo = 0;
2868 title->mhw2_duration_hi = 0;
2869 title->mhw2_duration_lo = 0;
2870 m_titles[ title_id ] = *title;
2871 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2872 // program_ids will be used to gather summaries.
2873 m_program_ids[ program_id ] = title_id;
2874 return; // Continue reading of the current table.
2876 else if (!checkTimeout())
2879 if ( !m_program_ids.empty())
2881 // Titles table has been read, there are summaries to read.
2882 // Start reading summaries, store corresponding titles on the fly.
2883 startMHWReader(0xD3, 0x90);
2884 eDebug("[EPGC] mhw %d titles(%d with summary) found",
2886 m_program_ids.size());
2891 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2894 mhw_summary_t *summary = (mhw_summary_t*) data;
2896 // Create unique key per record
2897 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2898 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2899 int len = ((data[1]&0xf)<<8) + data[2];
2901 // ugly workaround to convert const __u8* to char*
2903 memcpy(&tmp, &data, sizeof(void*));
2904 tmp[len+3] = 0; // Terminate as a string.
2906 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2907 if ( itProgid == m_program_ids.end() )
2908 { /* This part is to prevent to looping forever if some summaries are not received yet.
2909 There is a timeout of 4 sec. after the last successfully read summary. */
2910 if (!m_program_ids.empty() && !checkTimeout())
2911 return; // Continue reading of the current table.
2915 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2918 while((pos = the_text.find("\r\n")) != std::string::npos)
2919 the_text.replace(pos, 2, " ");
2921 // Find corresponding title, store title and summary in epgcache.
2922 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2923 if ( itTitle != m_titles.end() )
2926 storeTitle( itTitle, the_text, data );
2927 m_titles.erase( itTitle );
2929 m_program_ids.erase( itProgid );
2930 if ( !m_program_ids.empty() )
2931 return; // Continue reading of the current table.
2934 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
2935 eDVBLocalTimeHandler::getInstance()->nowTime(),
2936 m_program_ids.size());
2937 // Summaries have been read, titles that have summaries have been stored.
2938 // Now store titles that do not have summaries.
2939 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
2940 storeTitle( itTitle, "", data );
2944 m_MHWReader->stop();
2949 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
2951 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
2954 m_MHWReader->stop();
2956 if ( state > 1 || // aborted
2957 // have si data.. so we dont read mhw data
2958 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
2960 eDebug("[EPGC] mhw2 aborted %d", state);
2962 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
2965 int num_channels = data[120];
2968 int ptr = 121 + 6 * num_channels;
2971 for( int chid = 0; chid < num_channels; ++chid )
2973 ptr += ( data[ptr] & 0x0f ) + 1;
2983 // data seems consistent...
2984 const __u8 *tmp = data+121;
2985 for (int i=0; i < num_channels; ++i)
2987 mhw_channel_name_t channel;
2988 channel.transport_stream_id_hi = *(tmp++);
2989 channel.transport_stream_id_lo = *(tmp++);
2990 channel.channel_id_hi = *(tmp++);
2991 channel.channel_id_lo = *(tmp++);
2992 #warning FIXME hardcoded network_id in mhw2 epg
2993 channel.network_id_hi = 0; // hardcoded astra 19.2
2994 channel.network_id_lo = 1;
2995 m_channels.push_back(channel);
2998 for (int i=0; i < num_channels; ++i)
3000 mhw_channel_name_t &channel = m_channels[i];
3001 int channel_name_len=*(tmp++)&0x0f;
3003 for (; x < channel_name_len; ++x)
3004 channel.name[x]=*(tmp++);
3005 channel.name[x+1]=0;
3008 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3010 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3013 eDebug("[EPGC] mhw2 themes nyi");
3015 else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3020 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3022 if(data[dataLen-1] != 0xff)
3024 while( pos < dataLen )
3033 if( data[pos] > 0xc0 )
3035 pos += ( data[pos] - 0xc0 );
3039 if( data[pos] == 0xff )
3055 // data seems consistent...
3060 title.channel_id = data[pos]+1;
3061 title.program_id_ml = data[pos+1];
3062 title.program_id_lo = data[pos+2];
3063 title.mhw2_mjd_hi = data[pos+3];
3064 title.mhw2_mjd_lo = data[pos+4];
3065 title.mhw2_hours = data[pos+5];
3066 title.mhw2_minutes = data[pos+6];
3067 title.mhw2_seconds = data[pos+7];
3068 int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3069 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3070 title.mhw2_duration_lo = duration&0xFF;
3071 __u8 slen = data[pos+10] & 0x3f;
3072 __u8 *dest = ((__u8*)title.title)-4;
3073 memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3074 memset(dest+slen, 0x20, 33-slen);
3076 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3077 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3079 // Create unique key per title
3080 __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3082 // eDebug("program_id: %08x, %s", program_id,
3083 // std::string((const char *)title.title, (int)(slen > 23 ? 23 : slen)).c_str());
3087 if ( m_titles.find( title_id ) == m_titles.end() )
3090 m_titles[ title_id ] = title;
3091 if (summary_id != 0xFFFF && // no summary avail
3092 m_program_ids.find(summary_id) == m_program_ids.end())
3094 m_program_ids[ summary_id ] = title_id;
3099 if ( !checkTimeout() )
3100 continue; // Continue reading of the current table.
3108 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3109 if (!m_program_ids.empty())
3111 // Titles table has been read, there are summaries to read.
3112 // Start reading summaries, store corresponding titles on the fly.
3113 startMHWReader2(0x236, 0x96);
3121 else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3124 int len, loop, pos, lenline;
3133 loop = data[pos] & 0x0f;
3138 for( ; loop > 0; --loop )
3140 if( dataLen > (pos+len) )
3142 lenline = data[pos+len];
3151 else if (!checkTimeout())
3152 return; // continue reading
3153 if (valid && !checkTimeout())
3155 // data seems consistent...
3156 __u32 summary_id = (data[3]<<8)|data[4];
3158 // ugly workaround to convert const __u8* to char*
3160 memcpy(&tmp, &data, sizeof(void*));
3165 loop = tmp[pos] & 0x0f;
3167 for( ; loop > 0; loop -- )
3169 lenline = tmp[pos+len];
3178 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( summary_id ) );
3179 if ( itProgid == m_program_ids.end() )
3180 { /* This part is to prevent to looping forever if some summaries are not received yet.
3181 There is a timeout of 4 sec. after the last successfully read summary. */
3183 if ( !m_program_ids.empty() && !checkTimeout() )
3184 return; // Continue reading of the current table.
3189 std::string the_text = (char *) (data + pos + 1);
3191 // Find corresponding title, store title and summary in epgcache.
3192 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3193 if ( itTitle != m_titles.end() )
3195 storeTitle( itTitle, the_text, data );
3196 m_titles.erase( itTitle );
3198 m_program_ids.erase( itProgid );
3199 if ( !m_program_ids.empty() )
3200 return; // Continue reading of the current table.
3204 if (isRunning & eEPGCache::MHW)
3206 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3208 // Channels table has been read, start reading the themes table.
3209 startMHWReader2(0x231, 0xC8, 1);
3212 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3214 // Themes table has been read, start reading the titles table.
3215 startMHWReader2(0x234, 0xe6);
3220 // Summaries have been read, titles that have summaries have been stored.
3221 // Now store titles that do not have summaries.
3222 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3223 storeTitle( itTitle, "", data );
3224 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3225 eDVBLocalTimeHandler::getInstance()->nowTime(),
3226 m_program_ids.size());
3233 m_MHWReader2->stop();