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