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