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