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