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 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!!");
267 messages.send(Message(Message::startChannel, chan));
268 // -> gotMessage -> changedService
274 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
276 channelMapIterator it =
277 m_knownChannels.find(chan);
278 if ( it != m_knownChannels.end() )
281 chan->getState(state);
282 if ( it->second->prevChannelState != state )
286 case iDVBChannel::state_ok:
288 eDebug("[eEPGCache] channel %p running", chan);
289 DVBChannelRunning(chan);
292 case iDVBChannel::state_release:
294 eDebug("[eEPGCache] remove channel %p", chan);
295 messages.send(Message(Message::leaveChannel, chan));
296 pthread_mutex_lock(&it->second->channel_active);
297 singleLock s(channel_map_lock);
298 m_knownChannels.erase(it);
299 pthread_mutex_unlock(&it->second->channel_active);
302 // -> gotMessage -> abortEPG
305 default: // ignore all other events
309 it->second->prevChannelState = state;
314 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
316 timeMap::iterator tmp = tm_it;
317 while ((tmp->first+tmp->second->getDuration()-300) > TM)
319 if(tmp->first != TM && tmp->second->type != PRIVATE)
321 __u16 event_id = tmp->second->getEventID();
322 servicemap.first.erase(event_id);
324 Event evt((uint8_t*)tmp->second->get());
326 event.parseFrom(&evt, service.sid<<16|service.onid);
327 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
328 service.sid, event_id,
329 event.getBeginTimeString().c_str(),
330 event.getEventName().c_str(),
331 event.getExtendedDescription().c_str());
334 if (tmp == servicemap.second.begin())
336 servicemap.second.erase(tmp);
340 servicemap.second.erase(tmp--);
344 if (tmp == servicemap.second.begin())
351 while(tmp->first < (TM+duration-300))
353 if (tmp->first != TM && tmp->second->type != PRIVATE)
355 __u16 event_id = tmp->second->getEventID();
356 servicemap.first.erase(event_id);
358 Event evt((uint8_t*)tmp->second->get());
360 event.parseFrom(&evt, service.sid<<16|service.onid);
361 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
362 service.sid, event_id,
363 event.getBeginTimeString().c_str(),
364 event.getEventName().c_str(),
365 event.getExtendedDescription().c_str());
368 servicemap.second.erase(tmp++);
372 if (tmp == servicemap.second.end())
377 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
379 eit_t *eit = (eit_t*) data;
381 int len=HILO(eit->section_length)-1;//+3-4;
386 // This fixed the EPG on the Multichoice irdeto systems
387 // the EIT packet is non-compliant.. their EIT packet stinks
388 if ( data[ptr-1] < 0x40 )
391 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
392 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
396 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);
397 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
399 if ( TM != 3599 && TM > -1)
400 channel->haveData |= source;
402 singleLock s(cache_lock);
403 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
404 // oder eine durch [] erzeugte
405 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
406 eventMap::iterator prevEventIt = servicemap.first.end();
407 timeMap::iterator prevTimeIt = servicemap.second.end();
411 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
413 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
415 eit_event->start_time_1,
416 eit_event->start_time_2,
417 eit_event->start_time_3,
418 eit_event->start_time_4,
419 eit_event->start_time_5);
424 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
427 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
429 __u16 event_id = HILO(eit_event->event_id);
430 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
433 int ev_erase_count = 0;
434 int tm_erase_count = 0;
436 // search in eventmap
437 eventMap::iterator ev_it =
438 servicemap.first.find(event_id);
440 // entry with this event_id is already exist ?
441 if ( ev_it != servicemap.first.end() )
443 if ( source > ev_it->second->type ) // update needed ?
444 goto next; // when not.. then skip this entry
446 // search this event in timemap
447 timeMap::iterator tm_it_tmp =
448 servicemap.second.find(ev_it->second->getStartTime());
450 if ( tm_it_tmp != servicemap.second.end() )
452 if ( tm_it_tmp->first == TM ) // just update eventdata
455 delete ev_it->second;
456 ev_it->second = tm_it_tmp->second =
457 new eventData(eit_event, eit_event_size, source);
458 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
461 else // event has new event begin time
464 // delete the found record from timemap
465 servicemap.second.erase(tm_it_tmp);
466 prevTimeIt=servicemap.second.end();
471 // search in timemap, for check of a case if new time has coincided with time of other event
472 // or event was is not found in eventmap
473 timeMap::iterator tm_it =
474 servicemap.second.find(TM);
476 if ( tm_it != servicemap.second.end() )
478 // event with same start time but another event_id...
479 if ( source > tm_it->second->type &&
480 ev_it == servicemap.first.end() )
481 goto next; // when not.. then skip this entry
483 // search this time in eventmap
484 eventMap::iterator ev_it_tmp =
485 servicemap.first.find(tm_it->second->getEventID());
487 if ( ev_it_tmp != servicemap.first.end() )
490 // delete the found record from eventmap
491 servicemap.first.erase(ev_it_tmp);
492 prevEventIt=servicemap.first.end();
496 evt = new eventData(eit_event, eit_event_size, source);
498 bool consistencyCheck=true;
500 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
503 delete ev_it->second;
504 delete tm_it->second;
508 else if (ev_erase_count == 0 && tm_erase_count > 0)
511 delete ev_it->second;
512 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
515 else if (ev_erase_count > 0 && tm_erase_count == 0)
518 delete tm_it->second;
519 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
522 else // added new eventData
525 consistencyCheck=false;
527 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
528 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
531 FixOverlapping(servicemap, TM, duration, tm_it, service);
534 if ( consistencyCheck )
536 if ( tm_it->second != evt || ev_it->second != evt )
537 eFatal("tm_it->second != ev_it->second");
538 else if ( tm_it->second->getStartTime() != tm_it->first )
539 eFatal("event start_time(%d) non equal timemap key(%d)",
540 tm_it->second->getStartTime(), tm_it->first );
541 else if ( tm_it->first != TM )
542 eFatal("timemap key(%d) non equal TM(%d)",
544 else if ( ev_it->second->getEventID() != ev_it->first )
545 eFatal("event_id (%d) non equal event_map key(%d)",
546 ev_it->second->getEventID(), ev_it->first);
547 else if ( ev_it->first != event_id )
548 eFatal("eventmap key(%d) non equal event_id(%d)",
549 ev_it->first, event_id );
555 if ( servicemap.first.size() != servicemap.second.size() )
557 FILE *f = fopen("/hdd/event_map.txt", "w+");
559 for (eventMap::iterator it(servicemap.first.begin())
560 ; it != servicemap.first.end(); ++it )
561 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
562 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
564 f = fopen("/hdd/time_map.txt", "w+");
566 for (timeMap::iterator it(servicemap.second.begin())
567 ; it != servicemap.second.end(); ++it )
568 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
569 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
572 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
573 service.sid, service.tsid, service.onid,
574 servicemap.first.size(), servicemap.second.size() );
577 ptr += eit_event_size;
578 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
582 void eEPGCache::flushEPG(const uniqueEPGKey & s)
584 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
585 singleLock l(cache_lock);
586 if (s) // clear only this service
588 eventCache::iterator it = eventDB.find(s);
589 if ( it != eventDB.end() )
591 eventMap &evMap = it->second.first;
592 timeMap &tmMap = it->second.second;
594 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
599 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
600 #ifdef ENABLE_PRIVATE_EPG
601 contentMaps::iterator it =
602 content_time_tables.find(s);
603 if ( it != content_time_tables.end() )
606 content_time_tables.erase(it);
611 else // clear complete EPG Cache
613 for (eventCache::iterator it(eventDB.begin());
614 it != eventDB.end(); ++it)
616 eventMap &evMap = it->second.first;
617 timeMap &tmMap = it->second.second;
618 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
624 #ifdef ENABLE_PRIVATE_EPG
625 content_time_tables.clear();
627 channelLastUpdated.clear();
628 singleLock m(channel_map_lock);
629 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
630 it->second->startEPG();
632 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
635 void eEPGCache::cleanLoop()
637 singleLock s(cache_lock);
638 if (!eventDB.empty())
640 eDebug("[EPGC] start cleanloop");
642 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
644 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
646 bool updated = false;
647 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
649 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
651 // remove entry from eventMap
652 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
653 if ( b != DBIt->second.first.end() )
655 // release Heap Memory for this entry (new ....)
656 // eDebug("[EPGC] delete old event (evmap)");
657 DBIt->second.first.erase(b);
660 // remove entry from timeMap
661 // eDebug("[EPGC] release heap mem");
663 DBIt->second.second.erase(It++);
664 // eDebug("[EPGC] delete old event (timeMap)");
670 #ifdef ENABLE_PRIVATE_EPG
673 contentMaps::iterator x =
674 content_time_tables.find( DBIt->first );
675 if ( x != content_time_tables.end() )
677 timeMap &tmMap = eventDB[DBIt->first].second;
678 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
680 for ( contentTimeMap::iterator it(i->second.begin());
681 it != i->second.end(); )
683 if ( tmMap.find(it->second.first) == tmMap.end() )
684 i->second.erase(it++);
688 if ( i->second.size() )
691 x->second.erase(i++);
697 eDebug("[EPGC] stop cleanloop");
698 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
700 cleanTimer.start(CLEAN_INTERVAL,true);
703 eEPGCache::~eEPGCache()
705 messages.send(Message::quit);
706 kill(); // waiting for thread shutdown
707 singleLock s(cache_lock);
708 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
709 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
713 void eEPGCache::gotMessage( const Message &msg )
718 flushEPG(msg.service);
720 case Message::startChannel:
722 singleLock s(channel_map_lock);
723 channelMapIterator channel =
724 m_knownChannels.find(msg.channel);
725 if ( channel != m_knownChannels.end() )
726 channel->second->startChannel();
729 case Message::leaveChannel:
731 singleLock s(channel_map_lock);
732 channelMapIterator channel =
733 m_knownChannels.find(msg.channel);
734 if ( channel != m_knownChannels.end() )
735 channel->second->abortEPG();
741 #ifdef ENABLE_PRIVATE_EPG
742 case Message::got_private_pid:
744 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
746 eDVBChannel *channel = (eDVBChannel*) it->first;
747 channel_data *data = it->second;
748 eDVBChannelID chid = channel->getChannelID();
749 if ( chid.transport_stream_id.get() == msg.service.tsid &&
750 chid.original_network_id.get() == msg.service.onid &&
751 data->m_PrivatePid == -1 )
753 data->m_PrevVersion = -1;
754 data->m_PrivatePid = msg.pid;
755 data->m_PrivateService = msg.service;
756 updateMap::iterator It = channelLastUpdated.find( channel->getChannelID() );
757 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
758 if (update < ZAP_DELAY)
760 data->startPrivateTimer.start(update, 1);
762 eDebug("[EPGC] next private update in %i min", update/60000);
763 else if (update >= 1000)
764 eDebug("[EPGC] next private update in %i sec", update/1000);
771 case Message::timeChanged:
775 eDebug("unhandled EPGCache Message!!");
780 void eEPGCache::thread()
790 void eEPGCache::load()
792 singleLock s(cache_lock);
793 FILE *f = fopen("/hdd/epg.dat", "r");
799 unsigned char md5_saved[16];
800 unsigned char md5[16];
803 if (!md5_file("/hdd/epg.dat", 1, md5))
805 FILE *f = fopen("/hdd/epg.dat.md5", "r");
808 fread( md5_saved, 16, 1, f);
810 if ( !memcmp(md5_saved, md5, 16) )
817 unsigned int magic=0;
818 fread( &magic, sizeof(int), 1, f);
819 if (magic != 0x98765432)
821 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
826 fread( text1, 13, 1, f);
827 if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
829 fread( &size, sizeof(int), 1, f);
836 fread( &key, sizeof(uniqueEPGKey), 1, f);
837 fread( &size, sizeof(int), 1, f);
843 fread( &type, sizeof(__u8), 1, f);
844 fread( &len, sizeof(__u8), 1, f);
845 event = new eventData(0, len, type);
846 event->EITdata = new __u8[len];
847 eventData::CacheSize+=len;
848 fread( event->EITdata, len, 1, f);
849 evMap[ event->getEventID() ]=event;
850 tmMap[ event->getStartTime() ]=event;
853 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
856 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
857 #ifdef ENABLE_PRIVATE_EPG
859 fread( text2, 11, 1, f);
860 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
863 fread( &size, sizeof(int), 1, f);
868 fread( &key, sizeof(uniqueEPGKey), 1, f);
869 eventMap &evMap=eventDB[key].first;
870 fread( &size, sizeof(int), 1, f);
875 fread( &content_id, sizeof(int), 1, f);
876 fread( &size, sizeof(int), 1, f);
881 fread( &time1, sizeof(time_t), 1, f);
882 fread( &time2, sizeof(time_t), 1, f);
883 fread( &event_id, sizeof(__u16), 1, f);
884 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
885 eventMap::iterator it =
886 evMap.find(event_id);
887 if (it != evMap.end())
888 it->second->type = PRIVATE;
893 #endif // ENABLE_PRIVATE_EPG
896 eDebug("[EPGC] don't read old epg database");
902 void eEPGCache::save()
906 if (statfs("/hdd", &s)<0)
914 // prevent writes to builtin flash
915 if ( tmp < 1024*1024*50 ) // storage size < 50MB
918 // check for enough free space on storage
921 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
924 FILE *f = fopen("/hdd/epg.dat", "w");
928 unsigned int magic = 0x98765432;
929 fwrite( &magic, sizeof(int), 1, f);
930 const char *text = "ENIGMA_EPG_V5";
931 fwrite( text, 13, 1, f );
932 int size = eventDB.size();
933 fwrite( &size, sizeof(int), 1, f );
934 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
936 timeMap &timemap = service_it->second.second;
937 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
938 size = timemap.size();
939 fwrite( &size, sizeof(int), 1, f);
940 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
942 __u8 len = time_it->second->ByteSize;
943 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
944 fwrite( &len, sizeof(__u8), 1, f);
945 fwrite( time_it->second->EITdata, len, 1, f);
949 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
951 #ifdef ENABLE_PRIVATE_EPG
952 const char* text3 = "PRIVATE_EPG";
953 fwrite( text3, 11, 1, f );
954 size = content_time_tables.size();
955 fwrite( &size, sizeof(int), 1, f);
956 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
958 contentMap &content_time_table = a->second;
959 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
960 int size = content_time_table.size();
961 fwrite( &size, sizeof(int), 1, f);
962 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
964 int size = i->second.size();
965 fwrite( &i->first, sizeof(int), 1, f);
966 fwrite( &size, sizeof(int), 1, f);
967 for ( contentTimeMap::iterator it(i->second.begin());
968 it != i->second.end(); ++it )
970 fwrite( &it->first, sizeof(time_t), 1, f);
971 fwrite( &it->second.first, sizeof(time_t), 1, f);
972 fwrite( &it->second.second, sizeof(__u16), 1, f);
979 unsigned char md5[16];
980 if (!md5_file("/hdd/epg.dat", 1, md5))
982 FILE *f = fopen("/hdd/epg.dat.md5", "w");
985 fwrite( md5, 16, 1, f);
993 eEPGCache::channel_data::channel_data(eEPGCache *ml)
995 ,abortTimer(ml), zapTimer(ml), state(0)
996 ,isRunning(0), haveData(0)
997 #ifdef ENABLE_PRIVATE_EPG
998 ,startPrivateTimer(ml)
1000 #ifdef ENABLE_MHW_EPG
1001 ,m_MHWTimeoutTimer(ml)
1004 #ifdef ENABLE_MHW_EPG
1005 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1007 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1008 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1009 #ifdef ENABLE_PRIVATE_EPG
1010 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1012 pthread_mutex_init(&channel_active, 0);
1015 bool eEPGCache::channel_data::finishEPG()
1017 if (!isRunning) // epg ready
1019 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1020 zapTimer.start(UPDATE_INTERVAL, 1);
1021 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1022 for (int i=0; i < 3; ++i)
1024 seenSections[i].clear();
1025 calcedSections[i].clear();
1027 singleLock l(cache->cache_lock);
1028 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1029 #ifdef ENABLE_MHW_EPG
1037 void eEPGCache::channel_data::startEPG()
1039 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1042 for (int i=0; i < 3; ++i)
1044 seenSections[i].clear();
1045 calcedSections[i].clear();
1048 eDVBSectionFilterMask mask;
1049 memset(&mask, 0, sizeof(mask));
1051 #ifdef ENABLE_MHW_EPG
1053 mask.data[0] = 0x91;
1054 mask.mask[0] = 0xFF;
1055 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1056 m_MHWReader->start(mask);
1058 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1062 mask.flags = eDVBSectionFilterMask::rfCRC;
1064 mask.data[0] = 0x4E;
1065 mask.mask[0] = 0xFE;
1066 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1067 m_NowNextReader->start(mask);
1068 isRunning |= NOWNEXT;
1070 mask.data[0] = 0x50;
1071 mask.mask[0] = 0xF0;
1072 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1073 m_ScheduleReader->start(mask);
1074 isRunning |= SCHEDULE;
1076 mask.data[0] = 0x60;
1077 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1078 m_ScheduleOtherReader->start(mask);
1079 isRunning |= SCHEDULE_OTHER;
1081 abortTimer.start(7000,true);
1084 void eEPGCache::channel_data::abortNonAvail()
1088 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1090 eDebug("[EPGC] abort non avail nownext reading");
1091 isRunning &= ~NOWNEXT;
1092 m_NowNextReader->stop();
1095 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1097 eDebug("[EPGC] abort non avail schedule reading");
1098 isRunning &= ~SCHEDULE;
1099 m_ScheduleReader->stop();
1102 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1104 eDebug("[EPGC] abort non avail schedule_other reading");
1105 isRunning &= ~SCHEDULE_OTHER;
1106 m_ScheduleOtherReader->stop();
1107 m_ScheduleOtherConn=0;
1109 #ifdef ENABLE_MHW_EPG
1110 if ( !(haveData&MHW) && (isRunning&MHW) )
1112 eDebug("[EPGC] abort non avail mhw reading");
1114 m_MHWReader->stop();
1119 abortTimer.start(90000, true);
1123 for (int i=0; i < 3; ++i)
1125 seenSections[i].clear();
1126 calcedSections[i].clear();
1133 void eEPGCache::channel_data::startChannel()
1135 pthread_mutex_lock(&channel_active);
1136 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1138 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1140 if (update < ZAP_DELAY)
1143 zapTimer.start(update, 1);
1144 if (update >= 60000)
1145 eDebug("[EPGC] next update in %i min", update/60000);
1146 else if (update >= 1000)
1147 eDebug("[EPGC] next update in %i sec", update/1000);
1150 void eEPGCache::channel_data::abortEPG()
1152 for (int i=0; i < 3; ++i)
1154 seenSections[i].clear();
1155 calcedSections[i].clear();
1161 eDebug("[EPGC] abort caching events !!");
1162 if (isRunning & SCHEDULE)
1164 isRunning &= ~SCHEDULE;
1165 m_ScheduleReader->stop();
1168 if (isRunning & NOWNEXT)
1170 isRunning &= ~NOWNEXT;
1171 m_NowNextReader->stop();
1174 if (isRunning & SCHEDULE_OTHER)
1176 isRunning &= ~SCHEDULE_OTHER;
1177 m_ScheduleOtherReader->stop();
1178 m_ScheduleOtherConn=0;
1180 #ifdef ENABLE_MHW_EPG
1181 if (isRunning & MHW)
1184 m_MHWReader->stop();
1189 #ifdef ENABLE_PRIVATE_EPG
1190 if (m_PrivateReader)
1191 m_PrivateReader->stop();
1195 pthread_mutex_unlock(&channel_active);
1198 void eEPGCache::channel_data::readData( const __u8 *data)
1202 iDVBSectionReader *reader=NULL;
1206 reader=m_NowNextReader;
1211 reader=m_ScheduleReader;
1216 reader=m_ScheduleOtherReader;
1217 source=SCHEDULE_OTHER;
1221 eDebug("[EPGC] unknown table_id !!!");
1224 tidMap &seenSections = this->seenSections[map];
1225 tidMap &calcedSections = this->calcedSections[map];
1226 if ( state == 1 && calcedSections == seenSections || state > 1 )
1228 eDebugNoNewLine("[EPGC] ");
1233 eDebugNoNewLine("nownext");
1237 eDebugNoNewLine("schedule");
1239 case SCHEDULE_OTHER:
1240 m_ScheduleOtherConn=0;
1241 eDebugNoNewLine("schedule other");
1243 default: eDebugNoNewLine("unknown");break;
1245 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1248 isRunning &= ~source;
1254 eit_t *eit = (eit_t*) data;
1255 __u32 sectionNo = data[0] << 24;
1256 sectionNo |= data[3] << 16;
1257 sectionNo |= data[4] << 8;
1258 sectionNo |= eit->section_number;
1260 tidMap::iterator it =
1261 seenSections.find(sectionNo);
1263 if ( it == seenSections.end() )
1265 seenSections.insert(sectionNo);
1266 calcedSections.insert(sectionNo);
1267 __u32 tmpval = sectionNo & 0xFFFFFF00;
1268 __u8 incr = source == NOWNEXT ? 1 : 8;
1269 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1271 if ( i == eit->section_number )
1273 for (int x=i; x <= eit->segment_last_section_number; ++x)
1274 calcedSections.insert(tmpval|(x&0xFF));
1277 calcedSections.insert(tmpval|(i&0xFF));
1279 cache->sectionRead(data, source, this);
1284 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1285 // if t == -1 we search the current event...
1287 singleLock s(cache_lock);
1288 uniqueEPGKey key(service);
1290 // check if EPG for this service is ready...
1291 eventCache::iterator It = eventDB.find( key );
1292 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1295 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1296 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1297 It->second.second.upper_bound(t); // just >
1298 if ( i != It->second.second.end() )
1300 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1302 timeMap::iterator x = i;
1304 if ( x != It->second.second.end() )
1306 time_t start_time = x->second->getStartTime();
1311 if (t > (start_time+x->second->getDuration()))
1326 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1328 singleLock s(cache_lock);
1329 const eventData *data=0;
1330 RESULT ret = lookupEventTime(service, t, data, direction);
1332 result = data->get();
1336 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1338 singleLock s(cache_lock);
1339 const eventData *data=0;
1340 RESULT ret = lookupEventTime(service, t, data, direction);
1342 result = new Event((uint8_t*)data->get());
1346 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1348 singleLock s(cache_lock);
1349 const eventData *data=0;
1350 RESULT ret = lookupEventTime(service, t, data, direction);
1353 Event ev((uint8_t*)data->get());
1354 result = new eServiceEvent();
1355 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1356 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1361 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1363 singleLock s(cache_lock);
1364 uniqueEPGKey key( service );
1366 eventCache::iterator It = eventDB.find( key );
1367 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1369 eventMap::iterator i( It->second.first.find( event_id ));
1370 if ( i != It->second.first.end() )
1378 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1384 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1386 singleLock s(cache_lock);
1387 const eventData *data=0;
1388 RESULT ret = lookupEventId(service, event_id, data);
1390 result = data->get();
1394 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1396 singleLock s(cache_lock);
1397 const eventData *data=0;
1398 RESULT ret = lookupEventId(service, event_id, data);
1400 result = new Event((uint8_t*)data->get());
1404 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1406 singleLock s(cache_lock);
1407 const eventData *data=0;
1408 RESULT ret = lookupEventId(service, event_id, data);
1411 Event ev((uint8_t*)data->get());
1412 result = new eServiceEvent();
1413 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1414 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1419 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1421 eventCache::iterator It = eventDB.find( service );
1422 if ( It != eventDB.end() && It->second.second.size() )
1424 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1427 m_timemap_cursor = It->second.second.lower_bound(begin);
1428 if ( m_timemap_cursor != It->second.second.end() )
1430 if ( m_timemap_cursor->second->getStartTime() != begin )
1432 timeMap::iterator x = m_timemap_cursor;
1434 if ( x != It->second.second.end() )
1436 time_t start_time = x->second->getStartTime();
1437 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1438 m_timemap_cursor = x;
1444 m_timemap_cursor = It->second.second.begin();
1445 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1446 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1452 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1454 if ( m_timemap_cursor != m_timemap_end )
1456 result = m_timemap_cursor++->second;
1462 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1464 if ( m_timemap_cursor != m_timemap_end )
1466 result = m_timemap_cursor++->second->get();
1472 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1474 if ( m_timemap_cursor != m_timemap_end )
1476 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1482 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1484 if ( m_timemap_cursor != m_timemap_end )
1486 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1487 result = new eServiceEvent();
1488 return result->parseFrom(&ev, currentQueryTsidOnid);
1493 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1497 while(pos < argcount)
1499 bool inc_refcount=false;
1500 switch(argstring[pos])
1502 case '0': // PyLong 0
1503 tmp = PyLong_FromLong(0);
1505 case 'I': // Event Id
1506 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1508 case 'B': // Event Begin Time
1509 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1511 case 'D': // Event Duration
1512 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1514 case 'T': // Event Title
1515 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1517 case 'S': // Event Short Description
1518 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1520 case 'E': // Event Extended Description
1521 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1523 case 'C': // Current Time
1525 inc_refcount = true;
1527 case 'R': // service reference string
1529 inc_refcount = true;
1531 case 'N': // service name
1533 inc_refcount = true;
1538 inc_refcount = true;
1542 PyTuple_SET_ITEM(tuple, pos++, tmp);
1546 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1550 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1551 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1555 Py_DECREF(service_name);
1558 Py_DECREF(convertFuncArgs);
1559 Py_DECREF(dest_list);
1562 PyList_Append(dest_list, result);
1567 PyObject *tuple = PyTuple_New(argcount);
1568 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1569 PyList_Append(dest_list, tuple);
1575 // here we get a python list
1576 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1579 // B = Event Begin Time
1580 // D = Event Duration
1582 // S = Event Short Description
1583 // E = Event Extended Description
1585 // R = Service Reference
1587 // then for each service follows a tuple
1588 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1589 // the second is the type of query
1591 // -1 = event before given start_time
1592 // 0 = event intersects given start_time
1593 // +1 = event after given start_time
1595 // when type is eventid it is the event_id
1596 // when type is time then it is the start_time ( 0 for now_time )
1597 // the fourth is the end_time .. ( optional .. for query all events in time range)
1599 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1601 PyObject *convertFuncArgs=NULL;
1603 char *argstring=NULL;
1604 if (!PyList_Check(list))
1606 PyErr_SetString(PyExc_StandardError,
1612 int listSize=PyList_Size(list);
1615 PyErr_SetString(PyExc_StandardError,
1616 "not params given");
1617 eDebug("not params given");
1622 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1623 if (PyString_Check(argv))
1625 argstring = PyString_AS_STRING(argv);
1629 argstring = "I"; // just event id as default
1630 argcount = strlen(argstring);
1631 // eDebug("have %d args('%s')", argcount, argstring);
1635 if (!PyCallable_Check(convertFunc))
1637 PyErr_SetString(PyExc_StandardError,
1638 "convertFunc must be callable");
1639 eDebug("convertFunc is not callable");
1642 convertFuncArgs = PyTuple_New(argcount);
1645 PyObject *nowTime = strchr(argstring, 'C') ?
1646 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1649 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1652 PyObject *dest_list=PyList_New(0);
1653 while(listSize > listIt)
1655 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1656 if (PyTuple_Check(item))
1658 bool service_changed=false;
1663 int tupleSize=PyTuple_Size(item);
1665 PyObject *service=NULL;
1666 while(tupleSize > tupleIt) // parse query args
1668 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1673 if (!PyString_Check(entry))
1675 eDebug("tuple entry 0 is no a string");
1682 type=PyInt_AsLong(entry);
1683 if (type < -1 || type > 2)
1685 eDebug("unknown type %d", type);
1690 event_id=stime=PyInt_AsLong(entry);
1693 minutes=PyInt_AsLong(entry);
1696 eDebug("unneeded extra argument");
1700 eServiceReference ref(PyString_AS_STRING(service));
1701 if (ref.type != eServiceReference::idDVB)
1703 eDebug("service reference for epg query is not valid");
1707 // redirect subservice querys to parent service
1708 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1709 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1711 eServiceCenterPtr service_center;
1712 if (!eServiceCenter::getPrivInstance(service_center))
1714 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1715 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1716 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1717 dvb_ref.setParentServiceID(eServiceID(0));
1719 service = PyString_FromString(dvb_ref.toString().c_str());
1720 service_changed = true;
1724 PyObject *service_name=NULL;
1725 if (must_get_service_name)
1727 ePtr<iStaticServiceInformation> sptr;
1728 eServiceCenterPtr service_center;
1729 eServiceCenter::getPrivInstance(service_center);
1732 service_center->info(ref, sptr);
1736 sptr->getName(ref, name);
1738 service_name = PyString_FromString(name.c_str());
1742 service_name = PyString_FromString("<n/a>");
1747 if (!startTimeQuery(ref, stime, minutes))
1749 ePtr<eServiceEvent> ptr;
1750 while (!getNextTimeEntry(ptr))
1752 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1761 ePtr<eServiceEvent> ptr;
1765 lookupEventId(ref, event_id, ptr);
1767 lookupEventTime(ref, stime, ptr, type);
1769 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1773 if (service_changed)
1776 Py_DECREF(service_name);
1781 if (convertFuncArgs)
1782 Py_DECREF(convertFuncArgs);
1788 void fillTuple2(PyObject *tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, PyObject *service_name, PyObject *service_reference)
1792 while(pos < argcount)
1794 bool inc_refcount=false;
1795 switch(argstring[pos])
1797 case '0': // PyLong 0
1798 tmp = PyLong_FromLong(0);
1800 case 'I': // Event Id
1801 tmp = PyLong_FromLong(evData->getEventID());
1803 case 'B': // Event Begin Time
1805 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1807 tmp = PyLong_FromLong(evData->getStartTime());
1809 case 'D': // Event Duration
1811 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1813 tmp = PyLong_FromLong(evData->getDuration());
1815 case 'T': // Event Title
1816 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1818 case 'S': // Event Short Description
1819 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1821 case 'E': // Event Extended Description
1822 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1824 case 'R': // service reference string
1825 tmp = service_reference;
1826 inc_refcount = true;
1828 case 'N': // service name
1830 inc_refcount = true;
1836 inc_refcount = true;
1840 PyTuple_SET_ITEM(tuple, pos++, tmp);
1844 // here we get a python tuple
1845 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1847 // B = Event Begin Time
1848 // D = Event Duration
1850 // S = Event Short Description
1851 // E = Event Extended Description
1852 // R = Service Reference
1854 // the second tuple entry is the MAX matches value
1855 // the third tuple entry is the type of query
1856 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1857 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1858 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1859 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1860 // the fourth is the servicereference string
1861 // the fifth is the eventid
1862 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1863 // the fourth is the search text
1865 // 0 = case sensitive (CASE_CHECK)
1866 // 1 = case insensitive (NO_CASECHECK)
1868 PyObject *eEPGCache::search(PyObject *arg)
1874 const char *argstring=0;
1878 bool needServiceEvent=false;
1881 if (PyTuple_Check(arg))
1883 int tuplesize=PyTuple_Size(arg);
1886 PyObject *obj = PyTuple_GET_ITEM(arg,0);
1887 if (PyString_Check(obj))
1889 argcount = PyString_GET_SIZE(obj);
1890 argstring = PyString_AS_STRING(obj);
1891 for (int i=0; i < argcount; ++i)
1892 switch(argstring[i])
1897 needServiceEvent=true;
1904 PyErr_SetString(PyExc_StandardError,
1906 eDebug("tuple arg 0 is not a string");
1911 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1914 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1915 if (tuplesize > 4 && querytype == 0)
1917 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1918 if (PyString_Check(obj))
1920 refstr = PyString_AS_STRING(obj);
1921 eServiceReferenceDVB ref(refstr);
1924 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1925 singleLock s(cache_lock);
1926 const eventData *evData = 0;
1927 lookupEventId(ref, eventid, evData);
1930 __u8 *data = evData->EITdata;
1931 int tmp = evData->ByteSize-12;
1932 __u32 *p = (__u32*)(data+12);
1933 // search short and extended event descriptors
1937 descriptorMap::iterator it =
1938 eventData::descriptors.find(crc);
1939 if (it != eventData::descriptors.end())
1941 __u8 *descr_data = it->second.second;
1942 switch(descr_data[0])
1945 descr[++descridx]=crc;
1954 eDebug("event not found");
1958 PyErr_SetString(PyExc_StandardError,
1960 eDebug("tuple arg 4 is not a valid service reference string");
1966 PyErr_SetString(PyExc_StandardError,
1968 eDebug("tuple arg 4 is not a string");
1972 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
1974 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1975 if (PyString_Check(obj))
1977 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1978 const char *str = PyString_AS_STRING(obj);
1979 int textlen = PyString_GET_SIZE(obj);
1981 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
1983 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
1984 singleLock s(cache_lock);
1985 for (descriptorMap::iterator it(eventData::descriptors.begin());
1986 it != eventData::descriptors.end() && descridx < 511; ++it)
1988 __u8 *data = it->second.second;
1989 if ( data[0] == 0x4D ) // short event descriptor
1991 int title_len = data[5];
1992 if ( querytype == 1 )
1994 if (title_len > textlen)
1996 else if (title_len < textlen)
2000 if ( !strncasecmp((const char*)data+6, str, title_len) )
2002 // std::string s((const char*)data+6, title_len);
2003 // eDebug("match1 %s %s", str, s.c_str() );
2004 descr[++descridx] = it->first;
2007 else if ( !strncmp((const char*)data+6, str, title_len) )
2009 // std::string s((const char*)data+6, title_len);
2010 // eDebug("match2 %s %s", str, s.c_str() );
2011 descr[++descridx] = it->first;
2017 while((title_len-idx) >= textlen)
2021 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2023 descr[++descridx] = it->first;
2024 // std::string s((const char*)data+6, title_len);
2025 // eDebug("match 3 %s %s", str, s.c_str() );
2028 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2030 descr[++descridx] = it->first;
2031 // std::string s((const char*)data+6, title_len);
2032 // eDebug("match 4 %s %s", str, s.c_str() );
2044 PyErr_SetString(PyExc_StandardError,
2046 eDebug("tuple arg 4 is not a string");
2052 PyErr_SetString(PyExc_StandardError,
2054 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2060 PyErr_SetString(PyExc_StandardError,
2062 eDebug("not enough args in tuple");
2068 PyErr_SetString(PyExc_StandardError,
2070 eDebug("arg 0 is not a tuple");
2076 int maxcount=maxmatches;
2077 eServiceReferenceDVB ref(refstr?refstr:"");
2078 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2079 // in this case we start searching with the base service
2080 bool first = ref.valid() ? true : false;
2081 singleLock s(cache_lock);
2082 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2083 while(cit != eventDB.end() && maxcount)
2085 if ( ref.valid() && !first && cit->first == ref )
2087 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2091 PyObject *service_name=0;
2092 PyObject *service_reference=0;
2093 timeMap &evmap = cit->second.second;
2095 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2097 if (evit->second->getEventID() == eventid)
2099 __u8 *data = evit->second->EITdata;
2100 int tmp = evit->second->ByteSize-12;
2101 __u32 *p = (__u32*)(data+12);
2102 // check if any of our descriptor used by this event
2107 for ( int i=0; i <= descridx; ++i)
2109 if (descr[i] == crc32) // found...
2114 if ( (querytype == 0 && cnt == descridx) ||
2115 ((querytype == 1 || querytype == 2) && cnt != -1) )
2117 const uniqueEPGKey &service = cit->first;
2118 eServiceReference ref =
2119 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2122 // create servive event
2123 ePtr<eServiceEvent> ptr;
2124 if (needServiceEvent)
2126 lookupEventId(ref, evit->first, ptr);
2128 eDebug("event not found !!!!!!!!!!!");
2130 // create service name
2131 if (!service_name && strchr(argstring,'N'))
2133 ePtr<iStaticServiceInformation> sptr;
2134 eServiceCenterPtr service_center;
2135 eServiceCenter::getPrivInstance(service_center);
2138 service_center->info(ref, sptr);
2142 sptr->getName(ref, name);
2144 service_name = PyString_FromString(name.c_str());
2148 service_name = PyString_FromString("<n/a>");
2150 // create servicereference string
2151 if (!service_reference && strchr(argstring,'R'))
2152 service_reference = PyString_FromString(ref.toString().c_str());
2155 ret = PyList_New(0);
2157 PyObject *tuple = PyTuple_New(argcount);
2159 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2160 PyList_Append(ret, tuple);
2167 Py_DECREF(service_name);
2168 if (service_reference)
2169 Py_DECREF(service_reference);
2172 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2174 cit=eventDB.begin();
2190 #ifdef ENABLE_PRIVATE_EPG
2191 #include <dvbsi++/descriptor_tag.h>
2192 #include <dvbsi++/unknown_descriptor.h>
2193 #include <dvbsi++/private_data_specifier_descriptor.h>
2195 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2197 ePtr<eTable<ProgramMapSection> > ptr;
2198 if (!pmthandler->getPMT(ptr) && ptr)
2200 std::vector<ProgramMapSection*>::const_iterator i;
2201 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2203 const ProgramMapSection &pmt = **i;
2205 ElementaryStreamInfoConstIterator es;
2206 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2209 switch ((*es)->getType())
2211 case 0x05: // private
2212 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2213 desc != (*es)->getDescriptors()->end(); ++desc)
2215 switch ((*desc)->getTag())
2217 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2218 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2223 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2224 int descr_len = descr->getLength();
2227 uint8_t data[descr_len+2];
2228 descr->writeToBuffer(data);
2229 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2243 eServiceReferenceDVB ref;
2244 if (!pmthandler->getServiceReference(ref))
2246 int pid = (*es)->getPid();
2247 messages.send(Message(Message::got_private_pid, ref, pid));
2255 eDebug("PMTready but no pmt!!");
2262 date_time( const date_time &a )
2264 memcpy(data, a.data, 5);
2267 date_time( const __u8 data[5])
2269 memcpy(this->data, data, 5);
2270 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2275 const __u8& operator[](int pos) const
2281 struct less_datetime
2283 bool operator()( const date_time &a, const date_time &b ) const
2285 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2289 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2291 contentMap &content_time_table = content_time_tables[current_service];
2292 singleLock s(cache_lock);
2293 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2294 eventMap &evMap = eventDB[current_service].first;
2295 timeMap &tmMap = eventDB[current_service].second;
2297 int content_id = data[ptr++] << 24;
2298 content_id |= data[ptr++] << 16;
2299 content_id |= data[ptr++] << 8;
2300 content_id |= data[ptr++];
2302 contentTimeMap &time_event_map =
2303 content_time_table[content_id];
2304 for ( contentTimeMap::iterator it( time_event_map.begin() );
2305 it != time_event_map.end(); ++it )
2307 eventMap::iterator evIt( evMap.find(it->second.second) );
2308 if ( evIt != evMap.end() )
2310 delete evIt->second;
2313 tmMap.erase(it->second.first);
2315 time_event_map.clear();
2318 memcpy(duration, data+ptr, 3);
2321 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2323 const __u8 *descriptors[65];
2324 const __u8 **pdescr = descriptors;
2326 int descriptors_length = (data[ptr++]&0x0F) << 8;
2327 descriptors_length |= data[ptr++];
2328 while ( descriptors_length > 0 )
2330 int descr_type = data[ptr];
2331 int descr_len = data[ptr+1];
2332 descriptors_length -= (descr_len+2);
2333 if ( descr_type == 0xf2 )
2336 int tsid = data[ptr++] << 8;
2337 tsid |= data[ptr++];
2338 int onid = data[ptr++] << 8;
2339 onid |= data[ptr++];
2340 int sid = data[ptr++] << 8;
2343 // WORKAROUND for wrong transmitted epg data
2344 if ( onid == 0x85 && tsid == 0x11 && sid == 0xd3 ) // premiere sends wrong tsid here
2346 else if ( onid == 0x85 && tsid == 0x3 && sid == 0xf5 ) // premiere sends wrong sid here
2348 ////////////////////////////////////////////
2350 uniqueEPGKey service( sid, onid, tsid );
2352 while( descr_len > 0 )
2355 datetime[0] = data[ptr++];
2356 datetime[1] = data[ptr++];
2357 int tmp_len = data[ptr++];
2359 while( tmp_len > 0 )
2361 memcpy(datetime+2, data+ptr, 3);
2365 start_times[datetime].push_back(service);
2377 eit_event_struct *ev_struct = (eit_event_struct*) event;
2378 ev_struct->running_status = 0;
2379 ev_struct->free_CA_mode = 1;
2380 memcpy(event+7, duration, 3);
2382 const __u8 **d=descriptors;
2383 while ( d < pdescr )
2385 memcpy(event+ptr, *d, ((*d)[1])+2);
2389 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2391 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2392 if ( (it->first.tm + duration_sec) < now )
2394 memcpy(event+2, it->first.data, 5);
2397 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2399 event[bptr++] = 0x4A;
2400 __u8 *len = event+(bptr++);
2401 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2402 event[bptr++] = (i->tsid & 0xFF);
2403 event[bptr++] = (i->onid & 0xFF00) >> 8;
2404 event[bptr++] = (i->onid & 0xFF);
2405 event[bptr++] = (i->sid & 0xFF00) >> 8;
2406 event[bptr++] = (i->sid & 0xFF);
2407 event[bptr++] = 0xB0;
2408 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2409 *len = ((event+bptr) - len)-1;
2411 int llen = bptr - 12;
2412 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2413 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2415 time_t stime = it->first.tm;
2416 while( tmMap.find(stime) != tmMap.end() )
2418 event[6] += (stime - it->first.tm);
2420 while( evMap.find(event_id) != evMap.end() )
2422 event[0] = (event_id & 0xFF00) >> 8;
2423 event[1] = (event_id & 0xFF);
2424 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2425 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2426 evMap[event_id] = d;
2431 void eEPGCache::channel_data::startPrivateReader()
2433 eDVBSectionFilterMask mask;
2434 memset(&mask, 0, sizeof(mask));
2435 mask.pid = m_PrivatePid;
2436 mask.flags = eDVBSectionFilterMask::rfCRC;
2437 mask.data[0] = 0xA0;
2438 mask.mask[0] = 0xFF;
2439 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2440 if (m_PrevVersion != -1)
2442 mask.data[3] = m_PrevVersion << 1;
2443 mask.mask[3] = 0x3E;
2444 mask.mode[3] = 0x3E;
2446 seenPrivateSections.clear();
2448 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2449 m_PrivateReader->start(mask);
2452 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2454 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2456 cache->privateSectionRead(m_PrivateService, data);
2457 seenPrivateSections.insert(data[6]);
2459 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2461 eDebug("[EPGC] private finished");
2462 m_PrevVersion = (data[5] & 0x3E) >> 1;
2463 startPrivateReader();
2467 #endif // ENABLE_PRIVATE_EPG
2469 #ifdef ENABLE_MHW_EPG
2470 void eEPGCache::channel_data::cleanup()
2475 m_program_ids.clear();
2478 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2480 // Names in mhw structs are not strings as they are not '\0' terminated.
2481 // This function converts the mhw name into a string.
2482 // Constraint: "length of out" = "length of in" + 1.
2484 for ( i=0; i < len_in; i++ )
2488 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2495 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2498 return_time[0] = toBCD( hours );
2499 return_time[1] = toBCD( minutes );
2503 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2505 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2508 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2509 // For date plus time of day
2511 // Remove offset in mhw time.
2512 __u8 local_hours = hours;
2515 else if ( hours >= 8 )
2518 // As far as we know all mhw time data is sent in central Europe time zone.
2519 // So, temporarily set timezone to western europe
2520 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2522 char *old_tz = getenv( "TZ" );
2523 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2526 tm *localnow = localtime( &dt );
2530 if ( day + 1 < localnow->tm_wday ) // day + 1 to prevent old events to show for next week.
2532 if (local_hours <= 5)
2535 dt += 3600*24*(day - localnow->tm_wday); // Shift dt to the recording date (local time zone).
2536 dt += 3600*(local_hours - localnow->tm_hour); // Shift dt to the recording hour.
2538 tm *recdate = gmtime( &dt ); // This will also take care of DST.
2540 if ( old_tz == NULL )
2546 // Calculate MJD according to annex in ETSI EN 300 468
2548 if ( recdate->tm_mon <= 1 ) // Jan or Feb
2550 int mjd = 14956 + recdate->tm_mday + int( (recdate->tm_year - l) * 365.25) +
2551 int( (recdate->tm_mon + 2 + l * 12) * 30.6001);
2553 return_time[0] = (mjd & 0xFF00)>>8;
2554 return_time[1] = mjd & 0xFF;
2556 timeMHW2DVB( recdate->tm_hour, minutes, return_time+2 );
2559 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2560 // data is borrowed from calling proc to save memory space.
2562 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2565 eit_t *packet = (eit_t *) data;
2566 packet->table_id = 0x50;
2567 packet->section_syntax_indicator = 1;
2568 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2569 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2570 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2571 packet->current_next_indicator = 0;
2572 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2573 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2574 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2575 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2576 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2577 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2578 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2579 packet->segment_last_table_id = 0x50;
2581 std::string prog_title = (char *) delimitName( itTitle->second.title, name, 23 );
2582 int prog_title_length = prog_title.length();
2584 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2585 prog_title_length + 1;
2587 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2588 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2589 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2591 timeMHW2DVB( itTitle->second.day, itTitle->second.hours, itTitle->second.minutes,
2592 (u_char *) event_data + 2 );
2593 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2595 event_data->running_status = 0;
2596 event_data->free_CA_mode = 0;
2597 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2599 eit_short_event_descriptor_struct *short_event_descriptor =
2600 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2601 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2602 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2603 prog_title_length - 1;
2604 short_event_descriptor->language_code_1 = 'e';
2605 short_event_descriptor->language_code_2 = 'n';
2606 short_event_descriptor->language_code_3 = 'g';
2607 short_event_descriptor->event_name_length = prog_title_length;
2608 delimitName( itTitle->second.title, name, 23 );
2609 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2610 memcpy(event_name, name, prog_title_length);
2613 event_name[prog_title_length] = 0;
2615 if ( sumText.length() > 0 )
2616 // There is summary info
2618 unsigned int sum_length = sumText.length();
2619 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2620 // Store summary in short event descriptor
2622 // Increase all relevant lengths
2623 event_name[prog_title_length] = sum_length;
2624 short_event_descriptor->descriptor_length += sum_length;
2625 packet_length += sum_length;
2626 descr_ll += sum_length;
2627 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2630 // Store summary in extended event descriptors
2632 int remaining_sum_length = sumText.length();
2633 int nbr_descr = int(remaining_sum_length/247) + 1;
2634 for ( int i=0; i < nbr_descr; i++)
2635 // Loop once per extended event descriptor
2637 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2638 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2639 remaining_sum_length -= sum_length;
2640 packet_length += 8 + sum_length;
2641 descr_ll += 8 + sum_length;
2643 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2644 ext_event_descriptor->descriptor_length = sum_length + 6;
2645 ext_event_descriptor->descriptor_number = i;
2646 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2647 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2648 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2649 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2650 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2652 the_text[-1] = sum_length;
2653 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2657 // Add content descriptor
2658 u_char *descriptor = (u_char *) data + packet_length;
2663 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2664 if ( content_descr.find( "FILM" ) != std::string::npos )
2666 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2669 descriptor[0] = 0x54;
2671 descriptor[2] = content_id;
2674 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2675 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2677 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2678 packet->section_length_lo = (packet_length - 3)&0xff;
2680 // Feed the data to eEPGCache::sectionRead()
2681 cache->sectionRead( data, MHW, this );
2684 void eEPGCache::channel_data::startTimeout(int msec)
2686 m_MHWTimeoutTimer.start(msec,true);
2687 m_MHWTimeoutet=false;
2690 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2692 m_MHWFilterMask.pid = pid;
2693 m_MHWFilterMask.data[0] = tid;
2694 m_MHWReader->start(m_MHWFilterMask);
2695 // eDebug("start 0x%02x 0x%02x", pid, tid);
2698 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2700 if ( state > 1 || // aborted
2701 // have si data.. so we dont read mhw data
2702 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2704 eDebug("[EPGC] mhw aborted %d", state);
2706 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2709 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2710 int record_size = sizeof( mhw_channel_name_t );
2711 int nbr_records = int (len/record_size);
2713 for ( int i = 0; i < nbr_records; i++ )
2715 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2716 m_channels.push_back( *channel );
2720 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2722 // Channels table has been read, start reading the themes table.
2723 startMHWReader(0xD3, 0x92);
2726 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2729 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2730 int record_size = sizeof( mhw_theme_name_t );
2731 int nbr_records = int (len/record_size);
2733 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2736 for ( int i = 0; i < nbr_records; i++ )
2738 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2739 if ( i >= next_idx )
2743 next_idx = (__u8) *(data + 3 + idx_ptr);
2749 m_themes[idx+sub_idx] = *theme;
2751 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2752 // Themes table has been read, start reading the titles table.
2753 startMHWReader(0xD2, 0x90);
2757 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2760 mhw_title_t *title = (mhw_title_t*) data;
2762 if ( title->channel_id == 0xFF ) // Separator
2763 return; // Continue reading of the current table.
2766 // Create unique key per title
2767 __u32 title_id = ((title->channel_id)<<16)|((title->day)<<13)|((title->hours)<<8)|
2769 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2770 ((title->program_id_ml)<<8)|(title->program_id_lo);
2772 if ( m_titles.find( title_id ) == m_titles.end() )
2775 m_titles[ title_id ] = *title;
2776 if ( (title->summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2777 // program_ids will be used to gather summaries.
2778 m_program_ids[ program_id ] = title_id;
2779 return; // Continue reading of the current table.
2781 else if (!checkTimeout())
2784 if ( !m_program_ids.empty())
2786 // Titles table has been read, there are summaries to read.
2787 // Start reading summaries, store corresponding titles on the fly.
2788 startMHWReader(0xD3, 0x90);
2789 eDebug("[EPGC] mhw %d titles(%d with summary) found",
2791 m_program_ids.size());
2796 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2799 mhw_summary_t *summary = (mhw_summary_t*) data;
2801 // Create unique key per record
2802 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2803 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2804 int len = ((data[1]&0xf)<<8) + data[2];
2806 // ugly workaround to convert const __u8* to char*
2808 memcpy(&tmp, &data, sizeof(void*));
2809 tmp[len+3] = 0; // Terminate as a string.
2811 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2812 if ( itProgid == m_program_ids.end() )
2813 { /* This part is to prevent to looping forever if some summaries are not received yet.
2814 There is a timeout of 4 sec. after the last successfully read summary. */
2815 if (!m_program_ids.empty() && !checkTimeout())
2816 return; // Continue reading of the current table.
2820 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2823 while((pos = the_text.find("\r\n")) != std::string::npos)
2824 the_text.replace(pos, 2, " ");
2826 // Find corresponding title, store title and summary in epgcache.
2827 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2828 if ( itTitle != m_titles.end() )
2831 storeTitle( itTitle, the_text, data );
2832 m_titles.erase( itTitle );
2834 m_program_ids.erase( itProgid );
2835 if ( !m_program_ids.empty() )
2836 return; // Continue reading of the current table.
2839 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
2840 eDVBLocalTimeHandler::getInstance()->nowTime(),
2841 m_program_ids.size());
2842 // Summaries have been read, titles that have summaries have been stored.
2843 // Now store titles that do not have summaries.
2844 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
2845 storeTitle( itTitle, "", data );
2849 m_MHWReader->stop();