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