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