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