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