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