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