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