[FCC] Fix to perform normal decoding for usb tuner on FCC mode.
[vuplus_dvbapp] / lib / dvb / pmt.cpp
1 #include <lib/base/nconfig.h> // access to python config
2 #include <lib/base/eerror.h>
3 #include <lib/dvb/pmt.h>
4 #include <lib/dvb/specs.h>
5 #include <lib/dvb/dvb.h>
6 #include <lib/dvb/metaparser.h>
7 #include <lib/dvb_ci/dvbci.h>
8 #include <lib/dvb/epgcache.h>
9 #include <lib/dvb/scan.h>
10 #include <lib/dvb_ci/dvbci_session.h>
11 #include <dvbsi++/ca_descriptor.h>
12 #include <dvbsi++/ca_program_map_section.h>
13 #include <dvbsi++/teletext_descriptor.h>
14 #include <dvbsi++/descriptor_tag.h>
15 #include <dvbsi++/iso639_language_descriptor.h>
16 #include <dvbsi++/stream_identifier_descriptor.h>
17 #include <dvbsi++/subtitling_descriptor.h>
18 #include <dvbsi++/teletext_descriptor.h>
19 #include <dvbsi++/video_stream_descriptor.h>
20 #include <dvbsi++/registration_descriptor.h>
21 #include <dvbsi++/ac3_descriptor.h>
22
23 #include <dvbsi++/simple_application_location_descriptor.h>
24 #include <dvbsi++/simple_application_boundary_descriptor.h>
25 #include <dvbsi++/transport_protocol_descriptor.h>
26 #include <dvbsi++/application_name_descriptor.h>
27
28
29 eDVBServicePMTHandler::eDVBServicePMTHandler()
30         :m_ca_servicePtr(0), m_dvb_scan(0), m_decode_demux_num(0xFF), m_no_pat_entry_delay(eTimer::create())
31 {
32         m_use_decode_demux = 0;
33         m_pmt_pid = -1;
34         m_dsmcc_pid = -1;
35         m_service_type = livetv;
36         m_descramble = true;
37         m_ca_disabled = false;
38         m_pmt_ready = false;
39         eDVBResourceManager::getInstance(m_resourceManager);
40         CONNECT(m_PMT.tableReady, eDVBServicePMTHandler::PMTready);
41         CONNECT(m_PAT.tableReady, eDVBServicePMTHandler::PATready);
42         CONNECT(m_no_pat_entry_delay->timeout, eDVBServicePMTHandler::sendEventNoPatEntry);
43
44         CONNECT(m_AIT.tableReady, eDVBServicePMTHandler::AITready);
45         CONNECT(m_OC.tableReady, eDVBServicePMTHandler::OCready);
46 }
47
48 eDVBServicePMTHandler::~eDVBServicePMTHandler()
49 {
50         free();
51 }
52
53 void eDVBServicePMTHandler::channelStateChanged(iDVBChannel *channel)
54 {
55         int state;
56         channel->getState(state);
57         
58         if ((m_last_channel_state != iDVBChannel::state_ok)
59                 && (state == iDVBChannel::state_ok) && (!m_demux))
60         {
61                 if (m_channel)
62                 {
63                         if (m_pvr_demux_tmp)
64                         {
65                                 m_demux = m_pvr_demux_tmp;
66                                 m_pvr_demux_tmp = NULL;
67                         }
68                         else if (m_channel->getDemux(m_demux, (!m_use_decode_demux) ? 0 : iDVBChannel::capDecode))
69                                 eDebug("Allocating %s-decoding a demux for now tuned-in channel failed.", m_use_decode_demux ? "" : "non-");
70                 }
71                 
72                 serviceEvent(eventTuned);
73                 
74                 if (m_demux)
75                 {
76                         eDebug("ok ... now we start!!");
77
78                         if (!m_service || m_service->usePMT())
79                         {
80                                 if (m_pmt_pid == -1)
81                                         m_PAT.begin(eApp, eDVBPATSpec(), m_demux);
82                                 else
83                                         m_PMT.begin(eApp, eDVBPMTSpec(m_pmt_pid, m_reference.getServiceID().get()), m_demux);
84                         }
85
86                         if ( m_service && !m_service->cacheEmpty() )
87                                 serviceEvent(eventNewProgramInfo);
88                 }
89         } else if ((m_last_channel_state != iDVBChannel::state_failed) && 
90                         (state == iDVBChannel::state_failed))
91         {
92                 eDebug("tune failed.");
93                 serviceEvent(eventTuneFailed);
94         }
95 }
96
97 void eDVBServicePMTHandler::channelEvent(iDVBChannel *channel, int event)
98 {
99         switch (event)
100         {
101         case iDVBChannel::evtPreStart:
102                 serviceEvent(eventPreStart);
103                 break;
104         case iDVBChannel::evtEOF:
105                 serviceEvent(eventEOF);
106                 break;
107         case iDVBChannel::evtSOF:
108                 serviceEvent(eventSOF);
109                 break;
110         case iDVBChannel::evtFailed+3:
111                 serviceEvent(eventNoDiskSpace);
112                 break;
113         default:
114                 break;
115         }
116 }
117
118 void eDVBServicePMTHandler::registerCAService()
119 {
120         int demuxes[2] = {0,0};
121         uint8_t demuxid;
122         m_demux->getCADemuxID(demuxid);
123         demuxes[0]=demuxid;
124         if (m_decode_demux_num != 0xFF)
125                 demuxes[1]=m_decode_demux_num;
126         else
127                 demuxes[1]=demuxes[0];
128         eDVBCAService::register_service(m_reference, demuxes, m_ca_servicePtr);
129 }
130
131 void eDVBServicePMTHandler::PMTready(int error)
132 {
133         if (error)
134                 serviceEvent(eventNoPMT);
135         else
136         {
137                 m_pmt_ready = true;
138                 m_have_cached_program = false;
139                 serviceEvent(eventNewProgramInfo);
140
141                 mDemuxId = m_decode_demux_num;
142                 if (!m_pvr_channel)
143                 {
144                         eEPGCache::getInstance()->PMTready(this);
145                 }
146
147                 if (m_descramble)
148                 {
149                         if(!m_ca_servicePtr)
150                         {
151                                 registerCAService();
152                         }
153                         if (!m_ca_disabled)
154                         {
155                                 eDVBCIInterfaces::getInstance()->recheckPMTHandlers();
156                                 eDVBCIInterfaces::getInstance()->gotPMT(this);
157                         }
158                 }
159                 if (m_ca_servicePtr)
160                 {
161                         ePtr<eTable<ProgramMapSection> > ptr;
162                         if (!m_PMT.getCurrent(ptr))
163                                 m_ca_servicePtr->buildCAPMT(ptr);
164                         else
165                                 eDebug("eDVBServicePMTHandler cannot call buildCAPMT");
166                 }
167
168                 if (m_service_type == pvrDescramble)
169                         serviceEvent(eventStartPvrDescramble);
170         }
171 }
172
173 void eDVBServicePMTHandler::sendEventNoPatEntry()
174 {
175         serviceEvent(eventNoPATEntry);
176 }
177
178 void eDVBServicePMTHandler::PATready(int)
179 {
180         eDebug("PATready");
181         ePtr<eTable<ProgramAssociationSection> > ptr;
182         if (!m_PAT.getCurrent(ptr))
183         {
184                 int service_id_single = -1;
185                 int pmtpid_single = -1;
186                 int pmtpid = -1;
187                 int cnt=0;
188                 std::vector<ProgramAssociationSection*>::const_iterator i;
189                 for (i = ptr->getSections().begin(); pmtpid == -1 && i != ptr->getSections().end(); ++i)
190                 {
191                         const ProgramAssociationSection &pat = **i;
192                         ProgramAssociationConstIterator program;
193                         for (program = pat.getPrograms()->begin(); pmtpid == -1 && program != pat.getPrograms()->end(); ++program)
194                         {
195                                 ++cnt;
196                                 if (eServiceID((*program)->getProgramNumber()) == m_reference.getServiceID())
197                                         pmtpid = (*program)->getProgramMapPid();
198                                 if (++cnt == 1 && pmtpid_single == -1 && pmtpid == -1)
199                                 {
200                                         pmtpid_single = (*program)->getProgramMapPid();
201                                         service_id_single = (*program)->getProgramNumber();
202                                 }
203                                 else
204                                         pmtpid_single = service_id_single = -1;
205                         }
206                 }
207                 if (pmtpid_single != -1) // only one PAT entry .. and not valid pmtpid found
208                 {
209                         eDebug("use single pat entry!");
210                         m_reference.setServiceID(eServiceID(service_id_single));
211                         pmtpid = pmtpid_single;
212                 }
213                 if (pmtpid == -1) {
214                         eDebug("no PAT entry found.. start delay");
215                         m_no_pat_entry_delay->start(1000, true);
216                 }
217                 else {
218                         eDebug("use pmtpid %04x for service_id %04x", pmtpid, m_reference.getServiceID().get());
219                         m_no_pat_entry_delay->stop();
220                         m_PMT.begin(eApp, eDVBPMTSpec(pmtpid, m_reference.getServiceID().get()), m_demux);
221                 }
222         } else
223                 serviceEvent(eventNoPAT);
224 }
225
226 static void eraseHbbTVApplications(HbbTVApplicationInfoList  *applications)
227 {
228         if(applications->size() == 0)
229                 return;
230         for(HbbTVApplicationInfoListConstIterator info = applications->begin() ; info != applications->end() ; ++info)
231                 delete(*info);
232         applications->clear();
233 }
234
235 void saveData(int orgid, unsigned char* data, int sectionLength)
236 {
237         int fd = 0, rc = 0;
238         char fileName[255] = {0};
239         sprintf(fileName, "/tmp/ait.%d", orgid);
240
241         if (data[6] > 0) {
242                 eDebug("section_number %d > 0", data[6]);
243                 data[6] = 0;
244         }
245         if (data[7] > data[6]) {
246                 eDebug("last_section_number %d > section_number %d", data[7], data[6]);
247                 data[7] = data[6];
248         }
249
250         if((fd = open(fileName, O_RDWR|O_CREAT|O_TRUNC)) < 0)
251         {
252                 eDebug("Fail to save a AIT Data.");
253                 return;
254         }
255         rc = write(fd, data, sectionLength);
256         eDebug("Save Data Len : [%d]", rc);
257         close(fd);
258 }
259
260 #include <dvbsi++/application_profile.h>
261 #include <dvbsi++/application_descriptor.h>
262 #include <dvbsi++/simple_application_boundary_descriptor.h>
263 #define PACK_VERSION(major,minor,micro) (((major) << 16) + ((minor) << 8) + (micro))
264 #define UNPACK_VERSION(version,major,minor,micro) { \
265         major = (version)&0xff; \
266         minor = (version>>8)&0xff; \
267         micro = (version>>16)&0xff; \
268 }
269 void eDVBServicePMTHandler::AITready(int error)
270 {
271         eDebug("AITready");
272         ePtr<eTable<ApplicationInformationSection> > ptr;
273         if (!m_AIT.getCurrent(ptr))
274         {
275                 short profilecode = 0;
276                 int orgid = 0, appid = 0, profileVersion = 0;
277                 m_ApplicationName = m_HBBTVUrl = "";
278
279                 eraseHbbTVApplications(&m_HbbTVApplications);
280
281                 int sectionLength = 0;
282                 for (std::vector<ApplicationInformationSection*>::const_iterator it = ptr->getSections().begin(); it != ptr->getSections().end(); ++it)
283                 {
284                         std::list<ApplicationInformation *>::const_iterator i = (*it)->getApplicationInformation()->begin();
285                         memcpy(m_AITData, ptr->getBufferData(), 4096);
286                         sectionLength = (*it)->getSectionLength() + 3;
287                         eDebug("Section Length : %d, Total Section Length : %d", (*it)->getSectionLength(), sectionLength);
288                         for (; i != (*it)->getApplicationInformation()->end(); ++i)
289                         {
290                                 std::string hbbtvUrl = "", applicaionName = "";
291                                 std::string boundaryExtension = "";
292                                 
293                                 int controlCode = (*i)->getApplicationControlCode();
294                                 const ApplicationIdentifier * applicationIdentifier = (*i)->getApplicationIdentifier();
295                                 profilecode = 0;
296                                 orgid = applicationIdentifier->getOrganisationId();
297                                 appid = applicationIdentifier->getApplicationId();
298                                 eDebug("found applicaions ids >> pid : %x, orgid : %d, appid : %d", m_ait_pid, orgid, appid);
299                                 if (controlCode == 1)
300                                         saveData(orgid, m_AITData, sectionLength);
301                                 if (controlCode == 1 || controlCode == 2) /* 1:AUTOSTART, 2:ETC */
302                                 {
303                                         for (DescriptorConstIterator desc = (*i)->getDescriptors()->begin();
304                                                 desc != (*i)->getDescriptors()->end(); ++desc)
305                                         {
306                                                 switch ((*desc)->getTag())
307                                                 {
308                                                 case APPLICATION_DESCRIPTOR:
309                                                 {
310                                                         ApplicationDescriptor* applicationDescriptor = (ApplicationDescriptor*)(*desc);
311                                                         const ApplicationProfileList* applicationProfiles = applicationDescriptor->getApplicationProfiles();
312                                                         ApplicationProfileConstIterator interactionit = applicationProfiles->begin();
313                                                         for(; interactionit != applicationProfiles->end(); ++interactionit)
314                                                         {
315                                                                 profilecode = (*interactionit)->getApplicationProfile();
316                                                                 profileVersion = PACK_VERSION(
317                                                                         (*interactionit)->getVersionMajor(),
318                                                                         (*interactionit)->getVersionMinor(),
319                                                                         (*interactionit)->getVersionMicro()
320                                                                 );
321                                                         }
322                                                         break;
323                                                 }
324                                                 case APPLICATION_NAME_DESCRIPTOR:
325                                                 {
326                                                         ApplicationNameDescriptor *nameDescriptor  = (ApplicationNameDescriptor*)(*desc);
327                                                         ApplicationNameConstIterator interactionit = nameDescriptor->getApplicationNames()->begin();
328                                                         for(; interactionit != nameDescriptor->getApplicationNames()->end(); ++interactionit)
329                                                         {
330                                                                 applicaionName = (*interactionit)->getApplicationName();
331                                                                 if(controlCode == 1) m_ApplicationName = applicaionName;
332                                                                 break;
333                                                         }
334                                                         break;
335                                                 }
336                                                 case TRANSPORT_PROTOCOL_DESCRIPTOR:
337                                                 {
338                                                         TransportProtocolDescriptor *transport = (TransportProtocolDescriptor*)(*desc);
339                                                         switch (transport->getProtocolId())
340                                                         {
341                                                         case 1: /* object carousel */
342                                                                 if (m_dsmcc_pid >= 0)
343                                                                 {
344                                                                         m_OC.begin(eApp, eDVBDSMCCDLDataSpec(m_dsmcc_pid), m_demux);
345                                                                 }
346                                                                 break;
347                                                         case 2: /* ip */
348                                                                 break;
349                                                         case 3: /* interaction */
350                                                                 {
351                                                                         InterActionTransportConstIterator interactionit = transport->getInteractionTransports()->begin();
352                                                                         for(; interactionit != transport->getInteractionTransports()->end(); ++interactionit)
353                                                                         {
354                                                                                 hbbtvUrl = (*interactionit)->getUrlBase()->getUrl();
355                                                                                 break;
356                                                                         }
357                                                                         break;
358                                                                 }
359                                                         }
360                                                         break;
361                                                 }
362                                                 case GRAPHICS_CONSTRAINTS_DESCRIPTOR:
363                                                         break;
364                                                 case SIMPLE_APPLICATION_LOCATION_DESCRIPTOR:
365                                                 {
366                                                         SimpleApplicationLocationDescriptor *applicationlocation = (SimpleApplicationLocationDescriptor*)(*desc);
367                                                         hbbtvUrl += applicationlocation->getInitialPath();
368                                                         break;
369                                                 }
370                                                 case APPLICATION_USAGE_DESCRIPTOR:
371                                                         break;
372                                                 case SIMPLE_APPLICATION_BOUNDARY_DESCRIPTOR:
373                                                         break;
374                                                 }
375                                         }
376                                 }
377                                 if(!hbbtvUrl.empty())
378                                 {
379                                         const char* uu = hbbtvUrl.c_str();
380                                         if(!strncmp(uu, "http://", 7) || !strncmp(uu, "dvb://", 6) || !strncmp(uu, "https://", 8))
381                                         {
382                                                 if(controlCode == 1) m_HBBTVUrl = hbbtvUrl;
383                                                 switch(profileVersion)
384                                                 {
385                                                 case 65793:
386                                                 case 66049:
387                                                         m_HbbTVApplications.push_back(new HbbTVApplicationInfo(controlCode, orgid, appid, hbbtvUrl, applicaionName, profilecode));
388                                                         break;
389                                                 case 1280:
390                                                 case 65538:
391                                                 default:
392                                                         m_HbbTVApplications.push_back(new HbbTVApplicationInfo((-1)*controlCode, orgid, appid, hbbtvUrl, applicaionName, profilecode));
393                                                         break;
394                                                 }
395                                         }
396                                         else if (!boundaryExtension.empty()) {
397                                                 if(boundaryExtension.at(boundaryExtension.length()-1) != '/') {
398                                                         boundaryExtension += "/";
399                                                 }
400                                                 boundaryExtension += hbbtvUrl;
401                                                 if(controlCode == 1) m_HBBTVUrl = boundaryExtension;
402                                                 switch(profileVersion)
403                                                 {
404                                                 case 65793:
405                                                 case 66049:
406                                                         m_HbbTVApplications.push_back(new HbbTVApplicationInfo(controlCode, orgid, appid, boundaryExtension, applicaionName, profilecode));
407                                                         break;
408                                                 case 1280:
409                                                 case 65538:
410                                                 default:
411                                                         m_HbbTVApplications.push_back(new HbbTVApplicationInfo((-1)*controlCode, orgid, appid, boundaryExtension, applicaionName, profilecode));
412                                                         break;
413                                                 }
414                                         }
415                                 }
416                         }
417                 }
418
419                 if (m_HbbTVApplications.size())
420                 {
421                         for(HbbTVApplicationInfoListConstIterator infoiter = m_HbbTVApplications.begin() ; infoiter != m_HbbTVApplications.end() ; ++infoiter)
422                         {
423                                 char fileName[255] = {0};
424                                 sprintf(fileName, "/tmp/ait.%d", (*infoiter)->m_OrgId);
425                                 if (access(fileName, 0) < 0)
426                                         saveData((*infoiter)->m_OrgId, m_AITData, sectionLength);
427                                 eDebug("Found : control[%d], name[%s], url[%s]", 
428                                         (*infoiter)->m_ControlCode, (*infoiter)->m_ApplicationName.c_str(), (*infoiter)->m_HbbTVUrl.c_str());
429                         }
430                         serviceEvent(eventHBBTVInfo);
431                 }
432                 else eDebug("No found anything.");
433         }
434         /* for now, do not keep listening for table updates */
435         m_AIT.stop();
436 }
437
438 void eDVBServicePMTHandler::OCready(int error)
439 {
440         eDebug("OCready");
441         ePtr<eTable<OCSection> > ptr;
442         if (!m_OC.getCurrent(ptr))
443         {
444                 for (std::vector<OCSection*>::const_iterator it = ptr->getSections().begin(); it != ptr->getSections().end(); ++it)
445                 {
446                         unsigned char* sectionData = (unsigned char*)(*it)->getData();
447                 }
448         }
449         /* for now, do not keep listening for table updates */
450         m_OC.stop();
451 }
452
453 PyObject *eDVBServicePMTHandler::getCaIds(bool pair)
454 {
455         ePyObject ret;
456
457         program prog;
458
459         if ( !getProgramInfo(prog) )
460         {
461                 if (pair)
462                 {
463                         int cnt=prog.caids.size();
464                         if (cnt)
465                         {
466                                 ret=PyList_New(cnt);
467                                 std::list<program::capid_pair>::iterator it(prog.caids.begin());
468                                 while(cnt--)
469                                 {
470                                         ePyObject tuple = PyTuple_New(2);
471                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(it->caid));
472                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong((it++)->capid));
473                                         PyList_SET_ITEM(ret, cnt, tuple);
474                                 }
475                         }
476                 }
477                 else
478                 {
479                         std::set<program::capid_pair> set(prog.caids.begin(), prog.caids.end());
480                         std::set<program::capid_pair>::iterator it(set.begin());
481                         int cnt=set.size();
482                         ret=PyList_New(cnt);
483                         while(cnt--)
484                                 PyList_SET_ITEM(ret, cnt, PyInt_FromLong((it++)->caid));
485                 }
486         }
487
488         return ret ? (PyObject*)ret : (PyObject*)PyList_New(0);
489 }
490
491 PyObject *eDVBServicePMTHandler::getHbbTVApplications(void)
492 {
493         ePyObject ret= PyList_New(0);;
494         if(m_HbbTVApplications.size())
495         {
496                 for(HbbTVApplicationInfoListConstIterator infoiter = m_HbbTVApplications.begin() ; infoiter != m_HbbTVApplications.end() ; ++infoiter)
497                 {
498                         ePyObject tuple = PyTuple_New(6);
499                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong((*infoiter)->m_ControlCode));
500                         PyTuple_SET_ITEM(tuple, 1, PyString_FromString((*infoiter)->m_ApplicationName.c_str()));
501                         PyTuple_SET_ITEM(tuple, 2, PyString_FromString((*infoiter)->m_HbbTVUrl.c_str()));
502                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong((*infoiter)->m_OrgId));
503                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong((*infoiter)->m_AppId));
504                         PyTuple_SET_ITEM(tuple, 5, PyInt_FromLong((*infoiter)->m_ProfileCode));
505                         PyList_Append(ret, tuple);
506                         Py_DECREF(tuple);
507                 }
508         }
509         return (PyObject*)ret;
510 }
511
512 int eDVBServicePMTHandler::getProgramInfo(program &program)
513 {
514         ePtr<eTable<ProgramMapSection> > ptr;
515         int cached_apid_ac3 = -1;
516         int cached_apid_ddp = -1;
517         int cached_apid_mpeg = -1;
518         int cached_apid_aache = -1;
519         int cached_apid_aac = -1;
520         int cached_vpid = -1;
521         int cached_tpid = -1;
522         int ret = -1;
523
524         program.videoStreams.clear();
525         program.audioStreams.clear();
526         program.pcrPid = -1;
527         program.pmtPid = -1;
528         program.textPid = -1;
529         program.aitPid = -1;
530         program.isCached = false;
531         program.pmtVersion = -1;
532
533         int first_ac3 = -1;
534         program.defaultAudioStream = 0;
535         audioStream *prev_audio = 0;
536
537         if ( m_service && !m_service->cacheEmpty() )
538         {
539                 cached_vpid = m_service->getCacheEntry(eDVBService::cVPID);
540                 cached_apid_mpeg = m_service->getCacheEntry(eDVBService::cMPEGAPID);
541                 cached_apid_ac3 = m_service->getCacheEntry(eDVBService::cAC3PID);
542                 cached_apid_ddp = m_service->getCacheEntry(eDVBService::cDDPPID);
543                 cached_apid_aache = m_service->getCacheEntry(eDVBService::cAACHEAPID);
544                 cached_apid_aac = m_service->getCacheEntry(eDVBService::cAACAPID);
545                 cached_tpid = m_service->getCacheEntry(eDVBService::cTPID);
546         }
547
548         if ( ((m_service && m_service->usePMT()) || !m_service) && !m_PMT.getCurrent(ptr))
549         {
550                 if (m_have_cached_program)
551                 {
552                         program = m_cached_program;
553                         ret = 0;
554                 }
555                 else
556                 {
557                         eDVBTableSpec table_spec;
558                         ptr->getSpec(table_spec);
559                         program.pmtPid = table_spec.pid < 0x1fff ? table_spec.pid : -1;
560                         program.pmtVersion = table_spec.version;
561                         std::vector<ProgramMapSection*>::const_iterator i;
562                         for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
563                         {
564                                 const ProgramMapSection &pmt = **i;
565                                 int is_hdmv = 0;
566
567                                 program.pcrPid = pmt.getPcrPid();
568
569                                 for (DescriptorConstIterator desc = pmt.getDescriptors()->begin();
570                                         desc != pmt.getDescriptors()->end(); ++desc)
571                                 {
572                                         if ((*desc)->getTag() == CA_DESCRIPTOR)
573                                         {
574                                                 CaDescriptor *descr = (CaDescriptor*)(*desc);
575                                                 program::capid_pair pair;
576                                                 pair.caid = descr->getCaSystemId();
577                                                 pair.capid = descr->getCaPid();
578                                                 program.caids.push_back(pair);
579                                         }
580                                         else if ((*desc)->getTag() == REGISTRATION_DESCRIPTOR)
581                                         {
582                                                 RegistrationDescriptor *d = (RegistrationDescriptor*)(*desc);
583                                                 if (d->getFormatIdentifier() == 0x48444d56) // HDMV
584                                                         is_hdmv = 1;
585                                         }
586                                 }
587
588                                 ElementaryStreamInfoConstIterator es;
589                                 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
590                                 {
591                                         int isaudio = 0, isvideo = 0, issubtitle = 0, forced_video = 0, forced_audio = 0, isteletext = 0;
592                                         int streamtype = (*es)->getType();
593                                         videoStream video;
594                                         audioStream audio;
595                                         audio.component_tag=video.component_tag=-1;
596                                         video.type = videoStream::vtMPEG2;
597                                         audio.type = audioStream::atMPEG;
598                                         audio.rdsPid = -1;
599
600                                         switch (streamtype)
601                                         {
602                                         case 0x1b: // AVC Video Stream (MPEG4 H264)
603                                                 video.type = videoStream::vtMPEG4_H264;
604                                                 isvideo = 1;
605                                                 //break; fall through !!!
606                                         case 0x24: // H265 HEVC
607                                                 if (!isvideo)
608                                                 {
609                                                         video.type = videoStream::vtH265_HEVC;
610                                                         isvideo = 1;
611                                                 }
612                                                 //break; fall through !!!
613                                         case 0x10: // MPEG 4 Part 2
614                                                 if (!isvideo)
615                                                 {
616                                                         video.type = videoStream::vtMPEG4_Part2;
617                                                         isvideo = 1;
618                                                 }
619                                                 //break; fall through !!!
620                                         case 0x01: // MPEG 1 video
621                                                 if (!isvideo)
622                                                         video.type = videoStream::vtMPEG1;
623                                                 //break; fall through !!!
624                                         case 0x02: // MPEG 2 video
625                                                 isvideo = 1;
626                                                 forced_video = 1;
627                                                 //break; fall through !!!
628                                         case 0x03: // MPEG 1 audio
629                                         case 0x04: // MPEG 2 audio:
630                                                 if (!isvideo) {
631                                                         isaudio = 1;
632                                                         forced_audio = 1;
633                                                 }
634                                                 //break; fall through !!!
635                                         case 0x0f: // MPEG 2 AAC
636                                                 if (!isvideo && !isaudio)
637                                                 {
638                                                         isaudio = 1;
639                                                         audio.type = audioStream::atAAC;
640                                                         forced_audio = 1;
641                                                 }
642                                                 //break; fall through !!!
643                                         case 0x11: // MPEG 4 AAC
644                                                 if (!isvideo && !isaudio)
645                                                 {
646                                                         isaudio = 1;
647                                                         audio.type = audioStream::atAACHE;
648                                                         forced_audio = 1;
649                                                 }
650                                         case 0x80: // user private ... but bluray LPCM
651                                         case 0xA0: // bluray secondary LPCM
652                                                 if (!isvideo && !isaudio && is_hdmv)
653                                                 {
654                                                         isaudio = 1;
655                                                         audio.type = audioStream::atLPCM;
656                                                 }
657                                         case 0x81: // user private ... but bluray AC3
658                                         case 0xA1: // bluray secondary AC3
659                                                 if (!isvideo && !isaudio && is_hdmv)
660                                                 {
661                                                         isaudio = 1;
662                                                         audio.type = audioStream::atAC3;
663                                                 }
664                                         case 0x82: // bluray DTS (dvb user private...)
665                                         case 0xA2: // bluray secondary DTS
666                                                 if (!isvideo && !isaudio && is_hdmv)
667                                                 {
668                                                         isaudio = 1;
669                                                         audio.type = audioStream::atDTS;
670                                                 }
671                                         case 0x86: // bluray DTS-HD (dvb user private...)
672                                         case 0xA6: // bluray secondary DTS-HD
673                                                 if (!isvideo && !isaudio && is_hdmv)
674                                                 {
675                                                         isaudio = 1;
676                                                         audio.type = audioStream::atDTSHD;
677                                                 }
678                                         case 0x06: // PES Private
679                                         case 0xEA: // TS_PSI_ST_SMPTE_VC1
680                                         {
681                                                 int num_descriptors = 0;
682                                                 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
683                                                         desc != (*es)->getDescriptors()->end(); ++desc)
684                                                 {
685                                                         uint8_t tag = (*desc)->getTag();
686                                                         /* check descriptors to get the exakt stream type. */
687                                                         ++num_descriptors;
688                                                         if (!forced_video && !forced_audio)
689                                                         {
690                                                                 switch (tag)
691                                                                 {
692                                                                 case AUDIO_STREAM_DESCRIPTOR:
693                                                                         isaudio = 1;
694                                                                         break;
695                                                                 case VIDEO_STREAM_DESCRIPTOR:
696                                                                 {
697                                                                         isvideo = 1;
698                                                                         VideoStreamDescriptor *d = (VideoStreamDescriptor*)(*desc);
699                                                                         if (d->getMpeg1OnlyFlag())
700                                                                                 video.type = videoStream::vtMPEG1;
701                                                                         break;
702                                                                 }
703                                                                 case SUBTITLING_DESCRIPTOR:
704                                                                 {
705                                                                         SubtitlingDescriptor *d = (SubtitlingDescriptor*)(*desc);
706                                                                         const SubtitlingList *list = d->getSubtitlings();
707                                                                         subtitleStream s;
708                                                                         s.pid = (*es)->getPid();
709                                                                         for (SubtitlingConstIterator it(list->begin()); it != list->end(); ++it)
710                                                                         {
711                                                                                 s.subtitling_type = (*it)->getSubtitlingType();
712                                                                                 switch(s.subtitling_type)
713                                                                                 {
714                                                                                 case 0x10 ... 0x13:
715                                                                                 case 0x20 ... 0x23: // dvb subtitles
716                                                                                         break;
717                                                                                 default:
718                                                                                         eDebug("dvb subtitle %s PID %04x with wrong subtitling type (%02x)... force 0x10!!",
719                                                                                                 s.language_code.c_str(), s.pid, s.subtitling_type);
720                                                                                         s.subtitling_type = 0x10;
721                                                                                         break;
722                                                                                 }
723                                                                                 s.composition_page_id = (*it)->getCompositionPageId();
724                                                                                 s.ancillary_page_id = (*it)->getAncillaryPageId();
725                                                                                 s.language_code = (*it)->getIso639LanguageCode();
726 //                                                                              eDebug("add dvb subtitle %s PID %04x, type %d, composition page %d, ancillary_page %d",
727 //                                                                                      s.language_code.c_str(), s.pid, s.subtitling_type, s.composition_page_id, s.ancillary_page_id);
728                                                                                 issubtitle=1;
729                                                                                 program.subtitleStreams.push_back(s);
730                                                                         }
731                                                                         break;
732                                                                 }
733                                                                 case TELETEXT_DESCRIPTOR:
734                                                                         if ( program.textPid == -1 || (*es)->getPid() == cached_tpid )
735                                                                         {
736                                                                                 subtitleStream s;
737                                                                                 s.subtitling_type = 0x01; // EBU TELETEXT SUBTITLES
738                                                                                 s.pid = program.textPid = (*es)->getPid();
739                                                                                 TeletextDescriptor *d = (TeletextDescriptor*)(*desc);
740                                                                                 isteletext = 1;
741                                                                                 const VbiTeletextList *list = d->getVbiTeletexts();
742                                                                                 for (VbiTeletextConstIterator it(list->begin()); it != list->end(); ++it)
743                                                                                 {
744                                                                                         switch((*it)->getTeletextType())
745                                                                                         {
746                                                                                         case 0x02: // Teletext subtitle page
747                                                                                         case 0x05: // Teletext subtitle page for hearing impaired pepople
748                                                                                                 s.language_code = (*it)->getIso639LanguageCode();
749                                                                                                 s.teletext_page_number = (*it)->getTeletextPageNumber();
750                                                                                                 s.teletext_magazine_number = (*it)->getTeletextMagazineNumber();
751 //                                                                                              eDebug("add teletext subtitle %s PID %04x, page number %d, magazine number %d",
752 //                                                                                                      s.language_code.c_str(), s.pid, s.teletext_page_number, s.teletext_magazine_number);
753                                                                                                 program.subtitleStreams.push_back(s);
754                                                                                                 issubtitle=1;
755                                                                                         default:
756                                                                                                 break;
757                                                                                         }
758                                                                                 }
759                                                                         }
760                                                                         break;
761                                                                 case DTS_DESCRIPTOR:
762                                                                         isaudio = 1;
763                                                                         audio.type = audioStream::atDTS;
764                                                                         break;
765                                                                 case 0x2B: // TS_PSI_DT_MPEG2_AAC
766                                                                         isaudio = 1;
767                                                                         audio.type = audioStream::atAAC; // MPEG2-AAC
768                                                                         break;
769                                                                 case 0x1C: // TS_PSI_DT_MPEG4_Audio
770                                                                 case AAC_DESCRIPTOR:
771                                                                         isaudio = 1;
772                                                                         audio.type = audioStream::atAACHE; // MPEG4-AAC
773                                                                         break;
774                                                                 case AC3_DESCRIPTOR:
775                                                                 {    
776                                                                         Ac3Descriptor *ac = (Ac3Descriptor*)(*desc);
777
778                                                                         isaudio = 1; 
779                                                                         audio.type = audioStream::atAC3;
780
781                                                                         if(ac->getAc3TypeFlag())
782                                                                         {    
783
784                                                                                 uint8_t ac3type = ac->getAc3Type();
785                                                                                 if( ( ac3type & 0x80 ) && ( (ac3type<<5) == 0xA0 || (ac3type<<5) == 0xC0) ) // From EN-300 468 v1.7.1 Table D.1
786                                                                                         audio.type = audioStream::atDDP;
787                                                                         }    
788
789                                                                         break;
790                                                                 }     
791                                                                 case ENHANCED_AC3_DESCRIPTOR:
792                                                                         isaudio = 1; 
793                                                                         audio.type = audioStream::atDDP;
794                                                                         break;
795      
796
797                                                                 case REGISTRATION_DESCRIPTOR: /* some services don't have a separate AC3 descriptor */
798                                                                 {
799                                                                         RegistrationDescriptor *d = (RegistrationDescriptor*)(*desc);
800                                                                         switch (d->getFormatIdentifier())
801                                                                         {
802                                                                         case 0x44545331 ... 0x44545333: // DTS1/DTS2/DTS3
803                                                                                 isaudio = 1;
804                                                                                 audio.type = audioStream::atDTS;
805                                                                                 break;
806                                                                         case 0x41432d33: // == 'AC-3'
807                                                                                 isaudio = 1;
808                                                                                 audio.type = audioStream::atAC3;
809                                                                                 break;
810                                                                         case 0x42535344: // == 'BSSD' (LPCM)
811                                                                                 isaudio = 1;
812                                                                                 audio.type = audioStream::atLPCM;
813                                                                                 break;
814                                                                         case 0x56432d31: // == 'VC-1'
815                                                                         {
816                                                                                 const AdditionalIdentificationInfoVector *vec = d->getAdditionalIdentificationInfo();
817                                                                                 if (vec->size() > 1 && (*vec)[0] == 0x01) // subdescriptor tag
818                                                                                 {
819                                                                                         if ((*vec)[1] >= 0x90) // profile_level
820                                                                                                 video.type = videoStream::vtVC1; // advanced profile
821                                                                                         else
822                                                                                                 video.type = videoStream::vtVC1_SM; // simple main
823                                                                                         isvideo = 1;
824                                                                                 }
825                                                                         }
826                                                                         default:
827                                                                                 break;
828                                                                         }
829                                                                         break;
830                                                                 }
831                                                                 case 0x28: // TS_PSI_DT_AVC
832                                                                         isvideo = 1;
833                                                                         video.type = videoStream::vtMPEG4_H264;
834                                                                         break;
835                                                                 case 0x1B: // TS_PSI_DT_MPEG4_Video
836                                                                         isvideo = 1;
837                                                                         video.type = videoStream::vtMPEG4_Part2;
838                                                                         break;
839                                                                 default:
840                                                                         break;
841                                                                 }
842                                                         }
843                                                         switch (tag)
844                                                         {
845                                                         case ISO_639_LANGUAGE_DESCRIPTOR:
846                                                                 if (!isvideo)
847                                                                 {
848                                                                         int cnt=0;
849                                                                         const Iso639LanguageList *languages = ((Iso639LanguageDescriptor*)*desc)->getIso639Languages();
850                                                                                 /* use last language code */
851                                                                         for (Iso639LanguageConstIterator i(languages->begin()); i != languages->end(); ++i, ++cnt)
852                                                                         {
853                                                                                 if (cnt == 0)
854                                                                                         audio.language_code = (*i)->getIso639LanguageCode();
855                                                                                 else
856                                                                                         audio.language_code += "/" + (*i)->getIso639LanguageCode();
857                                                                         }
858                                                                 }
859                                                                 break;
860                                                         case STREAM_IDENTIFIER_DESCRIPTOR:
861                                                                 audio.component_tag =
862                                                                         video.component_tag =
863                                                                                 ((StreamIdentifierDescriptor*)*desc)->getComponentTag();
864                                                                 break;
865                                                         case CA_DESCRIPTOR:
866                                                         {
867                                                                 CaDescriptor *descr = (CaDescriptor*)(*desc);
868                                                                 program::capid_pair pair;
869                                                                 pair.caid = descr->getCaSystemId();
870                                                                 pair.capid = descr->getCaPid();
871                                                                 program.caids.push_back(pair);
872                                                                 break;
873                                                         }
874                                                         default:
875                                                                 break;
876                                                         }
877                                                 }
878                                                 if (!num_descriptors && streamtype == 0x06 && prev_audio)
879                                                 {
880                                                         prev_audio->rdsPid = (*es)->getPid();
881                                                         eDebug("Rds PID %04x detected ? ! ?", prev_audio->rdsPid);
882                                                 }
883                                                 prev_audio = 0;
884                                         }
885                                         case 0x05: /* ITU-T Rec. H.222.0 | ISO/IEC 13818-1 private sections */
886                                         {
887                                                 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
888                                                         desc != (*es)->getDescriptors()->end(); ++desc)
889                                                 {
890                                                         m_ait_pid = -1;
891                                                         switch ((*desc)->getTag())
892                                                         {
893                                                         case APPLICATION_SIGNALLING_DESCRIPTOR:
894                                                                 m_ait_pid = program.aitPid = (*es)->getPid();
895                                                                 m_AIT.begin(eApp, eDVBAITSpec(program.aitPid), m_demux);
896                                                                 break;
897                                                         }
898                                                 }
899                                                 break;
900                                         }
901                                         case 0x0b: /* ISO/IEC 13818-6 DSM-CC U-N Messages */
902                                         {
903                                                 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
904                                                         desc != (*es)->getDescriptors()->end(); ++desc)
905                                                 {
906                                                         switch ((*desc)->getTag())
907                                                         {
908                                                         case CAROUSEL_IDENTIFIER_DESCRIPTOR:
909                                                                 m_dsmcc_pid = (*es)->getPid();
910                                                                 break;
911                                                         case STREAM_IDENTIFIER_DESCRIPTOR:
912                                                                 break;
913                                                         }
914                                                 }
915                                                 break;
916                                         }
917                                         default:
918                                                 break;
919                                         }
920                                         if (isteletext && (isaudio || isvideo))
921                                         {
922                                                 eDebug("ambiguous streamtype for PID %04x detected.. forced as teletext!", (*es)->getPid());
923                                                 continue; // continue with next PID
924                                         }
925                                         else if (issubtitle && (isaudio || isvideo))
926                                                 eDebug("ambiguous streamtype for PID %04x detected.. forced as subtitle!", (*es)->getPid());
927                                         else if (isaudio && isvideo)
928                                                 eDebug("ambiguous streamtype for PID %04x detected.. forced as video!", (*es)->getPid());
929                                         if (issubtitle) // continue with next PID
930                                                 continue;
931                                         else if (isvideo)
932                                         {
933                                                 video.pid = (*es)->getPid();
934                                                 if ( !program.videoStreams.empty() && video.pid == cached_vpid )
935                                                 {
936                                                         program.videoStreams.push_back(program.videoStreams[0]);
937                                                         program.videoStreams[0] = video;
938                                                 }
939                                                 else
940                                                         program.videoStreams.push_back(video);
941                                         }
942                                         else if (isaudio)
943                                         {
944                                                 audio.pid = (*es)->getPid();
945
946                                                         /* if we find the cached pids, this will be our default stream */
947                                                 if (audio.pid == cached_apid_ac3 || audio.pid == cached_apid_ddp || audio.pid == cached_apid_mpeg || audio.pid == cached_apid_aache || audio.pid == cached_apid_aac)
948                                                         program.defaultAudioStream = program.audioStreams.size();
949
950                                                         /* also, we need to know the first non-mpeg (i.e. "ac3"/dts/...) stream */
951                                                 if ((audio.type != audioStream::atMPEG) && ((first_ac3 == -1) || (audio.pid == cached_apid_ac3) || (audio.pid == cached_apid_ddp)))
952                                                         first_ac3 = program.audioStreams.size();
953
954                                                 program.audioStreams.push_back(audio);
955                                                 prev_audio = &program.audioStreams.back();
956                                         }
957                                         else
958                                                 continue;
959                                 }
960                         }
961                         ret = 0;
962
963                         /* finally some fixup: if our default audio stream is an MPEG audio stream, 
964                            and we have 'defaultac3' set, use the first available ac3 stream instead.
965                            (note: if an ac3 audio stream was selected before, this will be also stored
966                            in 'fisrt_ac3', so we don't need to worry. */
967                         bool defaultac3 = false;
968                         std::string default_ac3;
969
970                         if (!ePythonConfigQuery::getConfigValue("config.av.defaultac3", default_ac3))
971                                 defaultac3 = default_ac3 == "True";
972
973                         if (defaultac3 && (first_ac3 != -1))
974                                 program.defaultAudioStream = first_ac3;
975
976                         m_cached_program = program;
977                         m_have_cached_program = true;
978                 }
979         } else if ( m_service && !m_service->cacheEmpty() )
980         {
981                 int cached_pcrpid = m_service->getCacheEntry(eDVBService::cPCRPID),
982                         vpidtype = m_service->getCacheEntry(eDVBService::cVTYPE),
983                         cnt=0;
984
985                 program.isCached = true;
986
987                 if ( vpidtype == -1 )
988                         vpidtype = videoStream::vtMPEG2;
989                 if ( cached_vpid != -1 )
990                 {
991                         videoStream s;
992                         s.pid = cached_vpid;
993                         s.type = vpidtype;
994                         program.videoStreams.push_back(s);
995                         ++cnt;
996                 }
997                 if ( cached_apid_ac3 != -1 )
998                 {
999                         audioStream s;
1000                         s.type = audioStream::atAC3;
1001                         s.pid = cached_apid_ac3;
1002                         s.rdsPid = -1;
1003                         program.audioStreams.push_back(s);
1004                         ++cnt;
1005                 }
1006                 if ( cached_apid_ddp != -1 )
1007                 {
1008                         audioStream s;
1009                         s.type = audioStream::atDDP;
1010                         s.pid = cached_apid_ddp;
1011                         s.rdsPid = -1;
1012                         program.audioStreams.push_back(s);
1013                         ++cnt;
1014                 }
1015                 if ( cached_apid_aache != -1 )
1016                 {
1017                         audioStream s;
1018                         s.type = audioStream::atAACHE;
1019                         s.pid = cached_apid_aache;
1020                         s.rdsPid = -1;
1021                         program.audioStreams.push_back(s);
1022                         ++cnt;
1023                 }
1024                 if ( cached_apid_aac != -1 )
1025                 {
1026                         audioStream s;
1027                         s.type = audioStream::atAAC;
1028                         s.pid = cached_apid_aac;
1029                         s.rdsPid = -1;
1030                         program.audioStreams.push_back(s);
1031                         ++cnt;
1032                 }
1033                 if ( cached_apid_mpeg != -1 )
1034                 {
1035                         audioStream s;
1036                         s.type = audioStream::atMPEG;
1037                         s.pid = cached_apid_mpeg;
1038                         s.rdsPid = -1;
1039                         program.audioStreams.push_back(s);
1040                         ++cnt;
1041                 }
1042                 if ( cached_pcrpid != -1 )
1043                 {
1044                         ++cnt;
1045                         program.pcrPid = cached_pcrpid;
1046                 }
1047                 if ( cached_tpid != -1 )
1048                 {
1049                         ++cnt;
1050                         program.textPid = cached_tpid;
1051                 }
1052                 CAID_LIST &caids = m_service->m_ca;
1053                 for (CAID_LIST::iterator it(caids.begin()); it != caids.end(); ++it) {
1054                         program::capid_pair pair;
1055                         pair.caid = *it;
1056                         pair.capid = -1; // not known yet
1057                         program.caids.push_back(pair);
1058                 }
1059                 if ( cnt )
1060                         ret = 0;
1061         }
1062         return ret;
1063 }
1064
1065 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
1066 {
1067         channel = m_channel;
1068         if (channel)
1069                 return 0;
1070         else
1071                 return -1;
1072 }
1073
1074 int eDVBServicePMTHandler::getDataDemux(ePtr<iDVBDemux> &demux)
1075 {
1076         demux = m_demux;
1077         if (demux)
1078                 return 0;
1079         else
1080                 return -1;
1081 }
1082
1083 int eDVBServicePMTHandler::getDecodeDemux(ePtr<iDVBDemux> &demux)
1084 {
1085         int ret=0;
1086                 /* if we're using the decoding demux as data source
1087                    (for example in pvr playbacks), return that one. */
1088         if (m_use_decode_demux)
1089         {
1090                 demux = m_demux;
1091                 return ret;
1092         }
1093         
1094         ASSERT(m_channel); /* calling without a previous ::tune is certainly bad. */
1095
1096         ret = m_channel->getDemux(demux, iDVBChannel::capDecode);
1097         if (!ret)
1098                 demux->getCADemuxID(m_decode_demux_num);
1099
1100         return ret;
1101 }
1102
1103 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
1104 {
1105         pvr_channel = m_pvr_channel;
1106         if (pvr_channel)
1107                 return 0;
1108         else
1109                 return -1;
1110 }
1111
1112 void eDVBServicePMTHandler::SDTScanEvent(int event)
1113 {
1114         switch (event)
1115         {
1116                 case eDVBScan::evtFinish:
1117                 {
1118                         ePtr<iDVBChannelList> db;
1119                         if (m_resourceManager->getChannelList(db) != 0)
1120                                 eDebug("no channel list");
1121                         else
1122                         {
1123                                 eDVBChannelID chid;
1124                                 m_reference.getChannelID(chid);
1125                                 if (chid == m_dvb_scan->getCurrentChannelID())
1126                                 {
1127                                         m_dvb_scan->insertInto(db, true);
1128                                         eDebug("sdt update done!");
1129                                 }
1130                                 else
1131                                         eDebug("ignore sdt update data.... incorrect transponder tuned!!!");
1132                         }
1133                         break;
1134                 }
1135
1136                 default:
1137                         break;
1138         }
1139 }
1140
1141 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref, int use_decode_demux, eCueSheet *cue, bool simulate, eDVBService *service, serviceType type, bool descramble)
1142 {
1143         ePtr<iTsSource> s;
1144         return tuneExt(ref, use_decode_demux, s, NULL, cue, simulate, service, type, descramble);
1145 }
1146
1147 int eDVBServicePMTHandler::tuneExt(eServiceReferenceDVB &ref, int use_decode_demux, ePtr<iTsSource> &source, const char *streaminfo_file, eCueSheet *cue, bool simulate, eDVBService *service, serviceType type, bool descramble)
1148 {
1149         RESULT res=0;
1150         m_reference = ref;
1151         m_use_decode_demux = use_decode_demux;
1152         m_no_pat_entry_delay->stop();
1153         m_service_type = type;
1154         m_descramble = descramble;
1155
1156                 /* use given service as backup. This is used for timeshift where we want to clone the live stream using the cache, but in fact have a PVR channel */
1157         m_service = service;
1158         
1159                 /* is this a normal (non PVR) channel? */
1160         if (ref.path.empty())
1161         {
1162                 eDVBChannelID chid;
1163                 ref.getChannelID(chid);
1164                 res = m_resourceManager->allocateChannel(chid, m_channel, simulate);
1165                 if (!simulate)
1166                         eDebug("allocate Channel: res %d", res);
1167
1168                 if (!res)
1169                         serviceEvent(eventChannelAllocated);
1170
1171                 ePtr<iDVBChannelList> db;
1172                 if (!m_resourceManager->getChannelList(db))
1173                         db->getService((eServiceReferenceDVB&)m_reference, m_service);
1174
1175                 if (!res && !simulate && m_descramble && !m_ca_disabled)
1176                         eDVBCIInterfaces::getInstance()->addPMTHandler(this);
1177         } else if (!simulate) // no simulation of playback services
1178         {
1179                 if (!ref.getServiceID().get() /* incorrect sid in meta file or recordings.epl*/ )
1180                 {
1181                         eDVBTSTools tstools;
1182                         bool b = source || !tstools.openFile(ref.path.c_str(), 1);
1183                         eWarning("no .meta file found, trying to find PMT pid");
1184                         if (source)
1185                                 tstools.setSource(source, NULL);
1186                         if (b)
1187                         {
1188                                 int service_id, pmt_pid;
1189                                 if (!tstools.findPMT(pmt_pid, service_id))
1190                                 {
1191                                         eDebug("PMT pid found on pid %04x, service id %d", pmt_pid, service_id);
1192                                         m_reference.setServiceID(service_id);
1193                                         m_pmt_pid = pmt_pid;
1194                                 }
1195                         }
1196                         else
1197                                 eWarning("no valid source to find PMT pid!");
1198                 }
1199                 eDebug("alloc PVR");
1200                         /* allocate PVR */
1201                 eDVBChannelID chid;
1202                 if (m_service_type == streamclient) ref.getChannelID(chid);
1203                 res = m_resourceManager->allocatePVRChannel(chid, m_pvr_channel);
1204                 if (res)
1205                 {
1206                         eDebug("allocatePVRChannel failed!\n");
1207                 }
1208                 else if (descramble)
1209                 {
1210                         eDVBCIInterfaces::getInstance()->addPMTHandler(this);
1211                 }
1212                 m_channel = m_pvr_channel;
1213         }
1214
1215         if (!simulate)
1216         {
1217                 if (m_channel)
1218                 {
1219                         m_channel->connectStateChange(
1220                                 slot(*this, &eDVBServicePMTHandler::channelStateChanged), 
1221                                 m_channelStateChanged_connection);
1222                         m_last_channel_state = -1;
1223                         channelStateChanged(m_channel);
1224         
1225                         m_channel->connectEvent(
1226                                 slot(*this, &eDVBServicePMTHandler::channelEvent), 
1227                                 m_channelEvent_connection);
1228
1229                         if (ref.path.empty())
1230                         {
1231                                 m_dvb_scan = 0;
1232                                 m_dvb_scan = new eDVBScan(m_channel, true, false);
1233                                 m_dvb_scan->connectEvent(slot(*this, &eDVBServicePMTHandler::SDTScanEvent), m_scan_event_connection);
1234                         }
1235                 } else
1236                 {
1237                         if (res == eDVBResourceManager::errAllSourcesBusy)
1238                                 serviceEvent(eventNoResources);
1239                         else /* errChidNotFound, errNoChannelList, errChannelNotInList, errNoSourceFound */
1240                                 serviceEvent(eventMisconfiguration);
1241                         return res;
1242                 }
1243
1244                 if (m_pvr_channel)
1245                 {
1246                         m_pvr_channel->setCueSheet(cue);
1247
1248                         if (m_pvr_channel->getDemux(m_pvr_demux_tmp, (!m_use_decode_demux) ? 0 : iDVBChannel::capDecode))
1249                                 eDebug("[eDVBServicePMTHandler] Allocating %s-decoding a demux for PVR channel failed.", m_use_decode_demux ? "" : "non-");
1250                         else if (source)
1251                                 m_pvr_channel->playSource(source, streaminfo_file);
1252                         else
1253                                 m_pvr_channel->playFile(ref.path.c_str());
1254                 }
1255         }
1256
1257         return res;
1258 }
1259
1260 void eDVBServicePMTHandler::free()
1261 {
1262         m_dvb_scan = 0;
1263
1264         if (m_ca_servicePtr)
1265         {
1266                 int demuxes[2] = {0,0};
1267                 uint8_t tmp;
1268                 m_demux->getCADemuxID(tmp);
1269                 demuxes[0]=tmp;
1270                 if (m_decode_demux_num != 0xFF)
1271                         demuxes[1]=m_decode_demux_num;
1272                 else
1273                         demuxes[1]=demuxes[0];
1274                 ePtr<eTable<ProgramMapSection> > ptr;
1275                 m_PMT.getCurrent(ptr);
1276                 eDVBCAService::unregister_service(m_reference, demuxes, ptr);
1277                 m_ca_servicePtr = 0;
1278         }
1279
1280         if (m_channel)
1281                 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
1282
1283         if (m_pvr_channel)
1284         {
1285                 m_pvr_channel->stopFile();
1286                 m_pvr_channel->setCueSheet(0);
1287         }
1288
1289         m_OC.stop();
1290         m_AIT.stop();
1291
1292         m_PMT.stop();
1293         m_PAT.stop();
1294         m_service = 0;
1295         m_channel = 0;
1296         m_pvr_channel = 0;
1297         m_demux = 0;
1298 }
1299
1300 void eDVBServicePMTHandler::addCaHandler()
1301 {
1302         m_ca_disabled = false;
1303         if (m_channel)
1304         {
1305                 eDVBCIInterfaces::getInstance()->addPMTHandler(this);
1306                 if (m_pmt_ready)
1307                 {
1308                         eDVBCIInterfaces::getInstance()->recheckPMTHandlers();
1309                         eDVBCIInterfaces::getInstance()->gotPMT(this);
1310                 }
1311         }
1312 }
1313
1314 void eDVBServicePMTHandler::removeCaHandler()
1315 {
1316         m_ca_disabled = true;
1317         if (m_channel)
1318                 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
1319 }
1320
1321 bool eDVBServicePMTHandler::isCiConnected()
1322 {
1323         eDVBCIInterfaces::getInstance()->isCiConnected(this);
1324 }
1325
1326 CAServiceMap eDVBCAService::exist;
1327 ChannelMap eDVBCAService::exist_channels;
1328 ePtr<eConnection> eDVBCAService::m_chanAddedConn;
1329
1330 eDVBCAService::eDVBCAService()
1331         :m_buffer(512), m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eTimer::create(eApp))
1332 {
1333         memset(m_used_demux, 0xFF, sizeof(m_used_demux));
1334         CONNECT(m_retryTimer->timeout, eDVBCAService::sendCAPMT);
1335         Connect();
1336 }
1337
1338 eDVBCAService::~eDVBCAService()
1339 {
1340         eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
1341         ::close(m_sock);
1342 }
1343
1344 // begin static methods
1345 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_nums[2], eDVBCAService *&caservice )
1346 {
1347         CAServiceMap::iterator it = exist.find(ref);
1348         if ( it != exist.end() )
1349                 caservice = it->second;
1350         else
1351         {
1352                 caservice = (exist[ref]=new eDVBCAService());
1353                 caservice->m_service = ref;
1354                 eDebug("[eDVBCAService] new service %s", ref.toString().c_str() );
1355         }
1356
1357         int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
1358         for (int i=0; i < loops; ++i)
1359         {
1360 // search free demux entry
1361                 int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
1362
1363                 while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
1364                         ++iter;
1365
1366                 if ( iter < max_demux_slots )
1367                 {
1368                         caservice->m_used_demux[iter] = demux_nums[i] & 0xFF;
1369                         eDebug("[eDVBCAService] add demux %d to slot %d service %s", caservice->m_used_demux[iter], iter, ref.toString().c_str());
1370                 }
1371                 else
1372                 {
1373                         eDebug("[eDVBCAService] no more demux slots free for service %s!!", ref.toString().c_str());
1374                         return -1;
1375                 }
1376         }
1377         return 0;
1378 }
1379
1380 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_nums[2], eTable<ProgramMapSection> *ptr )
1381 {
1382         CAServiceMap::iterator it = exist.find(ref);
1383         if ( it == exist.end() )
1384         {
1385                 eDebug("[eDVBCAService] try to unregister non registered %s", ref.toString().c_str());
1386                 return -1;
1387         }
1388         else
1389         {
1390                 eDVBCAService *caservice = it->second;
1391                 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
1392                 for (int i=0; i < loops; ++i)
1393                 {
1394                         bool freed = false;
1395                         int iter = 0,
1396                                 used_demux_slots = 0,
1397                                 max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
1398                         while ( iter < max_demux_slots )
1399                         {
1400                                 if ( caservice->m_used_demux[iter] != 0xFF )
1401                                 {
1402                                         if ( !freed && caservice->m_used_demux[iter] == demux_nums[i] )
1403                                         {
1404                                                 eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
1405                                                 caservice->m_used_demux[iter] = 0xFF;
1406                                                 freed=true;
1407                                         }
1408                                         else
1409                                                 ++used_demux_slots;
1410                                 }
1411                                 ++iter;
1412                         }
1413                         if (!freed)
1414                                 eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_nums[i]);
1415                         if (i || loops == 1)
1416                         {
1417                                 if (!used_demux_slots)  // no more used.. so we remove it
1418                                 {
1419                                         delete it->second;
1420                                         exist.erase(it);
1421                                 }
1422                                 else
1423                                 {
1424                                         if (ptr)
1425                                                 it->second->buildCAPMT(ptr);
1426                                         else
1427                                                 eDebug("[eDVBCAService] can not send updated demux info");
1428                                 }
1429                         }
1430                 }
1431         }
1432         return 0;
1433 }
1434
1435 void eDVBCAService::registerChannelCallback(eDVBResourceManager *res_mgr)
1436 {
1437         res_mgr->connectChannelAdded(slot(&DVBChannelAdded), m_chanAddedConn);
1438 }
1439
1440 void eDVBCAService::DVBChannelAdded(eDVBChannel *chan)
1441 {
1442         if ( chan )
1443         {
1444                 eDebug("[eDVBCAService] new channel %p!", chan);
1445                 channel_data *data = new channel_data();
1446                 data->m_channel = chan;
1447                 data->m_prevChannelState = -1;
1448                 data->m_dataDemux = -1;
1449                 exist_channels[chan] = data;
1450                 chan->connectStateChange(slot(&DVBChannelStateChanged), data->m_stateChangedConn);
1451         }
1452 }
1453
1454 void eDVBCAService::DVBChannelStateChanged(iDVBChannel *chan)
1455 {
1456         ChannelMap::iterator it =
1457                 exist_channels.find(chan);
1458         if ( it != exist_channels.end() )
1459         {
1460                 int state=0;
1461                 chan->getState(state);
1462                 if ( it->second->m_prevChannelState != state )
1463                 {
1464                         switch (state)
1465                         {
1466                                 case iDVBChannel::state_ok:
1467                                 {
1468                                         eDebug("[eDVBCAService] channel %p running", chan);
1469                                         break;
1470                                 }
1471                                 case iDVBChannel::state_release:
1472                                 {
1473                                         eDebug("[eDVBCAService] remove channel %p", chan);
1474                                         unsigned char msg[8] = { 0x9f,0x80,0x3f,0x04,0x83,0x02,0x00,0x00 };
1475                                         msg[7] = it->second->m_dataDemux & 0xFF;
1476                                         int sock, clilen;
1477                                         struct sockaddr_un servaddr;
1478                                         memset(&servaddr, 0, sizeof(struct sockaddr_un));
1479                                         servaddr.sun_family = AF_UNIX;
1480                                         strcpy(servaddr.sun_path, "/tmp/camd.socket");
1481                                         clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
1482                                         sock = socket(PF_UNIX, SOCK_STREAM, 0);
1483                                         if (sock > -1)
1484                                         {
1485                                                 connect(sock, (struct sockaddr *) &servaddr, clilen);
1486                                                 fcntl(sock, F_SETFL, O_NONBLOCK);
1487                                                 int val=1;
1488                                                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
1489                                                 if (write(sock, msg, 8) != 8)
1490                                                         eDebug("[eDVBCAService] write leave transponder failed!!");
1491                                                 close(sock);
1492                                         }
1493                                         exist_channels.erase(it);
1494                                         delete it->second;
1495                                         it->second=0;
1496                                         break;
1497                                 }
1498                                 default: // ignore all other events
1499                                         return;
1500                         }
1501                         if (it->second)
1502                                 it->second->m_prevChannelState = state;
1503                 }
1504         }
1505 }
1506
1507 channel_data *eDVBCAService::getChannelData(eDVBChannelID &chid)
1508 {
1509         for (ChannelMap::iterator it(exist_channels.begin()); it != exist_channels.end(); ++it)
1510         {
1511                 if (chid == it->second->m_channel->getChannelID())
1512                         return it->second;
1513         }
1514         return 0;
1515 }
1516 // end static methods
1517
1518 #define CA_REPLY_DEBUG
1519 #define MAX_LENGTH_BYTES 4
1520 #define MIN_LENGTH_BYTES 1
1521
1522 void eDVBCAService::socketCB(int what)
1523 {
1524         if (what & (eSocketNotifier::Read | eSocketNotifier::Priority))
1525         {
1526                 char msgbuffer[4096];
1527                 ssize_t length = read(m_sock, msgbuffer, sizeof(msgbuffer));
1528                 if (length == -1)
1529                 {
1530                         if (errno != EAGAIN && errno != EINTR && errno != EBUSY)
1531                         {
1532                                 eDebug("[eSocketMMIHandler] read (%m)");
1533                                 what |= eSocketNotifier::Error;
1534                         }
1535                 } else if (length == 0)
1536                 {
1537                         what |= eSocketNotifier::Hungup;
1538                 } else
1539                 {
1540                         int len = length;
1541                         unsigned char *data = (unsigned char*)msgbuffer;
1542                         int clear = 1;
1543         // If a new message starts, then the previous message
1544         // should already have been processed. Otherwise the
1545         // previous message was incomplete and should therefore
1546         // be deleted.
1547                         if ((len >= 1) && ((data[0] & 0xFF) != 0x9f))
1548                                 clear = 0;
1549                         if ((len >= 2) && ((data[1] & 0x80) != 0x80))
1550                                 clear = 0;
1551                         if ((len >= 3) && ((data[2] & 0x80) != 0x00))
1552                                 clear = 0;
1553                         if (clear)
1554                         {
1555                                 m_buffer.clear();
1556 #ifdef CA_REPLY_DEBUG
1557                                 eDebug("clear buffer");
1558 #endif
1559                         }
1560 #ifdef CA_REPLY_DEBUG
1561                         eDebug("Put to buffer:");
1562                         for (int i=0; i < len; ++i)
1563                                 eDebugNoNewLine("%02x ", data[i]);
1564                         eDebug("\n--------");
1565 #endif
1566                         m_buffer.write( data, len );
1567
1568                         while ( m_buffer.size() >= (3 + MIN_LENGTH_BYTES) )
1569                         {
1570                                 unsigned char tmp[3+MAX_LENGTH_BYTES];
1571                                 m_buffer.peek(tmp, 3+MIN_LENGTH_BYTES);
1572                                 if (((tmp[0] & 0xFF) != 0x9f) || ((tmp[1] & 0x80) != 0x80) || ((tmp[2] & 0x80) != 0x00))
1573                                 {
1574                                         m_buffer.skip(1);
1575 #ifdef CA_REPLY_DEBUG
1576                                         eDebug("skip %02x", tmp[0]);
1577 #endif
1578                                         continue;
1579                                 }
1580                                 if (tmp[3] & 0x80)
1581                                 {
1582                                         int peekLength = (tmp[3] & 0x7f) + 4;
1583                                         if (m_buffer.size() < peekLength)
1584                                                 continue;
1585                                         m_buffer.peek(tmp, peekLength);
1586                                 }
1587                                 int size=0;
1588                                 int LengthBytes=eDVBCISession::parseLengthField(tmp+3, size);
1589                                 int messageLength = 3+LengthBytes+size;
1590                                 if ( m_buffer.size() >= messageLength )
1591                                 {
1592                                         unsigned char dest[messageLength];
1593                                         m_buffer.read(dest, messageLength);
1594 #ifdef CA_REPLY_DEBUG
1595                                         eDebug("dump ca reply:");
1596                                         for (int i=0; i < messageLength; ++i)
1597                                                 eDebugNoNewLine("%02x ", dest[i]);
1598                                         eDebug("\n--------");
1599 #endif
1600 //                                      /*emit*/ mmi_progress(0, dest, (const void*)(dest+3+LengthBytes), messageLength-3-LengthBytes);
1601                                 }
1602                         }
1603                 }
1604         }
1605         if (what & eSocketNotifier::Hungup) {
1606                 /*eDebug("[eDVBCAService] connection closed")*/;
1607                 m_sendstate=1;
1608                 sendCAPMT();
1609         }
1610         if (what & eSocketNotifier::Error)
1611                 eDebug("[eDVBCAService] connection error");
1612 }
1613
1614 void eDVBCAService::Connect()
1615 {
1616         m_sn=0;
1617         memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
1618         m_servaddr.sun_family = AF_UNIX;
1619         strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
1620         m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
1621         m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
1622         if (m_sock != -1)
1623         {
1624                 if (!connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen))
1625                 {
1626                         int val=1;
1627                         fcntl(m_sock, F_SETFL, O_NONBLOCK);
1628                         setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
1629                         m_sn = eSocketNotifier::create(eApp, m_sock,
1630                                 eSocketNotifier::Read|eSocketNotifier::Priority|eSocketNotifier::Error|eSocketNotifier::Hungup);
1631                         CONNECT(m_sn->activated, eDVBCAService::socketCB);
1632                         
1633                 }
1634 //              else
1635 //                      eDebug("[eDVBCAService] connect failed %m");
1636         }
1637         else
1638                 eDebug("[eDVBCAService] create socket failed %m");
1639 }
1640
1641 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
1642 {
1643         if (!ptr)
1644                 return;
1645
1646         eDVBTableSpec table_spec;
1647         ptr->getSpec(table_spec);
1648
1649         int pmtpid = table_spec.pid,
1650                 pmt_version = table_spec.version;
1651
1652         uint8_t demux_mask = 0;
1653         int data_demux = -1;
1654
1655         int iter=0, max_demux_slots = sizeof(m_used_demux);
1656         while ( iter < max_demux_slots )
1657         {
1658                 if ( m_used_demux[iter] != 0xFF )
1659                 {
1660                         if ( m_used_demux[iter] > data_demux )
1661                                 data_demux = m_used_demux[iter];
1662                         demux_mask |= (1 << m_used_demux[iter]);
1663                 }
1664                 ++iter;
1665         }
1666
1667         if ( data_demux == -1 )
1668         {
1669                 eDebug("[eDVBCAService] no data demux found for service %s", m_service.toString().c_str() );
1670                 return;
1671         }
1672
1673         eDebug("demux %d mask %02x prevhash %08x", data_demux, demux_mask, m_prev_build_hash);
1674
1675         unsigned int build_hash = ( pmtpid << 16);
1676         build_hash |= (demux_mask << 8);
1677         build_hash |= (pmt_version&0xFF);
1678
1679         if ( build_hash == m_prev_build_hash )
1680         {
1681                 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
1682                 return;
1683         }
1684
1685         std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
1686         if ( i != ptr->getSections().end() )
1687         {
1688                 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
1689
1690                 while( i != ptr->getSections().end() )
1691                 {
1692 //                      eDebug("append");
1693                         capmt.append(*i++);
1694                 }
1695
1696                 // add our private descriptors to capmt
1697                 uint8_t tmp[10];
1698
1699                 tmp[0]=0x84;  // pmt pid
1700                 tmp[1]=0x02;
1701                 tmp[2]=pmtpid>>8;
1702                 tmp[3]=pmtpid&0xFF;
1703                 capmt.injectDescriptor(tmp, false);
1704
1705                 tmp[0] = 0x82; // demux
1706                 tmp[1] = 0x02;
1707                 tmp[2] = demux_mask;    // descramble bitmask
1708                 tmp[3] = data_demux&0xFF; // read section data from demux number
1709                 capmt.injectDescriptor(tmp, false);
1710
1711                 tmp[0] = 0x81; // dvbnamespace
1712                 tmp[1] = 0x08;
1713                 tmp[2] = m_service.getDVBNamespace().get()>>24;
1714                 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
1715                 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
1716                 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
1717                 tmp[6]=m_service.getTransportStreamID().get()>>8;
1718                 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
1719                 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
1720                 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
1721                 capmt.injectDescriptor(tmp, false);
1722
1723                 capmt.writeToBuffer(m_capmt);
1724         }
1725
1726         m_prev_build_hash = build_hash;
1727
1728         if ( m_sendstate != 0xFFFFFFFF )
1729                 m_sendstate=0;
1730         sendCAPMT();
1731 }
1732
1733 void eDVBCAService::sendCAPMT()
1734 {
1735         if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
1736         {
1737                 ::close(m_sock);
1738                 Connect();
1739         }
1740
1741         int wp=0;
1742         if ( m_capmt[3] & 0x80 )
1743         {
1744                 int i=0;
1745                 int lenbytes = m_capmt[3] & ~0x80;
1746                 while(i < lenbytes)
1747                         wp = (wp << 8) | m_capmt[4 + i++];
1748                 wp+=4;
1749                 wp+=lenbytes;
1750         }
1751         else
1752         {
1753                 wp = m_capmt[3];
1754                 wp+=4;
1755         }
1756
1757         if ( write(m_sock, m_capmt, wp) == wp )
1758         {
1759                 m_sendstate=0xFFFFFFFF;
1760                 eDebug("[eDVBCAService] send %d bytes",wp);
1761                 eDVBChannelID chid;
1762                 m_service.getChannelID(chid);
1763                 channel_data *data = getChannelData(chid);
1764                 if (data)
1765                 {
1766                         int lenbytes = m_capmt[3] & 0x80 ? m_capmt[3] & ~0x80 : 0;
1767                         data->m_dataDemux = m_capmt[24+lenbytes];
1768                 }
1769 #if 1
1770                 for(int i=0;i<wp;i++)
1771                         eDebugNoNewLine("%02x ", m_capmt[i]);
1772                 eDebug("");
1773 #endif
1774         }
1775         else
1776         {
1777                 switch(m_sendstate)
1778                 {
1779                         case 0xFFFFFFFF:
1780                                 ++m_sendstate;
1781                                 m_retryTimer->start(0,true);
1782 //                              eDebug("[eDVBCAService] send failed .. immediate retry");
1783                                 break;
1784                         default:
1785                                 m_retryTimer->start(5000,true);
1786 //                              eDebug("[eDVBCAService] send failed .. retry in 5 sec");
1787                                 break;
1788                 }
1789                 ++m_sendstate;
1790         }
1791 }
1792
1793 static PyObject *createTuple(int pid, const char *type)
1794 {
1795         PyObject *r = PyTuple_New(2);
1796         PyTuple_SET_ITEM(r, 0, PyInt_FromLong(pid));
1797         PyTuple_SET_ITEM(r, 1, PyString_FromString(type));
1798         return r;
1799 }
1800
1801 static inline void PyList_AppendSteal(PyObject *list, PyObject *item)
1802 {
1803         PyList_Append(list, item);
1804         Py_DECREF(item);
1805 }
1806
1807 extern void PutToDict(ePyObject &dict, const char*key, ePyObject item); // defined in dvb/frontend.cpp
1808
1809 PyObject *eDVBServicePMTHandler::program::createPythonObject()
1810 {
1811         ePyObject r = PyDict_New();
1812         ePyObject l = PyList_New(0);
1813
1814         PyList_AppendSteal(l, createTuple(0, "pat"));
1815
1816         if (pmtPid != -1)
1817                 PyList_AppendSteal(l, createTuple(pmtPid, "pmt"));
1818
1819         for (std::vector<eDVBServicePMTHandler::videoStream>::const_iterator
1820                         i(videoStreams.begin()); 
1821                         i != videoStreams.end(); ++i)
1822                 PyList_AppendSteal(l, createTuple(i->pid, "video"));
1823
1824         for (std::vector<eDVBServicePMTHandler::audioStream>::const_iterator
1825                         i(audioStreams.begin()); 
1826                         i != audioStreams.end(); ++i)
1827                 PyList_AppendSteal(l, createTuple(i->pid, "audio"));
1828
1829         for (std::vector<eDVBServicePMTHandler::subtitleStream>::const_iterator
1830                         i(subtitleStreams.begin());
1831                         i != subtitleStreams.end(); ++i)
1832                 PyList_AppendSteal(l, createTuple(i->pid, "subtitle"));
1833
1834         PyList_AppendSteal(l, createTuple(pcrPid, "pcr"));
1835
1836         if (textPid != -1)
1837                 PyList_AppendSteal(l, createTuple(textPid, "text"));
1838
1839         PutToDict(r, "pids", l);
1840
1841         return r;
1842 }