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