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>
18 #include <dvbsi++/descriptor_tag.h>
20 int eventData::CacheSize=0;
21 descriptorMap eventData::descriptors;
22 __u8 eventData::data[4108];
23 extern const uint32_t crc32_table[256];
25 const eServiceReference &handleGroup(const eServiceReference &ref)
27 if (ref.flags & eServiceReference::isGroup)
29 ePtr<eDVBResourceManager> res;
30 if (!eDVBResourceManager::getInstance(res))
32 ePtr<iDVBChannelList> db;
33 if (!res->getChannelList(db))
36 if (!db->getBouquet(ref, bouquet))
38 std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
39 if (it != bouquet->m_services.end())
49 eventData::eventData(const eit_event_struct* e, int size, int type)
50 :ByteSize(size&0xFF), type(type&0xFF)
58 __u8 *data = (__u8*)e;
64 __u8 *descr = data+ptr;
65 int descr_len = descr[1];
67 if (size >= descr_len)
71 case EXTENDED_EVENT_DESCRIPTOR:
72 case SHORT_EVENT_DESCRIPTOR:
73 case LINKAGE_DESCRIPTOR:
74 case COMPONENT_DESCRIPTOR:
78 while(cnt++ < descr_len)
79 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
81 descriptorMap::iterator it =
82 descriptors.find(crc);
83 if ( it == descriptors.end() )
86 __u8 *d = new __u8[descr_len];
87 memcpy(d, descr, descr_len);
88 descriptors[crc] = descriptorPair(1, d);
95 default: // do not cache all other descriptors
104 ASSERT(pdescr <= &descr[65]);
105 ByteSize = 10+((pdescr-descr)*4);
106 EITdata = new __u8[ByteSize];
108 memcpy(EITdata, (__u8*) e, 10);
109 memcpy(EITdata+10, descr, ByteSize-10);
112 const eit_event_struct* eventData::get() const
115 int tmp = ByteSize-10;
116 memcpy(data, EITdata, 10);
117 int descriptors_length=0;
118 __u32 *p = (__u32*)(EITdata+10);
121 descriptorMap::iterator it =
122 descriptors.find(*p++);
123 if ( it != descriptors.end() )
125 int b = it->second.second[1]+2;
126 memcpy(data+pos, it->second.second, b );
128 descriptors_length += b;
131 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(p-1));
135 data[10] = (descriptors_length >> 8) & 0x0F;
136 data[11] = descriptors_length & 0xFF;
137 return (eit_event_struct*)data;
140 eventData::~eventData()
144 CacheSize -= ByteSize;
145 __u32 *d = (__u32*)(EITdata+10);
149 descriptorMap::iterator it =
150 descriptors.find(*d++);
151 if ( it != descriptors.end() )
153 descriptorPair &p = it->second;
154 if (!--p.first) // no more used descriptor
156 CacheSize -= it->second.second[1];
157 delete [] it->second.second; // free descriptor memory
158 descriptors.erase(it); // remove entry from descriptor map
162 eFatal("LINE %d descriptor not found in descriptor cache %08x!!!!!!", __LINE__, *(d-1));
169 void eventData::load(FILE *f)
175 fread(&size, sizeof(int), 1, f);
178 fread(&id, sizeof(__u32), 1, f);
179 fread(&p.first, sizeof(int), 1, f);
180 fread(header, 2, 1, f);
181 int bytes = header[1]+2;
182 p.second = new __u8[bytes];
183 p.second[0] = header[0];
184 p.second[1] = header[1];
185 fread(p.second+2, bytes-2, 1, f);
192 void eventData::save(FILE *f)
194 int size=descriptors.size();
195 descriptorMap::iterator it(descriptors.begin());
196 fwrite(&size, sizeof(int), 1, f);
199 fwrite(&it->first, sizeof(__u32), 1, f);
200 fwrite(&it->second.first, sizeof(int), 1, f);
201 fwrite(it->second.second, it->second.second[1]+2, 1, f);
207 eEPGCache* eEPGCache::instance;
208 pthread_mutex_t eEPGCache::cache_lock=
209 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
210 pthread_mutex_t eEPGCache::channel_map_lock=
211 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
213 DEFINE_REF(eEPGCache)
215 eEPGCache::eEPGCache()
216 :messages(this,1), cleanTimer(this)//, paused(0)
218 eDebug("[EPGC] Initialized EPGCache");
220 CONNECT(messages.recv_msg, eEPGCache::gotMessage);
221 CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
222 CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
224 ePtr<eDVBResourceManager> res_mgr;
225 eDVBResourceManager::getInstance(res_mgr);
227 eDebug("[eEPGCache] no resource manager !!!!!!!");
229 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
233 void eEPGCache::timeUpdated()
237 eDebug("[EPGC] time updated.. start EPG Mainloop");
240 messages.send(Message(Message::timeChanged));
243 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
247 // eDebug("[eEPGCache] add channel %p", chan);
248 channel_data *data = new channel_data(this);
249 data->channel = chan;
250 data->prevChannelState = -1;
251 #ifdef ENABLE_PRIVATE_EPG
252 data->m_PrivatePid = -1;
254 singleLock s(channel_map_lock);
255 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
256 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
260 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
262 channelMapIterator it =
263 m_knownChannels.find(chan);
264 if ( it == m_knownChannels.end() )
265 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
268 channel_data &data = *it->second;
269 ePtr<eDVBResourceManager> res_mgr;
270 if ( eDVBResourceManager::getInstance( res_mgr ) )
271 eDebug("[eEPGCache] no res manager!!");
274 ePtr<iDVBDemux> demux;
275 if ( data.channel->getDemux(demux, 0) )
277 eDebug("[eEPGCache] no demux!!");
282 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
285 eDebug("[eEPGCache] couldnt initialize nownext reader!!");
289 res = demux->createSectionReader( this, data.m_ScheduleReader );
292 eDebug("[eEPGCache] couldnt initialize schedule reader!!");
296 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
299 eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
302 #ifdef ENABLE_PRIVATE_EPG
303 res = demux->createSectionReader( this, data.m_PrivateReader );
306 eDebug("[eEPGCache] couldnt initialize private reader!!");
310 #ifdef ENABLE_MHW_EPG
311 res = demux->createSectionReader( this, data.m_MHWReader );
314 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
317 res = demux->createSectionReader( this, data.m_MHWReader2 );
320 eDebug("[eEPGCache] couldnt initialize mhw reader!!");
324 messages.send(Message(Message::startChannel, chan));
325 // -> gotMessage -> changedService
331 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
333 channelMapIterator it =
334 m_knownChannels.find(chan);
335 if ( it != m_knownChannels.end() )
338 chan->getState(state);
339 if ( it->second->prevChannelState != state )
343 case iDVBChannel::state_ok:
345 eDebug("[eEPGCache] channel %p running", chan);
346 DVBChannelRunning(chan);
349 case iDVBChannel::state_release:
351 eDebug("[eEPGCache] remove channel %p", chan);
352 messages.send(Message(Message::leaveChannel, chan));
353 pthread_mutex_lock(&it->second->channel_active);
354 singleLock s(channel_map_lock);
355 m_knownChannels.erase(it);
356 pthread_mutex_unlock(&it->second->channel_active);
359 // -> gotMessage -> abortEPG
362 default: // ignore all other events
366 it->second->prevChannelState = state;
371 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
373 timeMap::iterator tmp = tm_it;
374 while ((tmp->first+tmp->second->getDuration()-300) > TM)
377 #ifdef ENABLE_PRIVATE_EPG
378 && tmp->second->type != PRIVATE
381 && tmp->second->type != MHW
385 __u16 event_id = tmp->second->getEventID();
386 servicemap.first.erase(event_id);
388 Event evt((uint8_t*)tmp->second->get());
390 event.parseFrom(&evt, service.sid<<16|service.onid);
391 eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
392 service.sid, event_id,
393 event.getBeginTimeString().c_str(),
394 event.getEventName().c_str(),
395 event.getExtendedDescription().c_str());
398 if (tmp == servicemap.second.begin())
400 servicemap.second.erase(tmp);
404 servicemap.second.erase(tmp--);
408 if (tmp == servicemap.second.begin())
415 while(tmp->first < (TM+duration-300))
417 if (tmp->first != TM && tmp->second->type != PRIVATE)
419 __u16 event_id = tmp->second->getEventID();
420 servicemap.first.erase(event_id);
422 Event evt((uint8_t*)tmp->second->get());
424 event.parseFrom(&evt, service.sid<<16|service.onid);
425 eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
426 service.sid, event_id,
427 event.getBeginTimeString().c_str(),
428 event.getEventName().c_str(),
429 event.getExtendedDescription().c_str());
432 servicemap.second.erase(tmp++);
436 if (tmp == servicemap.second.end())
441 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
443 eit_t *eit = (eit_t*) data;
445 int len=HILO(eit->section_length)-1;//+3-4;
450 // This fixed the EPG on the Multichoice irdeto systems
451 // the EIT packet is non-compliant.. their EIT packet stinks
452 if ( data[ptr-1] < 0x40 )
455 uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
456 eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
460 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);
461 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
463 if ( TM != 3599 && TM > -1)
464 channel->haveData |= source;
466 singleLock s(cache_lock);
467 // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
468 // oder eine durch [] erzeugte
469 std::pair<eventMap,timeMap> &servicemap = eventDB[service];
470 eventMap::iterator prevEventIt = servicemap.first.end();
471 timeMap::iterator prevTimeIt = servicemap.second.end();
475 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
477 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
479 eit_event->start_time_1,
480 eit_event->start_time_2,
481 eit_event->start_time_3,
482 eit_event->start_time_4,
483 eit_event->start_time_5);
488 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
491 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ ) // old events should not be cached
493 __u16 event_id = HILO(eit_event->event_id);
494 // eDebug("event_id is %d sid is %04x", event_id, service.sid);
497 int ev_erase_count = 0;
498 int tm_erase_count = 0;
500 // search in eventmap
501 eventMap::iterator ev_it =
502 servicemap.first.find(event_id);
504 // entry with this event_id is already exist ?
505 if ( ev_it != servicemap.first.end() )
507 if ( source > ev_it->second->type ) // update needed ?
508 goto next; // when not.. then skip this entry
510 // search this event in timemap
511 timeMap::iterator tm_it_tmp =
512 servicemap.second.find(ev_it->second->getStartTime());
514 if ( tm_it_tmp != servicemap.second.end() )
516 if ( tm_it_tmp->first == TM ) // just update eventdata
519 delete ev_it->second;
520 ev_it->second = tm_it_tmp->second =
521 new eventData(eit_event, eit_event_size, source);
522 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
525 else // event has new event begin time
528 // delete the found record from timemap
529 servicemap.second.erase(tm_it_tmp);
530 prevTimeIt=servicemap.second.end();
535 // search in timemap, for check of a case if new time has coincided with time of other event
536 // or event was is not found in eventmap
537 timeMap::iterator tm_it =
538 servicemap.second.find(TM);
540 if ( tm_it != servicemap.second.end() )
542 // event with same start time but another event_id...
543 if ( source > tm_it->second->type &&
544 ev_it == servicemap.first.end() )
545 goto next; // when not.. then skip this entry
547 // search this time in eventmap
548 eventMap::iterator ev_it_tmp =
549 servicemap.first.find(tm_it->second->getEventID());
551 if ( ev_it_tmp != servicemap.first.end() )
554 // delete the found record from eventmap
555 servicemap.first.erase(ev_it_tmp);
556 prevEventIt=servicemap.first.end();
559 evt = new eventData(eit_event, eit_event_size, source);
561 bool consistencyCheck=true;
563 if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
566 delete ev_it->second;
567 delete tm_it->second;
571 else if (ev_erase_count == 0 && tm_erase_count > 0)
574 delete ev_it->second;
575 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
578 else if (ev_erase_count > 0 && tm_erase_count == 0)
581 delete tm_it->second;
582 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
585 else // added new eventData
588 consistencyCheck=false;
590 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
591 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
594 FixOverlapping(servicemap, TM, duration, tm_it, service);
597 if ( consistencyCheck )
599 if ( tm_it->second != evt || ev_it->second != evt )
600 eFatal("tm_it->second != ev_it->second");
601 else if ( tm_it->second->getStartTime() != tm_it->first )
602 eFatal("event start_time(%d) non equal timemap key(%d)",
603 tm_it->second->getStartTime(), tm_it->first );
604 else if ( tm_it->first != TM )
605 eFatal("timemap key(%d) non equal TM(%d)",
607 else if ( ev_it->second->getEventID() != ev_it->first )
608 eFatal("event_id (%d) non equal event_map key(%d)",
609 ev_it->second->getEventID(), ev_it->first);
610 else if ( ev_it->first != event_id )
611 eFatal("eventmap key(%d) non equal event_id(%d)",
612 ev_it->first, event_id );
618 if ( servicemap.first.size() != servicemap.second.size() )
620 FILE *f = fopen("/hdd/event_map.txt", "w+");
622 for (eventMap::iterator it(servicemap.first.begin())
623 ; it != servicemap.first.end(); ++it )
624 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
625 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
627 f = fopen("/hdd/time_map.txt", "w+");
629 for (timeMap::iterator it(servicemap.second.begin())
630 ; it != servicemap.second.end(); ++it )
631 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n",
632 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
635 eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d",
636 service.sid, service.tsid, service.onid,
637 servicemap.first.size(), servicemap.second.size() );
640 ptr += eit_event_size;
641 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
645 void eEPGCache::flushEPG(const uniqueEPGKey & s)
647 eDebug("[EPGC] flushEPG %d", (int)(bool)s);
648 singleLock l(cache_lock);
649 if (s) // clear only this service
651 eventCache::iterator it = eventDB.find(s);
652 if ( it != eventDB.end() )
654 eventMap &evMap = it->second.first;
655 timeMap &tmMap = it->second.second;
657 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
662 // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
663 #ifdef ENABLE_PRIVATE_EPG
664 contentMaps::iterator it =
665 content_time_tables.find(s);
666 if ( it != content_time_tables.end() )
669 content_time_tables.erase(it);
674 else // clear complete EPG Cache
676 for (eventCache::iterator it(eventDB.begin());
677 it != eventDB.end(); ++it)
679 eventMap &evMap = it->second.first;
680 timeMap &tmMap = it->second.second;
681 for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
687 #ifdef ENABLE_PRIVATE_EPG
688 content_time_tables.clear();
690 channelLastUpdated.clear();
691 singleLock m(channel_map_lock);
692 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
693 it->second->startEPG();
695 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
698 void eEPGCache::cleanLoop()
700 singleLock s(cache_lock);
701 if (!eventDB.empty())
703 eDebug("[EPGC] start cleanloop");
705 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
707 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
709 bool updated = false;
710 for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
712 if ( now > (It->first+It->second->getDuration()) ) // outdated normal entry (nvod references to)
714 // remove entry from eventMap
715 eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
716 if ( b != DBIt->second.first.end() )
718 // release Heap Memory for this entry (new ....)
719 // eDebug("[EPGC] delete old event (evmap)");
720 DBIt->second.first.erase(b);
723 // remove entry from timeMap
724 // eDebug("[EPGC] release heap mem");
726 DBIt->second.second.erase(It++);
727 // eDebug("[EPGC] delete old event (timeMap)");
733 #ifdef ENABLE_PRIVATE_EPG
736 contentMaps::iterator x =
737 content_time_tables.find( DBIt->first );
738 if ( x != content_time_tables.end() )
740 timeMap &tmMap = DBIt->second.second;
741 for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
743 for ( contentTimeMap::iterator it(i->second.begin());
744 it != i->second.end(); )
746 if ( tmMap.find(it->second.first) == tmMap.end() )
747 i->second.erase(it++);
751 if ( i->second.size() )
754 x->second.erase(i++);
760 eDebug("[EPGC] stop cleanloop");
761 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
763 cleanTimer.start(CLEAN_INTERVAL,true);
766 eEPGCache::~eEPGCache()
768 messages.send(Message::quit);
769 kill(); // waiting for thread shutdown
770 singleLock s(cache_lock);
771 for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
772 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
776 void eEPGCache::gotMessage( const Message &msg )
781 flushEPG(msg.service);
783 case Message::startChannel:
785 singleLock s(channel_map_lock);
786 channelMapIterator channel =
787 m_knownChannels.find(msg.channel);
788 if ( channel != m_knownChannels.end() )
789 channel->second->startChannel();
792 case Message::leaveChannel:
794 singleLock s(channel_map_lock);
795 channelMapIterator channel =
796 m_knownChannels.find(msg.channel);
797 if ( channel != m_knownChannels.end() )
798 channel->second->abortEPG();
804 #ifdef ENABLE_PRIVATE_EPG
805 case Message::got_private_pid:
807 singleLock s(channel_map_lock);
808 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
810 eDVBChannel *channel = (eDVBChannel*) it->first;
811 channel_data *data = it->second;
812 eDVBChannelID chid = channel->getChannelID();
813 if ( chid.transport_stream_id.get() == msg.service.tsid &&
814 chid.original_network_id.get() == msg.service.onid &&
815 data->m_PrivatePid == -1 )
817 data->m_PrevVersion = -1;
818 data->m_PrivatePid = msg.pid;
819 data->m_PrivateService = msg.service;
820 int onid = chid.original_network_id.get();
821 onid |= 0x80000000; // we use highest bit as private epg indicator
822 chid.original_network_id = onid;
823 updateMap::iterator It = channelLastUpdated.find( chid );
824 int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
825 if (update < ZAP_DELAY)
827 data->startPrivateTimer.start(update, 1);
829 eDebug("[EPGC] next private update in %i min", update/60000);
830 else if (update >= 1000)
831 eDebug("[EPGC] next private update in %i sec", update/1000);
838 case Message::timeChanged:
842 eDebug("unhandled EPGCache Message!!");
847 void eEPGCache::thread()
857 void eEPGCache::load()
859 singleLock s(cache_lock);
860 FILE *f = fopen("/hdd/epg.dat", "r");
866 unsigned char md5_saved[16];
867 unsigned char md5[16];
870 if (!md5_file("/hdd/epg.dat", 1, md5))
872 FILE *f = fopen("/hdd/epg.dat.md5", "r");
875 fread( md5_saved, 16, 1, f);
877 if ( !memcmp(md5_saved, md5, 16) )
884 unsigned int magic=0;
885 fread( &magic, sizeof(int), 1, f);
886 if (magic != 0x98765432)
888 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
893 fread( text1, 13, 1, f);
894 if ( !strncmp( text1, "ENIGMA_EPG_V7", 13) )
896 fread( &size, sizeof(int), 1, f);
903 fread( &key, sizeof(uniqueEPGKey), 1, f);
904 fread( &size, sizeof(int), 1, f);
910 fread( &type, sizeof(__u8), 1, f);
911 fread( &len, sizeof(__u8), 1, f);
912 event = new eventData(0, len, type);
913 event->EITdata = new __u8[len];
914 eventData::CacheSize+=len;
915 fread( event->EITdata, len, 1, f);
916 evMap[ event->getEventID() ]=event;
917 tmMap[ event->getStartTime() ]=event;
920 eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
923 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
924 #ifdef ENABLE_PRIVATE_EPG
926 fread( text2, 11, 1, f);
927 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
930 fread( &size, sizeof(int), 1, f);
935 fread( &key, sizeof(uniqueEPGKey), 1, f);
936 eventMap &evMap=eventDB[key].first;
937 fread( &size, sizeof(int), 1, f);
942 fread( &content_id, sizeof(int), 1, f);
943 fread( &size, sizeof(int), 1, f);
948 fread( &time1, sizeof(time_t), 1, f);
949 fread( &time2, sizeof(time_t), 1, f);
950 fread( &event_id, sizeof(__u16), 1, f);
951 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
952 eventMap::iterator it =
953 evMap.find(event_id);
954 if (it != evMap.end())
955 it->second->type = PRIVATE;
960 #endif // ENABLE_PRIVATE_EPG
963 eDebug("[EPGC] don't read old epg database");
969 void eEPGCache::save()
973 if (statfs("/hdd", &s)<0)
981 // prevent writes to builtin flash
982 if ( tmp < 1024*1024*50 ) // storage size < 50MB
985 // check for enough free space on storage
988 if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
991 FILE *f = fopen("/hdd/epg.dat", "w");
995 unsigned int magic = 0x98765432;
996 fwrite( &magic, sizeof(int), 1, f);
997 const char *text = "ENIGMA_EPG_V7";
998 fwrite( text, 13, 1, f );
999 int size = eventDB.size();
1000 fwrite( &size, sizeof(int), 1, f );
1001 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
1003 timeMap &timemap = service_it->second.second;
1004 fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
1005 size = timemap.size();
1006 fwrite( &size, sizeof(int), 1, f);
1007 for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
1009 __u8 len = time_it->second->ByteSize;
1010 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
1011 fwrite( &len, sizeof(__u8), 1, f);
1012 fwrite( time_it->second->EITdata, len, 1, f);
1016 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
1018 #ifdef ENABLE_PRIVATE_EPG
1019 const char* text3 = "PRIVATE_EPG";
1020 fwrite( text3, 11, 1, f );
1021 size = content_time_tables.size();
1022 fwrite( &size, sizeof(int), 1, f);
1023 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1025 contentMap &content_time_table = a->second;
1026 fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1027 int size = content_time_table.size();
1028 fwrite( &size, sizeof(int), 1, f);
1029 for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1031 int size = i->second.size();
1032 fwrite( &i->first, sizeof(int), 1, f);
1033 fwrite( &size, sizeof(int), 1, f);
1034 for ( contentTimeMap::iterator it(i->second.begin());
1035 it != i->second.end(); ++it )
1037 fwrite( &it->first, sizeof(time_t), 1, f);
1038 fwrite( &it->second.first, sizeof(time_t), 1, f);
1039 fwrite( &it->second.second, sizeof(__u16), 1, f);
1046 unsigned char md5[16];
1047 if (!md5_file("/hdd/epg.dat", 1, md5))
1049 FILE *f = fopen("/hdd/epg.dat.md5", "w");
1052 fwrite( md5, 16, 1, f);
1060 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1062 ,abortTimer(ml), zapTimer(ml), state(0)
1063 ,isRunning(0), haveData(0)
1064 #ifdef ENABLE_PRIVATE_EPG
1065 ,startPrivateTimer(ml)
1067 #ifdef ENABLE_MHW_EPG
1068 ,m_MHWTimeoutTimer(ml)
1071 #ifdef ENABLE_MHW_EPG
1072 CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1074 CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1075 CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1076 #ifdef ENABLE_PRIVATE_EPG
1077 CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1079 pthread_mutex_init(&channel_active, 0);
1082 bool eEPGCache::channel_data::finishEPG()
1084 if (!isRunning) // epg ready
1086 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1087 zapTimer.start(UPDATE_INTERVAL, 1);
1088 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1089 for (int i=0; i < 3; ++i)
1091 seenSections[i].clear();
1092 calcedSections[i].clear();
1094 singleLock l(cache->cache_lock);
1095 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1096 #ifdef ENABLE_MHW_EPG
1104 void eEPGCache::channel_data::startEPG()
1106 eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1109 for (int i=0; i < 3; ++i)
1111 seenSections[i].clear();
1112 calcedSections[i].clear();
1115 eDVBSectionFilterMask mask;
1116 memset(&mask, 0, sizeof(mask));
1118 #ifdef ENABLE_MHW_EPG
1120 mask.data[0] = 0x91;
1121 mask.mask[0] = 0xFF;
1122 m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1123 m_MHWReader->start(mask);
1125 memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1128 mask.data[0] = 0xC8;
1129 mask.mask[0] = 0xFF;
1131 mask.mask[1] = 0xFF;
1132 m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1133 m_MHWReader2->start(mask);
1135 memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1141 mask.flags = eDVBSectionFilterMask::rfCRC;
1143 mask.data[0] = 0x4E;
1144 mask.mask[0] = 0xFE;
1145 m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1146 m_NowNextReader->start(mask);
1147 isRunning |= NOWNEXT;
1149 mask.data[0] = 0x50;
1150 mask.mask[0] = 0xF0;
1151 m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1152 m_ScheduleReader->start(mask);
1153 isRunning |= SCHEDULE;
1155 mask.data[0] = 0x60;
1156 m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1157 m_ScheduleOtherReader->start(mask);
1158 isRunning |= SCHEDULE_OTHER;
1160 abortTimer.start(7000,true);
1163 void eEPGCache::channel_data::abortNonAvail()
1167 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1169 eDebug("[EPGC] abort non avail nownext reading");
1170 isRunning &= ~NOWNEXT;
1171 m_NowNextReader->stop();
1174 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1176 eDebug("[EPGC] abort non avail schedule reading");
1177 isRunning &= ~SCHEDULE;
1178 m_ScheduleReader->stop();
1181 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1183 eDebug("[EPGC] abort non avail schedule_other reading");
1184 isRunning &= ~SCHEDULE_OTHER;
1185 m_ScheduleOtherReader->stop();
1186 m_ScheduleOtherConn=0;
1188 #ifdef ENABLE_MHW_EPG
1189 if ( !(haveData&MHW) && (isRunning&MHW) )
1191 eDebug("[EPGC] abort non avail mhw reading");
1193 m_MHWReader->stop();
1195 m_MHWReader2->stop();
1200 abortTimer.start(90000, true);
1204 for (int i=0; i < 3; ++i)
1206 seenSections[i].clear();
1207 calcedSections[i].clear();
1214 void eEPGCache::channel_data::startChannel()
1216 pthread_mutex_lock(&channel_active);
1217 updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1219 int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1221 if (update < ZAP_DELAY)
1224 zapTimer.start(update, 1);
1225 if (update >= 60000)
1226 eDebug("[EPGC] next update in %i min", update/60000);
1227 else if (update >= 1000)
1228 eDebug("[EPGC] next update in %i sec", update/1000);
1231 void eEPGCache::channel_data::abortEPG()
1233 for (int i=0; i < 3; ++i)
1235 seenSections[i].clear();
1236 calcedSections[i].clear();
1242 eDebug("[EPGC] abort caching events !!");
1243 if (isRunning & SCHEDULE)
1245 isRunning &= ~SCHEDULE;
1246 m_ScheduleReader->stop();
1249 if (isRunning & NOWNEXT)
1251 isRunning &= ~NOWNEXT;
1252 m_NowNextReader->stop();
1255 if (isRunning & SCHEDULE_OTHER)
1257 isRunning &= ~SCHEDULE_OTHER;
1258 m_ScheduleOtherReader->stop();
1259 m_ScheduleOtherConn=0;
1261 #ifdef ENABLE_MHW_EPG
1262 if (isRunning & MHW)
1265 m_MHWReader->stop();
1267 m_MHWReader2->stop();
1272 #ifdef ENABLE_PRIVATE_EPG
1273 if (m_PrivateReader)
1274 m_PrivateReader->stop();
1278 pthread_mutex_unlock(&channel_active);
1281 void eEPGCache::channel_data::readData( const __u8 *data)
1285 iDVBSectionReader *reader=NULL;
1289 reader=m_NowNextReader;
1294 reader=m_ScheduleReader;
1299 reader=m_ScheduleOtherReader;
1300 source=SCHEDULE_OTHER;
1304 eDebug("[EPGC] unknown table_id !!!");
1307 tidMap &seenSections = this->seenSections[map];
1308 tidMap &calcedSections = this->calcedSections[map];
1309 if ( state == 1 && calcedSections == seenSections || state > 1 )
1311 eDebugNoNewLine("[EPGC] ");
1316 eDebugNoNewLine("nownext");
1320 eDebugNoNewLine("schedule");
1322 case SCHEDULE_OTHER:
1323 m_ScheduleOtherConn=0;
1324 eDebugNoNewLine("schedule other");
1326 default: eDebugNoNewLine("unknown");break;
1328 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1331 isRunning &= ~source;
1337 eit_t *eit = (eit_t*) data;
1338 __u32 sectionNo = data[0] << 24;
1339 sectionNo |= data[3] << 16;
1340 sectionNo |= data[4] << 8;
1341 sectionNo |= eit->section_number;
1343 tidMap::iterator it =
1344 seenSections.find(sectionNo);
1346 if ( it == seenSections.end() )
1348 seenSections.insert(sectionNo);
1349 calcedSections.insert(sectionNo);
1350 __u32 tmpval = sectionNo & 0xFFFFFF00;
1351 __u8 incr = source == NOWNEXT ? 1 : 8;
1352 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1354 if ( i == eit->section_number )
1356 for (int x=i; x <= eit->segment_last_section_number; ++x)
1357 calcedSections.insert(tmpval|(x&0xFF));
1360 calcedSections.insert(tmpval|(i&0xFF));
1362 cache->sectionRead(data, source, this);
1367 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1368 // if t == -1 we search the current event...
1370 singleLock s(cache_lock);
1371 uniqueEPGKey key(handleGroup(service));
1373 // check if EPG for this service is ready...
1374 eventCache::iterator It = eventDB.find( key );
1375 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1378 t = eDVBLocalTimeHandler::getInstance()->nowTime();
1379 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) : // find > or equal
1380 It->second.second.upper_bound(t); // just >
1381 if ( i != It->second.second.end() )
1383 if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1385 timeMap::iterator x = i;
1387 if ( x != It->second.second.end() )
1389 time_t start_time = x->second->getStartTime();
1394 if (t > (start_time+x->second->getDuration()))
1409 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1411 singleLock s(cache_lock);
1412 const eventData *data=0;
1413 RESULT ret = lookupEventTime(service, t, data, direction);
1415 result = data->get();
1419 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1421 singleLock s(cache_lock);
1422 const eventData *data=0;
1423 RESULT ret = lookupEventTime(service, t, data, direction);
1425 result = new Event((uint8_t*)data->get());
1429 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1431 singleLock s(cache_lock);
1432 const eventData *data=0;
1433 RESULT ret = lookupEventTime(service, t, data, direction);
1436 Event ev((uint8_t*)data->get());
1437 result = new eServiceEvent();
1438 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1439 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1444 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1446 singleLock s(cache_lock);
1447 uniqueEPGKey key(handleGroup(service));
1449 eventCache::iterator It = eventDB.find( key );
1450 if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1452 eventMap::iterator i( It->second.first.find( event_id ));
1453 if ( i != It->second.first.end() )
1461 eDebug("[EPGC] event %04x not found in epgcache", event_id);
1467 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1469 singleLock s(cache_lock);
1470 const eventData *data=0;
1471 RESULT ret = lookupEventId(service, event_id, data);
1473 result = data->get();
1477 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1479 singleLock s(cache_lock);
1480 const eventData *data=0;
1481 RESULT ret = lookupEventId(service, event_id, data);
1483 result = new Event((uint8_t*)data->get());
1487 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1489 singleLock s(cache_lock);
1490 const eventData *data=0;
1491 RESULT ret = lookupEventId(service, event_id, data);
1494 Event ev((uint8_t*)data->get());
1495 result = new eServiceEvent();
1496 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1497 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1502 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1505 eventCache::iterator It = eventDB.find(handleGroup(service));
1506 if ( It != eventDB.end() && It->second.second.size() )
1508 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1511 m_timemap_cursor = It->second.second.lower_bound(begin);
1512 if ( m_timemap_cursor != It->second.second.end() )
1514 if ( m_timemap_cursor->second->getStartTime() != begin )
1516 timeMap::iterator x = m_timemap_cursor;
1518 if ( x != It->second.second.end() )
1520 time_t start_time = x->second->getStartTime();
1521 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1522 m_timemap_cursor = x;
1528 m_timemap_cursor = It->second.second.begin();
1529 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1530 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1538 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1540 if ( m_timemap_cursor != m_timemap_end )
1542 result = m_timemap_cursor++->second;
1548 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1550 if ( m_timemap_cursor != m_timemap_end )
1552 result = m_timemap_cursor++->second->get();
1558 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1560 if ( m_timemap_cursor != m_timemap_end )
1562 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1568 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1570 if ( m_timemap_cursor != m_timemap_end )
1572 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1573 result = new eServiceEvent();
1574 return result->parseFrom(&ev, currentQueryTsidOnid);
1579 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, ePtr<eServiceEvent> &ptr, ePyObject nowTime, ePyObject service_name )
1583 while(pos < argcount)
1585 bool inc_refcount=false;
1586 switch(argstring[pos])
1588 case '0': // PyLong 0
1589 tmp = PyLong_FromLong(0);
1591 case 'I': // Event Id
1592 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1594 case 'B': // Event Begin Time
1595 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1597 case 'D': // Event Duration
1598 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1600 case 'T': // Event Title
1601 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1603 case 'S': // Event Short Description
1604 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1606 case 'E': // Event Extended Description
1607 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1609 case 'C': // Current Time
1611 inc_refcount = true;
1613 case 'R': // service reference string
1615 inc_refcount = true;
1617 case 'N': // service name
1619 inc_refcount = true;
1624 inc_refcount = true;
1628 PyTuple_SET_ITEM(tuple, pos++, tmp);
1632 int handleEvent(ePtr<eServiceEvent> &ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1636 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1637 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1641 Py_DECREF(service_name);
1644 Py_DECREF(convertFuncArgs);
1645 Py_DECREF(dest_list);
1646 PyErr_SetString(PyExc_StandardError,
1647 "error in convertFunc execute");
1648 eDebug("error in convertFunc execute");
1651 PyList_Append(dest_list, result);
1656 ePyObject tuple = PyTuple_New(argcount);
1657 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1658 PyList_Append(dest_list, tuple);
1664 // here we get a python list
1665 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1668 // B = Event Begin Time
1669 // D = Event Duration
1671 // S = Event Short Description
1672 // E = Event Extended Description
1674 // R = Service Reference
1676 // then for each service follows a tuple
1677 // first tuple entry is the servicereference (as string... use the ref.toString() function)
1678 // the second is the type of query
1680 // -1 = event before given start_time
1681 // 0 = event intersects given start_time
1682 // +1 = event after given start_time
1684 // when type is eventid it is the event_id
1685 // when type is time then it is the start_time ( 0 for now_time )
1686 // the fourth is the end_time .. ( optional .. for query all events in time range)
1688 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1690 ePyObject convertFuncArgs;
1692 char *argstring=NULL;
1693 if (!PyList_Check(list))
1695 PyErr_SetString(PyExc_StandardError,
1701 int listSize=PyList_Size(list);
1704 PyErr_SetString(PyExc_StandardError,
1705 "not params given");
1706 eDebug("not params given");
1711 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1712 if (PyString_Check(argv))
1714 argstring = PyString_AS_STRING(argv);
1718 argstring = "I"; // just event id as default
1719 argcount = strlen(argstring);
1720 // eDebug("have %d args('%s')", argcount, argstring);
1724 if (!PyCallable_Check(convertFunc))
1726 PyErr_SetString(PyExc_StandardError,
1727 "convertFunc must be callable");
1728 eDebug("convertFunc is not callable");
1731 convertFuncArgs = PyTuple_New(argcount);
1734 ePyObject nowTime = strchr(argstring, 'C') ?
1735 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1738 bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1741 ePyObject dest_list=PyList_New(0);
1742 while(listSize > listIt)
1744 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1745 if (PyTuple_Check(item))
1747 bool service_changed=false;
1752 int tupleSize=PyTuple_Size(item);
1755 while(tupleSize > tupleIt) // parse query args
1757 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1762 if (!PyString_Check(entry))
1764 eDebug("tuple entry 0 is no a string");
1771 type=PyInt_AsLong(entry);
1772 if (type < -1 || type > 2)
1774 eDebug("unknown type %d", type);
1779 event_id=stime=PyInt_AsLong(entry);
1782 minutes=PyInt_AsLong(entry);
1785 eDebug("unneeded extra argument");
1789 eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1790 if (ref.type != eServiceReference::idDVB)
1792 eDebug("service reference for epg query is not valid");
1796 // redirect subservice querys to parent service
1797 eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1798 if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1800 eServiceCenterPtr service_center;
1801 if (!eServiceCenter::getPrivInstance(service_center))
1803 dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1804 dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1805 dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1806 dvb_ref.setParentServiceID(eServiceID(0));
1808 service = PyString_FromString(dvb_ref.toString().c_str());
1809 service_changed = true;
1813 ePyObject service_name;
1814 if (must_get_service_name)
1816 ePtr<iStaticServiceInformation> sptr;
1817 eServiceCenterPtr service_center;
1818 eServiceCenter::getPrivInstance(service_center);
1821 service_center->info(ref, sptr);
1825 sptr->getName(ref, name);
1827 service_name = PyString_FromString(name.c_str());
1831 service_name = PyString_FromString("<n/a>");
1836 if (!startTimeQuery(ref, stime, minutes))
1838 ePtr<eServiceEvent> ptr;
1839 while (!getNextTimeEntry(ptr))
1841 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1852 ePtr<eServiceEvent> ptr;
1856 lookupEventId(ref, event_id, ptr);
1858 lookupEventTime(ref, stime, ptr, type);
1860 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1863 if (service_changed)
1866 Py_DECREF(service_name);
1871 if (convertFuncArgs)
1872 Py_DECREF(convertFuncArgs);
1878 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, ePyObject service_name, ePyObject service_reference)
1882 while(pos < argcount)
1884 bool inc_refcount=false;
1885 switch(argstring[pos])
1887 case '0': // PyLong 0
1888 tmp = PyLong_FromLong(0);
1890 case 'I': // Event Id
1891 tmp = PyLong_FromLong(evData->getEventID());
1893 case 'B': // Event Begin Time
1895 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1897 tmp = PyLong_FromLong(evData->getStartTime());
1899 case 'D': // Event Duration
1901 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1903 tmp = PyLong_FromLong(evData->getDuration());
1905 case 'T': // Event Title
1906 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1908 case 'S': // Event Short Description
1909 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1911 case 'E': // Event Extended Description
1912 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1914 case 'R': // service reference string
1915 tmp = service_reference;
1916 inc_refcount = true;
1918 case 'N': // service name
1920 inc_refcount = true;
1926 inc_refcount = true;
1930 PyTuple_SET_ITEM(tuple, pos++, tmp);
1934 // here we get a python tuple
1935 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1937 // B = Event Begin Time
1938 // D = Event Duration
1940 // S = Event Short Description
1941 // E = Event Extended Description
1942 // R = Service Reference
1944 // the second tuple entry is the MAX matches value
1945 // the third tuple entry is the type of query
1946 // 0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1947 // 1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1948 // 2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1949 // when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1950 // the fourth is the servicereference string
1951 // the fifth is the eventid
1952 // when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1953 // the fourth is the search text
1955 // 0 = case sensitive (CASE_CHECK)
1956 // 1 = case insensitive (NO_CASECHECK)
1958 PyObject *eEPGCache::search(ePyObject arg)
1964 const char *argstring=0;
1968 bool needServiceEvent=false;
1971 if (PyTuple_Check(arg))
1973 int tuplesize=PyTuple_Size(arg);
1976 ePyObject obj = PyTuple_GET_ITEM(arg,0);
1977 if (PyString_Check(obj))
1979 argcount = PyString_GET_SIZE(obj);
1980 argstring = PyString_AS_STRING(obj);
1981 for (int i=0; i < argcount; ++i)
1982 switch(argstring[i])
1987 needServiceEvent=true;
1994 PyErr_SetString(PyExc_StandardError,
1996 eDebug("tuple arg 0 is not a string");
2001 maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2004 querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2005 if (tuplesize > 4 && querytype == 0)
2007 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2008 if (PyString_Check(obj))
2010 refstr = PyString_AS_STRING(obj);
2011 eServiceReferenceDVB ref(refstr);
2014 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2015 singleLock s(cache_lock);
2016 const eventData *evData = 0;
2017 lookupEventId(ref, eventid, evData);
2020 __u8 *data = evData->EITdata;
2021 int tmp = evData->ByteSize-10;
2022 __u32 *p = (__u32*)(data+10);
2023 // search short and extended event descriptors
2027 descriptorMap::iterator it =
2028 eventData::descriptors.find(crc);
2029 if (it != eventData::descriptors.end())
2031 __u8 *descr_data = it->second.second;
2032 switch(descr_data[0])
2035 descr[++descridx]=crc;
2044 eDebug("event not found");
2048 PyErr_SetString(PyExc_StandardError,
2050 eDebug("tuple arg 4 is not a valid service reference string");
2056 PyErr_SetString(PyExc_StandardError,
2058 eDebug("tuple arg 4 is not a string");
2062 else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2064 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2065 if (PyString_Check(obj))
2067 int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2068 const char *str = PyString_AS_STRING(obj);
2069 int textlen = PyString_GET_SIZE(obj);
2071 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2073 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2074 singleLock s(cache_lock);
2075 for (descriptorMap::iterator it(eventData::descriptors.begin());
2076 it != eventData::descriptors.end() && descridx < 511; ++it)
2078 __u8 *data = it->second.second;
2079 if ( data[0] == 0x4D ) // short event descriptor
2081 int title_len = data[5];
2082 if ( querytype == 1 )
2084 if (title_len > textlen)
2086 else if (title_len < textlen)
2090 if ( !strncasecmp((const char*)data+6, str, title_len) )
2092 // std::string s((const char*)data+6, title_len);
2093 // eDebug("match1 %s %s", str, s.c_str() );
2094 descr[++descridx] = it->first;
2097 else if ( !strncmp((const char*)data+6, str, title_len) )
2099 // std::string s((const char*)data+6, title_len);
2100 // eDebug("match2 %s %s", str, s.c_str() );
2101 descr[++descridx] = it->first;
2107 while((title_len-idx) >= textlen)
2111 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2113 descr[++descridx] = it->first;
2114 // std::string s((const char*)data+6, title_len);
2115 // eDebug("match 3 %s %s", str, s.c_str() );
2118 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2120 descr[++descridx] = it->first;
2121 // std::string s((const char*)data+6, title_len);
2122 // eDebug("match 4 %s %s", str, s.c_str() );
2134 PyErr_SetString(PyExc_StandardError,
2136 eDebug("tuple arg 4 is not a string");
2142 PyErr_SetString(PyExc_StandardError,
2144 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2150 PyErr_SetString(PyExc_StandardError,
2152 eDebug("not enough args in tuple");
2158 PyErr_SetString(PyExc_StandardError,
2160 eDebug("arg 0 is not a tuple");
2164 ASSERT(descridx <= 512);
2168 int maxcount=maxmatches;
2169 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2170 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2171 // in this case we start searching with the base service
2172 bool first = ref.valid() ? true : false;
2173 singleLock s(cache_lock);
2174 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2175 while(cit != eventDB.end() && maxcount)
2177 if ( ref.valid() && !first && cit->first == ref )
2179 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2183 ePyObject service_name;
2184 ePyObject service_reference;
2185 timeMap &evmap = cit->second.second;
2187 for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2189 int evid = evit->second->getEventID();
2190 if ( evid == eventid)
2192 __u8 *data = evit->second->EITdata;
2193 int tmp = evit->second->ByteSize-12;
2194 __u32 *p = (__u32*)(data+12);
2195 // check if any of our descriptor used by this event
2200 for ( int i=0; i <= descridx; ++i)
2202 if (descr[i] == crc32) // found...
2207 if ( (querytype == 0 && cnt == descridx) ||
2208 ((querytype == 1 || querytype == 2) && cnt != -1) )
2210 const uniqueEPGKey &service = cit->first;
2211 eServiceReference ref =
2212 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2215 // create servive event
2216 ePtr<eServiceEvent> ptr;
2217 if (needServiceEvent)
2219 lookupEventId(ref, evid, ptr);
2221 eDebug("event not found !!!!!!!!!!!");
2223 // create service name
2224 if (!service_name && strchr(argstring,'N'))
2226 ePtr<iStaticServiceInformation> sptr;
2227 eServiceCenterPtr service_center;
2228 eServiceCenter::getPrivInstance(service_center);
2231 service_center->info(ref, sptr);
2235 sptr->getName(ref, name);
2237 service_name = PyString_FromString(name.c_str());
2241 service_name = PyString_FromString("<n/a>");
2243 // create servicereference string
2244 if (!service_reference && strchr(argstring,'R'))
2245 service_reference = PyString_FromString(ref.toString().c_str());
2248 ret = PyList_New(0);
2250 ePyObject tuple = PyTuple_New(argcount);
2252 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2253 PyList_Append(ret, tuple);
2260 Py_DECREF(service_name);
2261 if (service_reference)
2262 Py_DECREF(service_reference);
2265 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2267 cit=eventDB.begin();
2280 #ifdef ENABLE_PRIVATE_EPG
2281 #include <dvbsi++/descriptor_tag.h>
2282 #include <dvbsi++/unknown_descriptor.h>
2283 #include <dvbsi++/private_data_specifier_descriptor.h>
2285 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2287 ePtr<eTable<ProgramMapSection> > ptr;
2288 if (!pmthandler->getPMT(ptr) && ptr)
2290 std::vector<ProgramMapSection*>::const_iterator i;
2291 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2293 const ProgramMapSection &pmt = **i;
2295 ElementaryStreamInfoConstIterator es;
2296 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2299 switch ((*es)->getType())
2301 case 0x05: // private
2302 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2303 desc != (*es)->getDescriptors()->end(); ++desc)
2305 switch ((*desc)->getTag())
2307 case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2308 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2313 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2314 int descr_len = descr->getLength();
2317 uint8_t data[descr_len+2];
2318 descr->writeToBuffer(data);
2319 if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2333 eServiceReferenceDVB ref;
2334 if (!pmthandler->getServiceReference(ref))
2336 int pid = (*es)->getPid();
2337 messages.send(Message(Message::got_private_pid, ref, pid));
2345 eDebug("PMTready but no pmt!!");
2352 date_time( const date_time &a )
2354 memcpy(data, a.data, 5);
2357 date_time( const __u8 data[5])
2359 memcpy(this->data, data, 5);
2360 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2365 const __u8& operator[](int pos) const
2371 struct less_datetime
2373 bool operator()( const date_time &a, const date_time &b ) const
2375 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2379 void eEPGCache::privateSectionRead(const uniqueEPGKey ¤t_service, const __u8 *data)
2381 contentMap &content_time_table = content_time_tables[current_service];
2382 singleLock s(cache_lock);
2383 std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2384 eventMap &evMap = eventDB[current_service].first;
2385 timeMap &tmMap = eventDB[current_service].second;
2387 int content_id = data[ptr++] << 24;
2388 content_id |= data[ptr++] << 16;
2389 content_id |= data[ptr++] << 8;
2390 content_id |= data[ptr++];
2392 contentTimeMap &time_event_map =
2393 content_time_table[content_id];
2394 for ( contentTimeMap::iterator it( time_event_map.begin() );
2395 it != time_event_map.end(); ++it )
2397 eventMap::iterator evIt( evMap.find(it->second.second) );
2398 if ( evIt != evMap.end() )
2400 delete evIt->second;
2403 tmMap.erase(it->second.first);
2405 time_event_map.clear();
2408 memcpy(duration, data+ptr, 3);
2411 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2413 const __u8 *descriptors[65];
2414 const __u8 **pdescr = descriptors;
2416 int descriptors_length = (data[ptr++]&0x0F) << 8;
2417 descriptors_length |= data[ptr++];
2418 while ( descriptors_length > 1 )
2420 int descr_type = data[ptr];
2421 int descr_len = data[ptr+1];
2422 descriptors_length -= 2;
2423 if (descriptors_length >= descr_len)
2425 descriptors_length -= descr_len;
2426 if ( descr_type == 0xf2 && descr_len > 5)
2429 int tsid = data[ptr++] << 8;
2430 tsid |= data[ptr++];
2431 int onid = data[ptr++] << 8;
2432 onid |= data[ptr++];
2433 int sid = data[ptr++] << 8;
2436 // WORKAROUND for wrong transmitted epg data (01.08.2006)
2439 switch( (tsid << 16) | sid )
2441 case 0x01030b: sid = 0x1b; tsid = 4; break; // Premiere Win
2442 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2443 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2444 case 0x0300f5: sid = 0xdc; break;
2445 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2446 case 0x1100d3: sid = 0xe3; break;
2449 ////////////////////////////////////////////
2451 uniqueEPGKey service( sid, onid, tsid );
2453 while( descr_len > 2 )
2456 datetime[0] = data[ptr++];
2457 datetime[1] = data[ptr++];
2458 int tmp_len = data[ptr++];
2460 if (descr_len >= tmp_len)
2462 descr_len -= tmp_len;
2463 while( tmp_len > 2 )
2465 memcpy(datetime+2, data+ptr, 3);
2468 start_times[datetime].push_back(service);
2481 ASSERT(pdescr <= &descriptors[65])
2483 eit_event_struct *ev_struct = (eit_event_struct*) event;
2484 ev_struct->running_status = 0;
2485 ev_struct->free_CA_mode = 1;
2486 memcpy(event+7, duration, 3);
2488 const __u8 **d=descriptors;
2489 while ( d < pdescr )
2491 memcpy(event+ptr, *d, ((*d)[1])+2);
2495 ASSERT(ptr <= 4098);
2496 for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2498 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2499 if ( (it->first.tm + duration_sec) < now )
2501 memcpy(event+2, it->first.data, 5);
2504 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2506 event[bptr++] = 0x4A;
2507 __u8 *len = event+(bptr++);
2508 event[bptr++] = (i->tsid & 0xFF00) >> 8;
2509 event[bptr++] = (i->tsid & 0xFF);
2510 event[bptr++] = (i->onid & 0xFF00) >> 8;
2511 event[bptr++] = (i->onid & 0xFF);
2512 event[bptr++] = (i->sid & 0xFF00) >> 8;
2513 event[bptr++] = (i->sid & 0xFF);
2514 event[bptr++] = 0xB0;
2515 bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2516 *len = ((event+bptr) - len)-1;
2518 int llen = bptr - 12;
2519 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2520 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2522 time_t stime = it->first.tm;
2523 while( tmMap.find(stime) != tmMap.end() )
2525 event[6] += (stime - it->first.tm);
2527 while( evMap.find(event_id) != evMap.end() )
2529 event[0] = (event_id & 0xFF00) >> 8;
2530 event[1] = (event_id & 0xFF);
2531 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2532 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2533 evMap[event_id] = d;
2535 ASSERT(bptr <= 4098);
2539 void eEPGCache::channel_data::startPrivateReader()
2541 eDVBSectionFilterMask mask;
2542 memset(&mask, 0, sizeof(mask));
2543 mask.pid = m_PrivatePid;
2544 mask.flags = eDVBSectionFilterMask::rfCRC;
2545 mask.data[0] = 0xA0;
2546 mask.mask[0] = 0xFF;
2547 eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2548 if (m_PrevVersion != -1)
2550 mask.data[3] = m_PrevVersion << 1;
2551 mask.mask[3] = 0x3E;
2552 mask.mode[3] = 0x3E;
2554 seenPrivateSections.clear();
2556 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2557 m_PrivateReader->start(mask);
2560 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2562 if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2564 cache->privateSectionRead(m_PrivateService, data);
2565 seenPrivateSections.insert(data[6]);
2567 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2569 eDebug("[EPGC] private finished");
2570 eDVBChannelID chid = channel->getChannelID();
2571 int tmp = chid.original_network_id.get();
2572 tmp |= 0x80000000; // we use highest bit as private epg indicator
2573 chid.original_network_id = tmp;
2574 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2575 m_PrevVersion = (data[5] & 0x3E) >> 1;
2576 startPrivateReader();
2580 #endif // ENABLE_PRIVATE_EPG
2582 #ifdef ENABLE_MHW_EPG
2583 void eEPGCache::channel_data::cleanup()
2588 m_program_ids.clear();
2591 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2593 // Names in mhw structs are not strings as they are not '\0' terminated.
2594 // This function converts the mhw name into a string.
2595 // Constraint: "length of out" = "length of in" + 1.
2597 for ( i=0; i < len_in; i++ )
2601 while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2608 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2611 return_time[0] = toBCD( hours );
2612 return_time[1] = toBCD( minutes );
2616 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2618 timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2621 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2622 // For date plus time of day
2624 // Remove offset in mhw time.
2625 __u8 local_hours = hours;
2628 else if ( hours >= 8 )
2631 // As far as we know all mhw time data is sent in central Europe time zone.
2632 // So, temporarily set timezone to western europe
2633 time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2635 char *old_tz = getenv( "TZ" );
2636 putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2640 localtime_r(&dt, &localnow);
2644 if ( day + 1 < localnow.tm_wday ) // day + 1 to prevent old events to show for next week.
2646 if (local_hours <= 5)
2649 dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2650 dt += 3600*(local_hours - localnow.tm_hour); // Shift dt to the recording hour.
2653 gmtime_r( &dt, &recdate ); // This will also take care of DST.
2655 if ( old_tz == NULL )
2661 // Calculate MJD according to annex in ETSI EN 300 468
2663 if ( recdate.tm_mon <= 1 ) // Jan or Feb
2665 int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2666 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2668 return_time[0] = (mjd & 0xFF00)>>8;
2669 return_time[1] = mjd & 0xFF;
2671 timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2674 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2675 // data is borrowed from calling proc to save memory space.
2678 // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2679 bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2680 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2682 eit_t *packet = (eit_t *) data;
2683 packet->table_id = 0x50;
2684 packet->section_syntax_indicator = 1;
2685 packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2686 packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2687 packet->version_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2688 packet->current_next_indicator = 0;
2689 packet->section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2690 packet->last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2691 packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2692 packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2693 packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2694 packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2695 packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2696 packet->segment_last_table_id = 0x50;
2698 __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2699 std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2700 int prog_title_length = prog_title.length();
2702 int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2703 prog_title_length + 1;
2705 eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2706 event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2707 event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2711 u_char *data = (u_char*) event_data;
2712 data[2] = itTitle->second.mhw2_mjd_hi;
2713 data[3] = itTitle->second.mhw2_mjd_lo;
2714 data[4] = itTitle->second.mhw2_hours;
2715 data[5] = itTitle->second.mhw2_minutes;
2716 data[6] = itTitle->second.mhw2_seconds;
2717 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2721 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2722 (u_char *) event_data + 2 );
2723 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2726 event_data->running_status = 0;
2727 event_data->free_CA_mode = 0;
2728 int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2730 eit_short_event_descriptor_struct *short_event_descriptor =
2731 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2732 short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2733 short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2734 prog_title_length - 1;
2735 short_event_descriptor->language_code_1 = 'e';
2736 short_event_descriptor->language_code_2 = 'n';
2737 short_event_descriptor->language_code_3 = 'g';
2738 short_event_descriptor->event_name_length = prog_title_length;
2739 u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2740 memcpy(event_name, prog_title.c_str(), prog_title_length);
2743 event_name[prog_title_length] = 0;
2745 if ( sumText.length() > 0 )
2746 // There is summary info
2748 unsigned int sum_length = sumText.length();
2749 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2750 // Store summary in short event descriptor
2752 // Increase all relevant lengths
2753 event_name[prog_title_length] = sum_length;
2754 short_event_descriptor->descriptor_length += sum_length;
2755 packet_length += sum_length;
2756 descr_ll += sum_length;
2757 sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2760 // Store summary in extended event descriptors
2762 int remaining_sum_length = sumText.length();
2763 int nbr_descr = int(remaining_sum_length/247) + 1;
2764 for ( int i=0; i < nbr_descr; i++)
2765 // Loop once per extended event descriptor
2767 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2768 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2769 remaining_sum_length -= sum_length;
2770 packet_length += 8 + sum_length;
2771 descr_ll += 8 + sum_length;
2773 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2774 ext_event_descriptor->descriptor_length = sum_length + 6;
2775 ext_event_descriptor->descriptor_number = i;
2776 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2777 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2778 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2779 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2780 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2782 the_text[-1] = sum_length;
2783 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2790 // Add content descriptor
2791 u_char *descriptor = (u_char *) data + packet_length;
2796 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2797 if ( content_descr.find( "FILM" ) != std::string::npos )
2799 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2802 descriptor[0] = 0x54;
2804 descriptor[2] = content_id;
2808 event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2809 event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2811 packet->section_length_hi = ((packet_length - 3)&0xf00)>>8;
2812 packet->section_length_lo = (packet_length - 3)&0xff;
2814 // Feed the data to eEPGCache::sectionRead()
2815 cache->sectionRead( data, MHW, this );
2818 void eEPGCache::channel_data::startTimeout(int msec)
2820 m_MHWTimeoutTimer.start(msec,true);
2821 m_MHWTimeoutet=false;
2824 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2826 m_MHWFilterMask.pid = pid;
2827 m_MHWFilterMask.data[0] = tid;
2828 m_MHWReader->start(m_MHWFilterMask);
2829 // eDebug("start 0x%02x 0x%02x", pid, tid);
2832 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2834 m_MHWFilterMask2.pid = pid;
2835 m_MHWFilterMask2.data[0] = tid;
2838 m_MHWFilterMask2.data[1] = ext;
2839 m_MHWFilterMask2.mask[1] = 0xFF;
2840 // eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2844 m_MHWFilterMask2.data[1] = 0;
2845 m_MHWFilterMask2.mask[1] = 0;
2846 // eDebug("start 0x%02x 0x%02x", pid, tid);
2848 m_MHWReader2->start(m_MHWFilterMask2);
2851 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2854 m_MHWReader2->stop();
2856 if ( state > 1 || // aborted
2857 // have si data.. so we dont read mhw data
2858 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2860 eDebug("[EPGC] mhw aborted %d", state);
2862 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2865 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2866 int record_size = sizeof( mhw_channel_name_t );
2867 int nbr_records = int (len/record_size);
2869 for ( int i = 0; i < nbr_records; i++ )
2871 mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2872 m_channels.push_back( *channel );
2876 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2878 // Channels table has been read, start reading the themes table.
2879 startMHWReader(0xD3, 0x92);
2882 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2885 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2886 int record_size = sizeof( mhw_theme_name_t );
2887 int nbr_records = int (len/record_size);
2889 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2892 for ( int i = 0; i < nbr_records; i++ )
2894 mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2895 if ( i >= next_idx )
2899 next_idx = (__u8) *(data + 3 + idx_ptr);
2905 m_themes[idx+sub_idx] = *theme;
2907 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2908 // Themes table has been read, start reading the titles table.
2909 startMHWReader(0xD2, 0x90);
2913 else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2916 mhw_title_t *title = (mhw_title_t*) data;
2918 if ( title->channel_id == 0xFF ) // Separator
2919 return; // Continue reading of the current table.
2922 // Create unique key per title
2923 __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2924 (title->ms.minutes);
2925 __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2926 ((title->program_id_ml)<<8)|(title->program_id_lo);
2928 if ( m_titles.find( title_id ) == m_titles.end() )
2931 title->mhw2_mjd_hi = 0;
2932 title->mhw2_mjd_lo = 0;
2933 title->mhw2_duration_hi = 0;
2934 title->mhw2_duration_lo = 0;
2935 m_titles[ title_id ] = *title;
2936 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2937 // program_ids will be used to gather summaries.
2938 m_program_ids[ program_id ] = title_id;
2939 return; // Continue reading of the current table.
2941 else if (!checkTimeout())
2944 if ( !m_program_ids.empty())
2946 // Titles table has been read, there are summaries to read.
2947 // Start reading summaries, store corresponding titles on the fly.
2948 startMHWReader(0xD3, 0x90);
2949 eDebug("[EPGC] mhw %d titles(%d with summary) found",
2951 m_program_ids.size());
2956 else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2959 mhw_summary_t *summary = (mhw_summary_t*) data;
2961 // Create unique key per record
2962 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2963 ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2964 int len = ((data[1]&0xf)<<8) + data[2];
2966 // ugly workaround to convert const __u8* to char*
2968 memcpy(&tmp, &data, sizeof(void*));
2969 tmp[len+3] = 0; // Terminate as a string.
2971 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2972 if ( itProgid == m_program_ids.end() )
2973 { /* This part is to prevent to looping forever if some summaries are not received yet.
2974 There is a timeout of 4 sec. after the last successfully read summary. */
2975 if (!m_program_ids.empty() && !checkTimeout())
2976 return; // Continue reading of the current table.
2980 std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2983 while((pos = the_text.find("\r\n")) != std::string::npos)
2984 the_text.replace(pos, 2, " ");
2986 // Find corresponding title, store title and summary in epgcache.
2987 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2988 if ( itTitle != m_titles.end() )
2991 storeTitle( itTitle, the_text, data );
2992 m_titles.erase( itTitle );
2994 m_program_ids.erase( itProgid );
2995 if ( !m_program_ids.empty() )
2996 return; // Continue reading of the current table.
2999 eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3000 eDVBLocalTimeHandler::getInstance()->nowTime(),
3001 m_program_ids.size());
3002 // Summaries have been read, titles that have summaries have been stored.
3003 // Now store titles that do not have summaries.
3004 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3005 storeTitle( itTitle, "", data );
3009 m_MHWReader->stop();
3014 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3016 int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3019 m_MHWReader->stop();
3021 if ( state > 1 || // aborted
3022 // have si data.. so we dont read mhw data
3023 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
3025 eDebug("[EPGC] mhw2 aborted %d", state);
3027 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3030 int num_channels = data[120];
3033 int ptr = 121 + 6 * num_channels;
3036 for( int chid = 0; chid < num_channels; ++chid )
3038 ptr += ( data[ptr] & 0x0f ) + 1;
3048 // data seems consistent...
3049 const __u8 *tmp = data+121;
3050 for (int i=0; i < num_channels; ++i)
3052 mhw_channel_name_t channel;
3053 channel.transport_stream_id_hi = *(tmp++);
3054 channel.transport_stream_id_lo = *(tmp++);
3055 channel.channel_id_hi = *(tmp++);
3056 channel.channel_id_lo = *(tmp++);
3057 #warning FIXME hardcoded network_id in mhw2 epg
3058 channel.network_id_hi = 0; // hardcoded astra 19.2
3059 channel.network_id_lo = 1;
3060 m_channels.push_back(channel);
3063 for (int i=0; i < num_channels; ++i)
3065 mhw_channel_name_t &channel = m_channels[i];
3066 int channel_name_len=*(tmp++)&0x0f;
3068 for (; x < channel_name_len; ++x)
3069 channel.name[x]=*(tmp++);
3070 channel.name[x+1]=0;
3073 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3075 else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3078 eDebug("[EPGC] mhw2 themes nyi");
3080 else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3085 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3087 if(data[dataLen-1] != 0xff)
3089 while( pos < dataLen )
3098 if( data[pos] > 0xc0 )
3100 pos += ( data[pos] - 0xc0 );
3104 if( data[pos] == 0xff )
3120 // data seems consistent...
3125 title.channel_id = data[pos]+1;
3126 title.program_id_ml = data[pos+1];
3127 title.program_id_lo = data[pos+2];
3128 title.mhw2_mjd_hi = data[pos+3];
3129 title.mhw2_mjd_lo = data[pos+4];
3130 title.mhw2_hours = data[pos+5];
3131 title.mhw2_minutes = data[pos+6];
3132 title.mhw2_seconds = data[pos+7];
3133 int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3134 title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3135 title.mhw2_duration_lo = duration&0xFF;
3136 __u8 slen = data[pos+10] & 0x3f;
3137 __u8 *dest = ((__u8*)title.title)-4;
3138 memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3139 memset(dest+slen, 0x20, 33-slen);
3141 // not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3142 __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3144 // Create unique key per title
3145 __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3147 // eDebug("program_id: %08x, %s", program_id,
3148 // std::string((const char *)title.title, (int)(slen > 23 ? 23 : slen)).c_str());
3152 if ( m_titles.find( title_id ) == m_titles.end() )
3155 m_titles[ title_id ] = title;
3156 if (summary_id != 0xFFFF && // no summary avail
3157 m_program_ids.find(summary_id) == m_program_ids.end())
3159 m_program_ids[ summary_id ] = title_id;
3164 if ( !checkTimeout() )
3165 continue; // Continue reading of the current table.
3173 eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3174 if (!m_program_ids.empty())
3176 // Titles table has been read, there are summaries to read.
3177 // Start reading summaries, store corresponding titles on the fly.
3178 startMHWReader2(0x236, 0x96);
3186 else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3189 int len, loop, pos, lenline;
3198 loop = data[pos] & 0x0f;
3203 for( ; loop > 0; --loop )
3205 if( dataLen > (pos+len) )
3207 lenline = data[pos+len];
3216 else if (!checkTimeout())
3217 return; // continue reading
3218 if (valid && !checkTimeout())
3220 // data seems consistent...
3221 __u32 summary_id = (data[3]<<8)|data[4];
3223 // ugly workaround to convert const __u8* to char*
3225 memcpy(&tmp, &data, sizeof(void*));
3230 loop = tmp[pos] & 0x0f;
3232 for( ; loop > 0; loop -- )
3234 lenline = tmp[pos+len];
3243 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( summary_id ) );
3244 if ( itProgid == m_program_ids.end() )
3245 { /* This part is to prevent to looping forever if some summaries are not received yet.
3246 There is a timeout of 4 sec. after the last successfully read summary. */
3248 if ( !m_program_ids.empty() && !checkTimeout() )
3249 return; // Continue reading of the current table.
3254 std::string the_text = (char *) (data + pos + 1);
3256 // Find corresponding title, store title and summary in epgcache.
3257 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3258 if ( itTitle != m_titles.end() )
3260 storeTitle( itTitle, the_text, data );
3261 m_titles.erase( itTitle );
3263 m_program_ids.erase( itProgid );
3264 if ( !m_program_ids.empty() )
3265 return; // Continue reading of the current table.
3269 if (isRunning & eEPGCache::MHW)
3271 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3273 // Channels table has been read, start reading the themes table.
3274 startMHWReader2(0x231, 0xC8, 1);
3277 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3279 // Themes table has been read, start reading the titles table.
3280 startMHWReader2(0x234, 0xe6);
3285 // Summaries have been read, titles that have summaries have been stored.
3286 // Now store titles that do not have summaries.
3287 for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3288 storeTitle( itTitle, "", data );
3289 eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3290 eDVBLocalTimeHandler::getInstance()->nowTime(),
3291 m_program_ids.size());
3298 m_MHWReader2->stop();