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