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