add new tuneExt function to eDVBServicePMTHandler to make the class more reusable
[vuplus_dvbapp] / lib / dvb / pmt.cpp
1 #include <lib/base/nconfig.h> // access to python config
2 #include <lib/base/eerror.h>
3 #include <lib/dvb/pmt.h>
4 #include <lib/dvb/specs.h>
5 #include <lib/dvb/dvb.h>
6 #include <lib/dvb/metaparser.h>
7 #include <lib/dvb_ci/dvbci.h>
8 #include <lib/dvb/epgcache.h>
9 #include <lib/dvb/scan.h>
10 #include <lib/dvb_ci/dvbci_session.h>
11 #include <dvbsi++/ca_descriptor.h>
12 #include <dvbsi++/ca_program_map_section.h>
13 #include <dvbsi++/teletext_descriptor.h>
14 #include <dvbsi++/descriptor_tag.h>
15 #include <dvbsi++/iso639_language_descriptor.h>
16 #include <dvbsi++/stream_identifier_descriptor.h>
17 #include <dvbsi++/subtitling_descriptor.h>
18 #include <dvbsi++/teletext_descriptor.h>
19 #include <dvbsi++/video_stream_descriptor.h>
20 #include <dvbsi++/registration_descriptor.h>
21
22 eDVBServicePMTHandler::eDVBServicePMTHandler()
23         :m_ca_servicePtr(0), m_dvb_scan(0), m_decode_demux_num(0xFF)
24 {
25         m_use_decode_demux = 0;
26         m_pmt_pid = -1;
27         eDVBResourceManager::getInstance(m_resourceManager);
28         CONNECT(m_PMT.tableReady, eDVBServicePMTHandler::PMTready);
29         CONNECT(m_PAT.tableReady, eDVBServicePMTHandler::PATready);
30 }
31
32 eDVBServicePMTHandler::~eDVBServicePMTHandler()
33 {
34         free();
35 }
36
37 void eDVBServicePMTHandler::channelStateChanged(iDVBChannel *channel)
38 {
39         int state;
40         channel->getState(state);
41         
42         if ((m_last_channel_state != iDVBChannel::state_ok)
43                 && (state == iDVBChannel::state_ok) && (!m_demux))
44         {
45                 if (m_channel)
46                         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(); pmtpid == -1 && i != ptr->getSections().end(); ++i)
137                 {
138                         const ProgramAssociationSection &pat = **i;
139                         ProgramAssociationConstIterator program;
140                         for (program = pat.getPrograms()->begin(); pmtpid == -1 && 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         ePtr<iDataSource> s;
679         return tuneExt(ref, use_decode_demux, s, cue, simulate, service);
680 }
681
682 int eDVBServicePMTHandler::tuneExt(eServiceReferenceDVB &ref, int use_decode_demux, ePtr<iDataSource> &source, eCueSheet *cue, bool simulate, eDVBService *service)
683 {
684         RESULT res=0;
685         m_reference = ref;
686         
687         m_use_decode_demux = use_decode_demux;
688
689                 /* 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 */
690         m_service = service;
691         
692                 /* is this a normal (non PVR) channel? */
693         if (ref.path.empty())
694         {
695                 eDVBChannelID chid;
696                 ref.getChannelID(chid);
697                 res = m_resourceManager->allocateChannel(chid, m_channel, simulate);
698                 if (!simulate)
699                         eDebug("allocate Channel: res %d", res);
700
701                 ePtr<iDVBChannelList> db;
702                 if (!m_resourceManager->getChannelList(db))
703                         db->getService((eServiceReferenceDVB&)m_reference, m_service);
704
705                 if (!res && !simulate)
706                         eDVBCIInterfaces::getInstance()->addPMTHandler(this);
707         } else if (!simulate) // no simulation of playback services
708         {
709                 if (!ref.getServiceID().get() /* incorrect sid in meta file or recordings.epl*/ )
710                 {
711                         eWarning("no .meta file found, trying to find PMT pid");
712                         eDVBTSTools tstools;
713                         if (tstools.openFile(ref.path.c_str()))
714                                 eWarning("failed to open file");
715                         else
716                         {
717                                 int service_id, pmt_pid;
718                                 if (!tstools.findPMT(pmt_pid, service_id))
719                                 {
720                                         eDebug("PMT pid found on pid %04x, service id %d", pmt_pid, service_id);
721                                         m_reference.setServiceID(service_id);
722                                         m_pmt_pid = pmt_pid;
723                                 }
724                         }
725                 }
726                 eDebug("alloc PVR");
727                         /* allocate PVR */
728                 res = m_resourceManager->allocatePVRChannel(m_pvr_channel);
729                 if (res)
730                         eDebug("allocatePVRChannel failed!\n");
731                 m_channel = m_pvr_channel;
732         }
733
734         if (!simulate)
735         {
736                 if (m_channel)
737                 {
738                         m_channel->connectStateChange(
739                                 slot(*this, &eDVBServicePMTHandler::channelStateChanged), 
740                                 m_channelStateChanged_connection);
741                         m_last_channel_state = -1;
742                         channelStateChanged(m_channel);
743         
744                         m_channel->connectEvent(
745                                 slot(*this, &eDVBServicePMTHandler::channelEvent), 
746                                 m_channelEvent_connection);
747
748                         if (ref.path.empty())
749                         {
750                                 m_dvb_scan = 0;
751                                 m_dvb_scan = new eDVBScan(m_channel, true, false);
752                                 m_dvb_scan->connectEvent(slot(*this, &eDVBServicePMTHandler::SDTScanEvent), m_scan_event_connection);
753                         }
754                 } else
755                 {
756                         if (res == eDVBResourceManager::errAllSourcesBusy)
757                                 serviceEvent(eventNoResources);
758                         else /* errChidNotFound, errNoChannelList, errChannelNotInList, errNoSourceFound */
759                                 serviceEvent(eventMisconfiguration);
760                         return res;
761                 }
762
763                 if (m_pvr_channel)
764                 {
765                         m_pvr_channel->setCueSheet(cue);
766                         if (source)
767                                 m_pvr_channel->playSource(source);
768                         else
769                                 m_pvr_channel->playFile(ref.path.c_str());
770                 }
771         }
772
773         return res;
774 }
775
776 void eDVBServicePMTHandler::free()
777 {
778         m_dvb_scan = 0;
779
780         if (m_ca_servicePtr)
781         {
782                 int demuxes[2] = {0,0};
783                 uint8_t tmp;
784                 m_demux->getCADemuxID(tmp);
785                 demuxes[0]=tmp;
786                 if (m_decode_demux_num != 0xFF)
787                         demuxes[1]=m_decode_demux_num;
788                 else
789                         demuxes[1]=demuxes[0];
790                 ePtr<eTable<ProgramMapSection> > ptr;
791                 m_PMT.getCurrent(ptr);
792                 eDVBCAService::unregister_service(m_reference, demuxes, ptr);
793                 m_ca_servicePtr = 0;
794         }
795
796         if (m_channel)
797                 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
798
799         if (m_pvr_channel)
800         {
801                 m_pvr_channel->stopFile();
802                 m_pvr_channel->setCueSheet(0);
803         }
804
805         m_PMT.stop();
806         m_PAT.stop();
807         m_service = 0;
808         m_channel = 0;
809         m_pvr_channel = 0;
810         m_demux = 0;
811 }
812
813 CAServiceMap eDVBCAService::exist;
814 ChannelMap eDVBCAService::exist_channels;
815 ePtr<eConnection> eDVBCAService::m_chanAddedConn;
816
817 eDVBCAService::eDVBCAService()
818         :m_buffer(512), m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eTimer::create(eApp))
819 {
820         memset(m_used_demux, 0xFF, sizeof(m_used_demux));
821         CONNECT(m_retryTimer->timeout, eDVBCAService::sendCAPMT);
822         Connect();
823 }
824
825 eDVBCAService::~eDVBCAService()
826 {
827         eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
828         ::close(m_sock);
829 }
830
831 // begin static methods
832 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_nums[2], eDVBCAService *&caservice )
833 {
834         CAServiceMap::iterator it = exist.find(ref);
835         if ( it != exist.end() )
836                 caservice = it->second;
837         else
838         {
839                 caservice = (exist[ref]=new eDVBCAService());
840                 caservice->m_service = ref;
841                 eDebug("[eDVBCAService] new service %s", ref.toString().c_str() );
842         }
843
844         int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
845         for (int i=0; i < loops; ++i)
846         {
847 // search free demux entry
848                 int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
849
850                 while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
851                         ++iter;
852
853                 if ( iter < max_demux_slots )
854                 {
855                         caservice->m_used_demux[iter] = demux_nums[i] & 0xFF;
856                         eDebug("[eDVBCAService] add demux %d to slot %d service %s", caservice->m_used_demux[iter], iter, ref.toString().c_str());
857                 }
858                 else
859                 {
860                         eDebug("[eDVBCAService] no more demux slots free for service %s!!", ref.toString().c_str());
861                         return -1;
862                 }
863         }
864         return 0;
865 }
866
867 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_nums[2], eTable<ProgramMapSection> *ptr )
868 {
869         CAServiceMap::iterator it = exist.find(ref);
870         if ( it == exist.end() )
871         {
872                 eDebug("[eDVBCAService] try to unregister non registered %s", ref.toString().c_str());
873                 return -1;
874         }
875         else
876         {
877                 eDVBCAService *caservice = it->second;
878                 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
879                 for (int i=0; i < loops; ++i)
880                 {
881                         bool freed = false;
882                         int iter = 0,
883                                 used_demux_slots = 0,
884                                 max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
885                         while ( iter < max_demux_slots )
886                         {
887                                 if ( caservice->m_used_demux[iter] != 0xFF )
888                                 {
889                                         if ( !freed && caservice->m_used_demux[iter] == demux_nums[i] )
890                                         {
891                                                 eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
892                                                 caservice->m_used_demux[iter] = 0xFF;
893                                                 freed=true;
894                                         }
895                                         else
896                                                 ++used_demux_slots;
897                                 }
898                                 ++iter;
899                         }
900                         if (!freed)
901                                 eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_nums[i]);
902                         if (i || loops == 1)
903                         {
904                                 if (!used_demux_slots)  // no more used.. so we remove it
905                                 {
906                                         delete it->second;
907                                         exist.erase(it);
908                                 }
909                                 else
910                                 {
911                                         if (ptr)
912                                                 it->second->buildCAPMT(ptr);
913                                         else
914                                                 eDebug("[eDVBCAService] can not send updated demux info");
915                                 }
916                         }
917                 }
918         }
919         return 0;
920 }
921
922 void eDVBCAService::registerChannelCallback(eDVBResourceManager *res_mgr)
923 {
924         res_mgr->connectChannelAdded(slot(&DVBChannelAdded), m_chanAddedConn);
925 }
926
927 void eDVBCAService::DVBChannelAdded(eDVBChannel *chan)
928 {
929         if ( chan )
930         {
931                 eDebug("[eDVBCAService] new channel %p!", chan);
932                 channel_data *data = new channel_data();
933                 data->m_channel = chan;
934                 data->m_prevChannelState = -1;
935                 data->m_dataDemux = -1;
936                 exist_channels[chan] = data;
937                 chan->connectStateChange(slot(&DVBChannelStateChanged), data->m_stateChangedConn);
938         }
939 }
940
941 void eDVBCAService::DVBChannelStateChanged(iDVBChannel *chan)
942 {
943         ChannelMap::iterator it =
944                 exist_channels.find(chan);
945         if ( it != exist_channels.end() )
946         {
947                 int state=0;
948                 chan->getState(state);
949                 if ( it->second->m_prevChannelState != state )
950                 {
951                         switch (state)
952                         {
953                                 case iDVBChannel::state_ok:
954                                 {
955                                         eDebug("[eDVBCAService] channel %p running", chan);
956                                         break;
957                                 }
958                                 case iDVBChannel::state_release:
959                                 {
960                                         eDebug("[eDVBCAService] remove channel %p", chan);
961                                         unsigned char msg[8] = { 0x9f,0x80,0x3f,0x04,0x83,0x02,0x00,0x00 };
962                                         msg[7] = it->second->m_dataDemux & 0xFF;
963                                         int sock, clilen;
964                                         struct sockaddr_un servaddr;
965                                         memset(&servaddr, 0, sizeof(struct sockaddr_un));
966                                         servaddr.sun_family = AF_UNIX;
967                                         strcpy(servaddr.sun_path, "/tmp/camd.socket");
968                                         clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
969                                         sock = socket(PF_UNIX, SOCK_STREAM, 0);
970                                         if (sock > -1)
971                                         {
972                                                 connect(sock, (struct sockaddr *) &servaddr, clilen);
973                                                 fcntl(sock, F_SETFL, O_NONBLOCK);
974                                                 int val=1;
975                                                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
976                                                 if (write(sock, msg, 8) != 8)
977                                                         eDebug("[eDVBCAService] write leave transponder failed!!");
978                                                 close(sock);
979                                         }
980                                         exist_channels.erase(it);
981                                         delete it->second;
982                                         it->second=0;
983                                         break;
984                                 }
985                                 default: // ignore all other events
986                                         return;
987                         }
988                         if (it->second)
989                                 it->second->m_prevChannelState = state;
990                 }
991         }
992 }
993
994 channel_data *eDVBCAService::getChannelData(eDVBChannelID &chid)
995 {
996         for (ChannelMap::iterator it(exist_channels.begin()); it != exist_channels.end(); ++it)
997         {
998                 if (chid == it->second->m_channel->getChannelID())
999                         return it->second;
1000         }
1001         return 0;
1002 }
1003 // end static methods
1004
1005 #define CA_REPLY_DEBUG
1006 #define MAX_LENGTH_BYTES 4
1007 #define MIN_LENGTH_BYTES 1
1008
1009 void eDVBCAService::socketCB(int what)
1010 {
1011         if (what & (eSocketNotifier::Read | eSocketNotifier::Priority))
1012         {
1013                 char msgbuffer[4096];
1014                 ssize_t length = read(m_sock, msgbuffer, sizeof(msgbuffer));
1015                 if (length == -1)
1016                 {
1017                         if (errno != EAGAIN && errno != EINTR && errno != EBUSY)
1018                         {
1019                                 eDebug("[eSocketMMIHandler] read (%m)");
1020                                 what |= eSocketNotifier::Error;
1021                         }
1022                 } else if (length == 0)
1023                 {
1024                         what |= eSocketNotifier::Hungup;
1025                 } else
1026                 {
1027                         int len = length;
1028                         unsigned char *data = (unsigned char*)msgbuffer;
1029                         int clear = 1;
1030         // If a new message starts, then the previous message
1031         // should already have been processed. Otherwise the
1032         // previous message was incomplete and should therefore
1033         // be deleted.
1034                         if ((len >= 1) && ((data[0] & 0xFF) != 0x9f))
1035                                 clear = 0;
1036                         if ((len >= 2) && ((data[1] & 0x80) != 0x80))
1037                                 clear = 0;
1038                         if ((len >= 3) && ((data[2] & 0x80) != 0x00))
1039                                 clear = 0;
1040                         if (clear)
1041                         {
1042                                 m_buffer.clear();
1043 #ifdef CA_REPLY_DEBUG
1044                                 eDebug("clear buffer");
1045 #endif
1046                         }
1047 #ifdef CA_REPLY_DEBUG
1048                         eDebug("Put to buffer:");
1049                         for (int i=0; i < len; ++i)
1050                                 eDebugNoNewLine("%02x ", data[i]);
1051                         eDebug("\n--------");
1052 #endif
1053                         m_buffer.write( data, len );
1054
1055                         while ( m_buffer.size() >= (3 + MIN_LENGTH_BYTES) )
1056                         {
1057                                 unsigned char tmp[3+MAX_LENGTH_BYTES];
1058                                 m_buffer.peek(tmp, 3+MIN_LENGTH_BYTES);
1059                                 if (((tmp[0] & 0xFF) != 0x9f) || ((tmp[1] & 0x80) != 0x80) || ((tmp[2] & 0x80) != 0x00))
1060                                 {
1061                                         m_buffer.skip(1);
1062 #ifdef CA_REPLY_DEBUG
1063                                         eDebug("skip %02x", tmp[0]);
1064 #endif
1065                                         continue;
1066                                 }
1067                                 if (tmp[3] & 0x80)
1068                                 {
1069                                         int peekLength = (tmp[3] & 0x7f) + 4;
1070                                         if (m_buffer.size() < peekLength)
1071                                                 continue;
1072                                         m_buffer.peek(tmp, peekLength);
1073                                 }
1074                                 int size=0;
1075                                 int LengthBytes=eDVBCISession::parseLengthField(tmp+3, size);
1076                                 int messageLength = 3+LengthBytes+size;
1077                                 if ( m_buffer.size() >= messageLength )
1078                                 {
1079                                         unsigned char dest[messageLength];
1080                                         m_buffer.read(dest, messageLength);
1081 #ifdef CA_REPLY_DEBUG
1082                                         eDebug("dump ca reply:");
1083                                         for (int i=0; i < messageLength; ++i)
1084                                                 eDebugNoNewLine("%02x ", dest[i]);
1085                                         eDebug("\n--------");
1086 #endif
1087 //                                      /*emit*/ mmi_progress(0, dest, (const void*)(dest+3+LengthBytes), messageLength-3-LengthBytes);
1088                                 }
1089                         }
1090                 }
1091         }
1092         if (what & eSocketNotifier::Hungup) {
1093                 /*eDebug("[eDVBCAService] connection closed")*/;
1094                 m_sendstate=1;
1095                 sendCAPMT();
1096         }
1097         if (what & eSocketNotifier::Error)
1098                 eDebug("[eDVBCAService] connection error");
1099 }
1100
1101 void eDVBCAService::Connect()
1102 {
1103         m_sn=0;
1104         memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
1105         m_servaddr.sun_family = AF_UNIX;
1106         strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
1107         m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
1108         m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
1109         if (m_sock != -1)
1110         {
1111                 if (!connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen))
1112                 {
1113                         int val=1;
1114                         fcntl(m_sock, F_SETFL, O_NONBLOCK);
1115                         setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
1116                         m_sn = eSocketNotifier::create(eApp, m_sock,
1117                                 eSocketNotifier::Read|eSocketNotifier::Priority|eSocketNotifier::Error|eSocketNotifier::Hungup);
1118                         CONNECT(m_sn->activated, eDVBCAService::socketCB);
1119                         
1120                 }
1121 //              else
1122 //                      eDebug("[eDVBCAService] connect failed %m");
1123         }
1124         else
1125                 eDebug("[eDVBCAService] create socket failed %m");
1126 }
1127
1128 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
1129 {
1130         if (!ptr)
1131                 return;
1132
1133         eDVBTableSpec table_spec;
1134         ptr->getSpec(table_spec);
1135
1136         int pmtpid = table_spec.pid,
1137                 pmt_version = table_spec.version;
1138
1139         uint8_t demux_mask = 0;
1140         int data_demux = -1;
1141
1142         int iter=0, max_demux_slots = sizeof(m_used_demux);
1143         while ( iter < max_demux_slots )
1144         {
1145                 if ( m_used_demux[iter] != 0xFF )
1146                 {
1147                         if ( m_used_demux[iter] > data_demux )
1148                                 data_demux = m_used_demux[iter];
1149                         demux_mask |= (1 << m_used_demux[iter]);
1150                 }
1151                 ++iter;
1152         }
1153
1154         if ( data_demux == -1 )
1155         {
1156                 eDebug("[eDVBCAService] no data demux found for service %s", m_service.toString().c_str() );
1157                 return;
1158         }
1159
1160         eDebug("demux %d mask %02x prevhash %08x", data_demux, demux_mask, m_prev_build_hash);
1161
1162         unsigned int build_hash = ( pmtpid << 16);
1163         build_hash |= (demux_mask << 8);
1164         build_hash |= (pmt_version&0xFF);
1165
1166         if ( build_hash == m_prev_build_hash )
1167         {
1168                 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
1169                 return;
1170         }
1171
1172         std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
1173         if ( i != ptr->getSections().end() )
1174         {
1175                 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
1176
1177                 while( i != ptr->getSections().end() )
1178                 {
1179 //                      eDebug("append");
1180                         capmt.append(*i++);
1181                 }
1182
1183                 // add our private descriptors to capmt
1184                 uint8_t tmp[10];
1185
1186                 tmp[0]=0x84;  // pmt pid
1187                 tmp[1]=0x02;
1188                 tmp[2]=pmtpid>>8;
1189                 tmp[3]=pmtpid&0xFF;
1190                 capmt.injectDescriptor(tmp, false);
1191
1192                 tmp[0] = 0x82; // demux
1193                 tmp[1] = 0x02;
1194                 tmp[2] = demux_mask;    // descramble bitmask
1195                 tmp[3] = data_demux&0xFF; // read section data from demux number
1196                 capmt.injectDescriptor(tmp, false);
1197
1198                 tmp[0] = 0x81; // dvbnamespace
1199                 tmp[1] = 0x08;
1200                 tmp[2] = m_service.getDVBNamespace().get()>>24;
1201                 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
1202                 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
1203                 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
1204                 tmp[6]=m_service.getTransportStreamID().get()>>8;
1205                 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
1206                 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
1207                 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
1208                 capmt.injectDescriptor(tmp, false);
1209
1210                 capmt.writeToBuffer(m_capmt);
1211         }
1212
1213         m_prev_build_hash = build_hash;
1214
1215         if ( m_sendstate != 0xFFFFFFFF )
1216                 m_sendstate=0;
1217         sendCAPMT();
1218 }
1219
1220 void eDVBCAService::sendCAPMT()
1221 {
1222         if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
1223         {
1224                 ::close(m_sock);
1225                 Connect();
1226         }
1227
1228         int wp=0;
1229         if ( m_capmt[3] & 0x80 )
1230         {
1231                 int i=0;
1232                 int lenbytes = m_capmt[3] & ~0x80;
1233                 while(i < lenbytes)
1234                         wp = (wp << 8) | m_capmt[4 + i++];
1235                 wp+=4;
1236                 wp+=lenbytes;
1237         }
1238         else
1239         {
1240                 wp = m_capmt[3];
1241                 wp+=4;
1242         }
1243
1244         if ( write(m_sock, m_capmt, wp) == wp )
1245         {
1246                 m_sendstate=0xFFFFFFFF;
1247                 eDebug("[eDVBCAService] send %d bytes",wp);
1248                 eDVBChannelID chid;
1249                 m_service.getChannelID(chid);
1250                 channel_data *data = getChannelData(chid);
1251                 if (data)
1252                 {
1253                         int lenbytes = m_capmt[3] & 0x80 ? m_capmt[3] & ~0x80 : 0;
1254                         data->m_dataDemux = m_capmt[24+lenbytes];
1255                 }
1256 #if 1
1257                 for(int i=0;i<wp;i++)
1258                         eDebugNoNewLine("%02x ", m_capmt[i]);
1259                 eDebug("");
1260 #endif
1261         }
1262         else
1263         {
1264                 switch(m_sendstate)
1265                 {
1266                         case 0xFFFFFFFF:
1267                                 ++m_sendstate;
1268                                 m_retryTimer->start(0,true);
1269 //                              eDebug("[eDVBCAService] send failed .. immediate retry");
1270                                 break;
1271                         default:
1272                                 m_retryTimer->start(5000,true);
1273 //                              eDebug("[eDVBCAService] send failed .. retry in 5 sec");
1274                                 break;
1275                 }
1276                 ++m_sendstate;
1277         }
1278 }
1279
1280 static PyObject *createTuple(int pid, const char *type)
1281 {
1282         PyObject *r = PyTuple_New(2);
1283         PyTuple_SET_ITEM(r, 0, PyInt_FromLong(pid));
1284         PyTuple_SET_ITEM(r, 1, PyString_FromString(type));
1285         return r;
1286 }
1287
1288 static inline void PyList_AppendSteal(PyObject *list, PyObject *item)
1289 {
1290         PyList_Append(list, item);
1291         Py_DECREF(item);
1292 }
1293
1294 extern void PutToDict(ePyObject &dict, const char*key, ePyObject item); // defined in dvb/frontend.cpp
1295
1296 PyObject *eDVBServicePMTHandler::program::createPythonObject()
1297 {
1298         ePyObject r = PyDict_New();
1299         ePyObject l = PyList_New(0);
1300
1301         PyList_AppendSteal(l, createTuple(0, "pat"));
1302
1303         if (pmtPid != -1)
1304                 PyList_AppendSteal(l, createTuple(pmtPid, "pmt"));
1305
1306         for (std::vector<eDVBServicePMTHandler::videoStream>::const_iterator
1307                         i(videoStreams.begin()); 
1308                         i != videoStreams.end(); ++i)
1309                 PyList_AppendSteal(l, createTuple(i->pid, "video"));
1310
1311         for (std::vector<eDVBServicePMTHandler::audioStream>::const_iterator
1312                         i(audioStreams.begin()); 
1313                         i != audioStreams.end(); ++i)
1314                 PyList_AppendSteal(l, createTuple(i->pid, "audio"));
1315
1316         for (std::vector<eDVBServicePMTHandler::subtitleStream>::const_iterator
1317                         i(subtitleStreams.begin());
1318                         i != subtitleStreams.end(); ++i)
1319                 PyList_AppendSteal(l, createTuple(i->pid, "subtitle"));
1320
1321         PyList_AppendSteal(l, createTuple(pcrPid, "pcr"));
1322
1323         if (textPid != -1)
1324                 PyList_AppendSteal(l, createTuple(textPid, "text"));
1325
1326         PutToDict(r, "pids", l);
1327
1328         return r;
1329 }