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