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