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