enigma.cpp: take care of running fullsize pig timer on e2 shutdown
[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;
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                                                                                 const VbiTeletextList *list = d->getVbiTeletexts();
346                                                                                 for (VbiTeletextConstIterator it(list->begin()); it != list->end(); ++it)
347                                                                                 {
348                                                                                         switch((*it)->getTeletextType())
349                                                                                         {
350                                                                                         case 0x02: // Teletext subtitle page
351                                                                                         case 0x05: // Teletext subtitle page for hearing impaired pepople
352                                                                                                 s.language_code = (*it)->getIso639LanguageCode();
353                                                                                                 s.teletext_page_number = (*it)->getTeletextPageNumber();
354                                                                                                 s.teletext_magazine_number = (*it)->getTeletextMagazineNumber();
355 //                                                                                              eDebug("add teletext subtitle %s PID %04x, page number %d, magazine number %d",
356 //                                                                                                      s.language_code.c_str(), s.pid, s.teletext_page_number, s.teletext_magazine_number);
357                                                                                                 program.subtitleStreams.push_back(s);
358                                                                                                 issubtitle=1;
359                                                                                         default:
360                                                                                                 break;
361                                                                                         }
362                                                                                 }
363                                                                         }
364                                                                         break;
365                                                                 case DTS_DESCRIPTOR:
366                                                                         isaudio = 1;
367                                                                         audio.type = audioStream::atDTS;
368                                                                         break;
369                                                                 case 0x2B: // TS_PSI_DT_MPEG2_AAC
370                                                                         isaudio = 1;
371                                                                         audio.type = audioStream::atAAC; // MPEG2-AAC
372                                                                         break;
373                                                                 case 0x1C: // TS_PSI_DT_MPEG4_Audio
374                                                                 case AAC_DESCRIPTOR:
375                                                                         isaudio = 1;
376                                                                         audio.type = audioStream::atAACHE; // MPEG4-AAC
377                                                                         break;
378                                                                 case AC3_DESCRIPTOR:
379                                                                         isaudio = 1;
380                                                                         audio.type = audioStream::atAC3;
381                                                                         break;
382                                                                 case REGISTRATION_DESCRIPTOR: /* some services don't have a separate AC3 descriptor */
383                                                                 {
384                                                                         RegistrationDescriptor *d = (RegistrationDescriptor*)(*desc);
385                                                                         switch (d->getFormatIdentifier())
386                                                                         {
387                                                                         case 0x44545331 ... 0x44545333: // DTS1/DTS2/DTS3
388                                                                                 isaudio = 1;
389                                                                                 audio.type = audioStream::atDTS;
390                                                                                 break;
391                                                                         case 0x41432d33: // == 'AC-3'
392                                                                                 isaudio = 1;
393                                                                                 audio.type = audioStream::atAC3;
394                                                                                 break;
395                                                                         case 0x42535344: // == 'BSSD' (LPCM)
396                                                                                 isaudio = 1;
397                                                                                 audio.type = audioStream::atLPCM;
398                                                                                 break;
399                                                                         case 0x56432d31: // == 'VC-1'
400                                                                         {
401                                                                                 const AdditionalIdentificationInfoVector *vec = d->getAdditionalIdentificationInfo();
402                                                                                 if (vec->size() > 1 && (*vec)[1] == 0x01) // subdescriptor tag
403                                                                                 {
404                                                                                         if ((*vec)[2] >= 0x90) // profile_level
405                                                                                                 video.type = videoStream::vtVC1; // advanced profile
406                                                                                         else
407                                                                                                 video.type = videoStream::vtVC1_SM; // simple main
408                                                                                         isvideo = 1;
409                                                                                 }
410                                                                         }
411                                                                         default:
412                                                                                 break;
413                                                                         }
414                                                                         break;
415                                                                 }
416                                                                 case 0x28: // TS_PSI_DT_AVC
417                                                                         isvideo = 1;
418                                                                         video.type = videoStream::vtMPEG4_H264;
419                                                                         break;
420                                                                 case 0x1B: // TS_PSI_DT_MPEG4_Video
421                                                                         isvideo = 1;
422                                                                         video.type = videoStream::vtMPEG4_Part2;
423                                                                         break;
424                                                                 default:
425                                                                         break;
426                                                                 }
427                                                         }
428                                                         switch (tag)
429                                                         {
430                                                         case ISO_639_LANGUAGE_DESCRIPTOR:
431                                                                 if (!isvideo)
432                                                                 {
433                                                                         int cnt=0;
434                                                                         const Iso639LanguageList *languages = ((Iso639LanguageDescriptor*)*desc)->getIso639Languages();
435                                                                                 /* use last language code */
436                                                                         for (Iso639LanguageConstIterator i(languages->begin()); i != languages->end(); ++i, ++cnt)
437                                                                         {
438                                                                                 if (cnt == 0)
439                                                                                         audio.language_code = (*i)->getIso639LanguageCode();
440                                                                                 else
441                                                                                         audio.language_code += "/" + (*i)->getIso639LanguageCode();
442                                                                         }
443                                                                 }
444                                                                 break;
445                                                         case STREAM_IDENTIFIER_DESCRIPTOR:
446                                                                 audio.component_tag =
447                                                                         video.component_tag =
448                                                                                 ((StreamIdentifierDescriptor*)*desc)->getComponentTag();
449                                                                 break;
450                                                         case CA_DESCRIPTOR:
451                                                         {
452                                                                 CaDescriptor *descr = (CaDescriptor*)(*desc);
453                                                                 program.caids.insert(descr->getCaSystemId());
454                                                                 break;
455                                                         }
456                                                         default:
457                                                                 break;
458                                                         }
459                                                 }
460                                         default:
461                                                 break;
462                                         }
463                                         if (issubtitle && (isaudio || isvideo))
464                                                 eDebug("ambiguous streamtype for PID %04x detected.. forced as subtitle!", (*es)->getPid());
465                                         else if (isaudio && isvideo)
466                                                 eDebug("ambiguous streamtype for PID %04x detected.. forced as video!", (*es)->getPid());
467                                         if (issubtitle)
468                                                 continue;
469                                         else if (isvideo)
470                                         {
471                                                 video.pid = (*es)->getPid();
472                                                 if ( !program.videoStreams.empty() && video.pid == cached_vpid )
473                                                 {
474                                                         program.videoStreams.push_back(program.videoStreams[0]);
475                                                         program.videoStreams[0] = video;
476                                                 }
477                                                 else
478                                                         program.videoStreams.push_back(video);
479                                         }
480                                         else if (isaudio)
481                                         {
482                                                 audio.pid = (*es)->getPid();
483
484                                                         /* if we find the cached pids, this will be our default stream */
485                                                 if (audio.pid == cached_apid_ac3 || audio.pid == cached_apid_mpeg)
486                                                         program.defaultAudioStream = program.audioStreams.size();
487
488                                                         /* also, we need to know the first non-mpeg (i.e. "ac3"/dts/...) stream */
489                                                 if ((audio.type != audioStream::atMPEG) && ((first_ac3 == -1) || (audio.pid == cached_apid_ac3)))
490                                                         first_ac3 = program.audioStreams.size();
491
492                                                 program.audioStreams.push_back(audio);
493                                         }
494                                         else
495                                                 continue;
496                                 }
497                                 for (DescriptorConstIterator desc = pmt.getDescriptors()->begin();
498                                         desc != pmt.getDescriptors()->end(); ++desc)
499                                 {
500                                         if ((*desc)->getTag() == CA_DESCRIPTOR)
501                                         {
502                                                 CaDescriptor *descr = (CaDescriptor*)(*desc);
503                                                 program.caids.insert(descr->getCaSystemId());
504                                         }
505                                 }
506                         }
507                         ret = 0;
508
509                         /* finally some fixup: if our default audio stream is an MPEG audio stream, 
510                            and we have 'defaultac3' set, use the first available ac3 stream instead.
511                            (note: if an ac3 audio stream was selected before, this will be also stored
512                            in 'fisrt_ac3', so we don't need to worry. */
513                         bool defaultac3 = false;
514                         std::string default_ac3;
515
516                         if (!ePythonConfigQuery::getConfigValue("config.av.defaultac3", default_ac3))
517                                 defaultac3 = default_ac3 == "True";
518
519                         if (defaultac3 && (first_ac3 != -1))
520                                 program.defaultAudioStream = first_ac3;
521
522                         m_cached_program = program;
523                         m_have_cached_program = true;
524                 }
525         } else if ( m_service && !m_service->cacheEmpty() )
526         {
527                 int cached_pcrpid = m_service->getCacheEntry(eDVBService::cPCRPID),
528                         vpidtype = m_service->getCacheEntry(eDVBService::cVTYPE),
529                         cnt=0;
530                 if ( vpidtype == -1 )
531                         vpidtype = videoStream::vtMPEG2;
532                 if ( cached_vpid != -1 )
533                 {
534                         videoStream s;
535                         s.pid = cached_vpid;
536                         s.type = vpidtype;
537                         program.videoStreams.push_back(s);
538                         ++cnt;
539                 }
540                 if ( cached_apid_ac3 != -1 )
541                 {
542                         audioStream s;
543                         s.type = audioStream::atAC3;
544                         s.pid = cached_apid_ac3;
545                         program.audioStreams.push_back(s);
546                         ++cnt;
547                 }
548                 if ( cached_apid_mpeg != -1 )
549                 {
550                         audioStream s;
551                         s.type = audioStream::atMPEG;
552                         s.pid = cached_apid_mpeg;
553                         program.audioStreams.push_back(s);
554                         ++cnt;
555                 }
556                 if ( cached_pcrpid != -1 )
557                 {
558                         ++cnt;
559                         program.pcrPid = cached_pcrpid;
560                 }
561                 if ( cached_tpid != -1 )
562                 {
563                         ++cnt;
564                         program.textPid = cached_tpid;
565                 }
566                 CAID_LIST &caids = m_service->m_ca;
567                 for (CAID_LIST::iterator it(caids.begin()); it != caids.end(); ++it)
568                         program.caids.insert(*it);
569                 if ( cnt )
570                         ret = 0;
571         }
572         return ret;
573 }
574
575 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
576 {
577         channel = m_channel;
578         if (channel)
579                 return 0;
580         else
581                 return -1;
582 }
583
584 int eDVBServicePMTHandler::getDataDemux(ePtr<iDVBDemux> &demux)
585 {
586         demux = m_demux;
587         if (demux)
588                 return 0;
589         else
590                 return -1;
591 }
592
593 int eDVBServicePMTHandler::getDecodeDemux(ePtr<iDVBDemux> &demux)
594 {
595         int ret=0;
596                 /* if we're using the decoding demux as data source
597                    (for example in pvr playbacks), return that one. */
598         if (m_use_decode_demux)
599         {
600                 demux = m_demux;
601                 return ret;
602         }
603         
604         ASSERT(m_channel); /* calling without a previous ::tune is certainly bad. */
605
606         ret = m_channel->getDemux(demux, iDVBChannel::capDecode);
607         if (!ret)
608                 demux->getCADemuxID(m_decode_demux_num);
609
610         return ret;
611 }
612
613 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
614 {
615         pvr_channel = m_pvr_channel;
616         if (pvr_channel)
617                 return 0;
618         else
619                 return -1;
620 }
621
622 void eDVBServicePMTHandler::SDTScanEvent(int event)
623 {
624         switch (event)
625         {
626                 case eDVBScan::evtFinish:
627                 {
628                         ePtr<iDVBChannelList> db;
629                         if (m_resourceManager->getChannelList(db) != 0)
630                                 eDebug("no channel list");
631                         else
632                         {
633                                 eDVBChannelID chid;
634                                 m_reference.getChannelID(chid);
635                                 if (chid == m_dvb_scan->getCurrentChannelID())
636                                 {
637                                         m_dvb_scan->insertInto(db, true);
638                                         eDebug("sdt update done!");
639                                 }
640                                 else
641                                         eDebug("ignore sdt update data.... incorrect transponder tuned!!!");
642                         }
643                         break;
644                 }
645
646                 default:
647                         break;
648         }
649 }
650
651 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref, int use_decode_demux, eCueSheet *cue, bool simulate, eDVBService *service)
652 {
653         RESULT res=0;
654         m_reference = ref;
655         
656         m_use_decode_demux = use_decode_demux;
657
658                 /* 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 */
659         m_service = service;
660         
661                 /* is this a normal (non PVR) channel? */
662         if (ref.path.empty())
663         {
664                 eDVBChannelID chid;
665                 ref.getChannelID(chid);
666                 res = m_resourceManager->allocateChannel(chid, m_channel, simulate);
667                 if (!simulate)
668                         eDebug("allocate Channel: res %d", res);
669
670                 ePtr<iDVBChannelList> db;
671                 if (!m_resourceManager->getChannelList(db))
672                         db->getService((eServiceReferenceDVB&)m_reference, m_service);
673
674                 if (!res && !simulate)
675                         eDVBCIInterfaces::getInstance()->addPMTHandler(this);
676         } else if (!simulate) // no simulation of playback services
677         {
678                 eDVBMetaParser parser;
679
680                 int ret=parser.parseFile(ref.path);
681                 if (ret || !parser.m_ref.getServiceID().get() /* incorrect sid in meta file or recordings.epl*/ )
682                 {
683                         eWarning("no .meta file found, trying to find PMT pid");
684                         eDVBTSTools tstools;
685                         if (tstools.openFile(ref.path.c_str()))
686                                 eWarning("failed to open file");
687                         else
688                         {
689                                 int service_id, pmt_pid;
690                                 if (!tstools.findPMT(pmt_pid, service_id))
691                                 {
692                                         eDebug("PMT pid found on pid %04x, service id %d", pmt_pid, service_id);
693                                         m_reference.setServiceID(service_id);
694                                         m_pmt_pid = pmt_pid;
695                                 }
696                         }
697                 } else
698                         m_reference = parser.m_ref;
699                 
700                 eDebug("alloc PVR");
701                         /* allocate PVR */
702                 res = m_resourceManager->allocatePVRChannel(m_pvr_channel);
703                 if (res)
704                         eDebug("allocatePVRChannel failed!\n");
705                 m_channel = m_pvr_channel;
706         }
707
708         if (!simulate)
709         {
710                 if (m_channel)
711                 {
712                         m_channel->connectStateChange(
713                                 slot(*this, &eDVBServicePMTHandler::channelStateChanged), 
714                                 m_channelStateChanged_connection);
715                         m_last_channel_state = -1;
716                         channelStateChanged(m_channel);
717         
718                         m_channel->connectEvent(
719                                 slot(*this, &eDVBServicePMTHandler::channelEvent), 
720                                 m_channelEvent_connection);
721
722                         if (ref.path.empty())
723                         {
724                                 m_dvb_scan = 0;
725                                 m_dvb_scan = new eDVBScan(m_channel, true, false);
726                                 m_dvb_scan->connectEvent(slot(*this, &eDVBServicePMTHandler::SDTScanEvent), m_scan_event_connection);
727                         }
728                 } else
729                 {
730                         if (res == eDVBResourceManager::errAllSourcesBusy)
731                                 serviceEvent(eventNoResources);
732                         else /* errChidNotFound, errNoChannelList, errChannelNotInList, errNoSourceFound */
733                                 serviceEvent(eventMisconfiguration);
734                         return res;
735                 }
736
737                 if (m_pvr_channel)
738                 {
739                         m_pvr_channel->setCueSheet(cue);
740                         m_pvr_channel->playFile(ref.path.c_str());
741                 }
742         }
743
744         return res;
745 }
746
747 void eDVBServicePMTHandler::free()
748 {
749         m_dvb_scan = 0;
750
751         if (m_ca_servicePtr)
752         {
753                 int demuxes[2] = {0,0};
754                 uint8_t tmp;
755                 m_demux->getCADemuxID(tmp);
756                 demuxes[0]=tmp;
757                 if (m_decode_demux_num != 0xFF)
758                         demuxes[1]=m_decode_demux_num;
759                 else
760                         demuxes[1]=demuxes[0];
761                 ePtr<eTable<ProgramMapSection> > ptr;
762                 m_PMT.getCurrent(ptr);
763                 eDVBCAService::unregister_service(m_reference, demuxes, ptr);
764                 m_ca_servicePtr = 0;
765         }
766
767         if (m_channel)
768                 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
769
770         if (m_pvr_channel)
771         {
772                 m_pvr_channel->stopFile();
773                 m_pvr_channel->setCueSheet(0);
774         }
775
776         m_PMT.stop();
777         m_PAT.stop();
778         m_service = 0;
779         m_channel = 0;
780         m_pvr_channel = 0;
781         m_demux = 0;
782 }
783
784 CAServiceMap eDVBCAService::exist;
785 ChannelMap eDVBCAService::exist_channels;
786 ePtr<eConnection> eDVBCAService::m_chanAddedConn;
787
788 eDVBCAService::eDVBCAService()
789         :m_buffer(512), m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eTimer::create(eApp))
790 {
791         memset(m_used_demux, 0xFF, sizeof(m_used_demux));
792         CONNECT(m_retryTimer->timeout, eDVBCAService::sendCAPMT);
793         Connect();
794 }
795
796 eDVBCAService::~eDVBCAService()
797 {
798         eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
799         ::close(m_sock);
800 }
801
802 // begin static methods
803 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_nums[2], eDVBCAService *&caservice )
804 {
805         CAServiceMap::iterator it = exist.find(ref);
806         if ( it != exist.end() )
807                 caservice = it->second;
808         else
809         {
810                 caservice = (exist[ref]=new eDVBCAService());
811                 caservice->m_service = ref;
812                 eDebug("[eDVBCAService] new service %s", ref.toString().c_str() );
813         }
814
815         int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
816         for (int i=0; i < loops; ++i)
817         {
818 // search free demux entry
819                 int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
820
821                 while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
822                         ++iter;
823
824                 if ( iter < max_demux_slots )
825                 {
826                         caservice->m_used_demux[iter] = demux_nums[i] & 0xFF;
827                         eDebug("[eDVBCAService] add demux %d to slot %d service %s", caservice->m_used_demux[iter], iter, ref.toString().c_str());
828                 }
829                 else
830                 {
831                         eDebug("[eDVBCAService] no more demux slots free for service %s!!", ref.toString().c_str());
832                         return -1;
833                 }
834         }
835         return 0;
836 }
837
838 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_nums[2], eTable<ProgramMapSection> *ptr )
839 {
840         CAServiceMap::iterator it = exist.find(ref);
841         if ( it == exist.end() )
842         {
843                 eDebug("[eDVBCAService] try to unregister non registered %s", ref.toString().c_str());
844                 return -1;
845         }
846         else
847         {
848                 eDVBCAService *caservice = it->second;
849                 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
850                 for (int i=0; i < loops; ++i)
851                 {
852                         bool freed = false;
853                         int iter = 0,
854                                 used_demux_slots = 0,
855                                 max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
856                         while ( iter < max_demux_slots )
857                         {
858                                 if ( caservice->m_used_demux[iter] != 0xFF )
859                                 {
860                                         if ( !freed && caservice->m_used_demux[iter] == demux_nums[i] )
861                                         {
862                                                 eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
863                                                 caservice->m_used_demux[iter] = 0xFF;
864                                                 freed=true;
865                                         }
866                                         else
867                                                 ++used_demux_slots;
868                                 }
869                                 ++iter;
870                         }
871                         if (!freed)
872                                 eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_nums[i]);
873                         if (i || loops == 1)
874                         {
875                                 if (!used_demux_slots)  // no more used.. so we remove it
876                                 {
877                                         delete it->second;
878                                         exist.erase(it);
879                                 }
880                                 else
881                                 {
882                                         if (ptr)
883                                                 it->second->buildCAPMT(ptr);
884                                         else
885                                                 eDebug("[eDVBCAService] can not send updated demux info");
886                                 }
887                         }
888                 }
889         }
890         return 0;
891 }
892
893 void eDVBCAService::registerChannelCallback(eDVBResourceManager *res_mgr)
894 {
895         res_mgr->connectChannelAdded(slot(&DVBChannelAdded), m_chanAddedConn);
896 }
897
898 void eDVBCAService::DVBChannelAdded(eDVBChannel *chan)
899 {
900         if ( chan )
901         {
902                 eDebug("[eDVBCAService] new channel %p!", chan);
903                 channel_data *data = new channel_data();
904                 data->m_channel = chan;
905                 data->m_prevChannelState = -1;
906                 data->m_dataDemux = -1;
907                 exist_channels[chan] = data;
908                 chan->connectStateChange(slot(&DVBChannelStateChanged), data->m_stateChangedConn);
909         }
910 }
911
912 void eDVBCAService::DVBChannelStateChanged(iDVBChannel *chan)
913 {
914         ChannelMap::iterator it =
915                 exist_channels.find(chan);
916         if ( it != exist_channels.end() )
917         {
918                 int state=0;
919                 chan->getState(state);
920                 if ( it->second->m_prevChannelState != state )
921                 {
922                         switch (state)
923                         {
924                                 case iDVBChannel::state_ok:
925                                 {
926                                         eDebug("[eDVBCAService] channel %p running", chan);
927                                         break;
928                                 }
929                                 case iDVBChannel::state_release:
930                                 {
931                                         eDebug("[eDVBCAService] remove channel %p", chan);
932                                         unsigned char msg[8] = { 0x9f,0x80,0x3f,0x04,0x83,0x02,0x00,0x00 };
933                                         msg[7] = it->second->m_dataDemux & 0xFF;
934                                         int sock, clilen;
935                                         struct sockaddr_un servaddr;
936                                         memset(&servaddr, 0, sizeof(struct sockaddr_un));
937                                         servaddr.sun_family = AF_UNIX;
938                                         strcpy(servaddr.sun_path, "/tmp/camd.socket");
939                                         clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
940                                         sock = socket(PF_UNIX, SOCK_STREAM, 0);
941                                         if (sock > -1)
942                                         {
943                                                 connect(sock, (struct sockaddr *) &servaddr, clilen);
944                                                 fcntl(sock, F_SETFL, O_NONBLOCK);
945                                                 int val=1;
946                                                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
947                                                 if (write(sock, msg, 8) != 8)
948                                                         eDebug("[eDVBCAService] write leave transponder failed!!");
949                                                 close(sock);
950                                         }
951                                         exist_channels.erase(it);
952                                         delete it->second;
953                                         it->second=0;
954                                         break;
955                                 }
956                                 default: // ignore all other events
957                                         return;
958                         }
959                         if (it->second)
960                                 it->second->m_prevChannelState = state;
961                 }
962         }
963 }
964
965 channel_data *eDVBCAService::getChannelData(eDVBChannelID &chid)
966 {
967         for (ChannelMap::iterator it(exist_channels.begin()); it != exist_channels.end(); ++it)
968         {
969                 if (chid == it->second->m_channel->getChannelID())
970                         return it->second;
971         }
972         return 0;
973 }
974 // end static methods
975
976 #define CA_REPLY_DEBUG
977 #define MAX_LENGTH_BYTES 4
978 #define MIN_LENGTH_BYTES 1
979
980 void eDVBCAService::socketCB(int what)
981 {
982         if (what & (eSocketNotifier::Read | eSocketNotifier::Priority))
983         {
984                 char msgbuffer[4096];
985                 ssize_t length = read(m_sock, msgbuffer, sizeof(msgbuffer));
986                 if (length == -1)
987                 {
988                         if (errno != EAGAIN && errno != EINTR && errno != EBUSY)
989                         {
990                                 eDebug("[eSocketMMIHandler] read (%m)");
991                                 what |= eSocketNotifier::Error;
992                         }
993                 } else if (length == 0)
994                 {
995                         what |= eSocketNotifier::Hungup;
996                 } else
997                 {
998                         int len = length;
999                         unsigned char *data = (unsigned char*)msgbuffer;
1000                         int clear = 1;
1001         // If a new message starts, then the previous message
1002         // should already have been processed. Otherwise the
1003         // previous message was incomplete and should therefore
1004         // be deleted.
1005                         if ((len >= 1) && ((data[0] & 0xFF) != 0x9f))
1006                                 clear = 0;
1007                         if ((len >= 2) && ((data[1] & 0x80) != 0x80))
1008                                 clear = 0;
1009                         if ((len >= 3) && ((data[2] & 0x80) != 0x00))
1010                                 clear = 0;
1011                         if (clear)
1012                         {
1013                                 m_buffer.clear();
1014 #ifdef CA_REPLY_DEBUG
1015                                 eDebug("clear buffer");
1016 #endif
1017                         }
1018 #ifdef CA_REPLY_DEBUG
1019                         eDebug("Put to buffer:");
1020                         for (int i=0; i < len; ++i)
1021                                 eDebugNoNewLine("%02x ", data[i]);
1022                         eDebug("\n--------");
1023 #endif
1024                         m_buffer.write( data, len );
1025
1026                         while ( m_buffer.size() >= (3 + MIN_LENGTH_BYTES) )
1027                         {
1028                                 unsigned char tmp[3+MAX_LENGTH_BYTES];
1029                                 m_buffer.peek(tmp, 3+MIN_LENGTH_BYTES);
1030                                 if (((tmp[0] & 0xFF) != 0x9f) || ((tmp[1] & 0x80) != 0x80) || ((tmp[2] & 0x80) != 0x00))
1031                                 {
1032                                         m_buffer.skip(1);
1033 #ifdef CA_REPLY_DEBUG
1034                                         eDebug("skip %02x", tmp[0]);
1035 #endif
1036                                         continue;
1037                                 }
1038                                 if (tmp[3] & 0x80)
1039                                 {
1040                                         int peekLength = (tmp[3] & 0x7f) + 4;
1041                                         if (m_buffer.size() < peekLength)
1042                                                 continue;
1043                                         m_buffer.peek(tmp, peekLength);
1044                                 }
1045                                 int size=0;
1046                                 int LengthBytes=eDVBCISession::parseLengthField(tmp+3, size);
1047                                 int messageLength = 3+LengthBytes+size;
1048                                 if ( m_buffer.size() >= messageLength )
1049                                 {
1050                                         unsigned char dest[messageLength];
1051                                         m_buffer.read(dest, messageLength);
1052 #ifdef CA_REPLY_DEBUG
1053                                         eDebug("dump ca reply:");
1054                                         for (int i=0; i < messageLength; ++i)
1055                                                 eDebugNoNewLine("%02x ", dest[i]);
1056                                         eDebug("\n--------");
1057 #endif
1058 //                                      /*emit*/ mmi_progress(0, dest, (const void*)(dest+3+LengthBytes), messageLength-3-LengthBytes);
1059                                 }
1060                         }
1061                 }
1062         }
1063         if (what & eSocketNotifier::Hungup) {
1064                 /*eDebug("[eDVBCAService] connection closed")*/;
1065                 m_sendstate=1;
1066                 sendCAPMT();
1067         }
1068         if (what & eSocketNotifier::Error)
1069                 eDebug("[eDVBCAService] connection error");
1070 }
1071
1072 void eDVBCAService::Connect()
1073 {
1074         m_sn=0;
1075         memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
1076         m_servaddr.sun_family = AF_UNIX;
1077         strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
1078         m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
1079         m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
1080         if (m_sock != -1)
1081         {
1082                 if (!connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen))
1083                 {
1084                         int val=1;
1085                         fcntl(m_sock, F_SETFL, O_NONBLOCK);
1086                         setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
1087                         m_sn = eSocketNotifier::create(eApp, m_sock,
1088                                 eSocketNotifier::Read|eSocketNotifier::Priority|eSocketNotifier::Error|eSocketNotifier::Hungup);
1089                         CONNECT(m_sn->activated, eDVBCAService::socketCB);
1090                         
1091                 }
1092 //              else
1093 //                      eDebug("[eDVBCAService] connect failed %m");
1094         }
1095         else
1096                 eDebug("[eDVBCAService] create socket failed %m");
1097 }
1098
1099 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
1100 {
1101         if (!ptr)
1102                 return;
1103
1104         eDVBTableSpec table_spec;
1105         ptr->getSpec(table_spec);
1106
1107         int pmtpid = table_spec.pid,
1108                 pmt_version = table_spec.version;
1109
1110         uint8_t demux_mask = 0;
1111         int data_demux = -1;
1112
1113         int iter=0, max_demux_slots = sizeof(m_used_demux);
1114         while ( iter < max_demux_slots )
1115         {
1116                 if ( m_used_demux[iter] != 0xFF )
1117                 {
1118                         if ( m_used_demux[iter] > data_demux )
1119                                 data_demux = m_used_demux[iter];
1120                         demux_mask |= (1 << m_used_demux[iter]);
1121                 }
1122                 ++iter;
1123         }
1124
1125         if ( data_demux == -1 )
1126         {
1127                 eDebug("[eDVBCAService] no data demux found for service %s", m_service.toString().c_str() );
1128                 return;
1129         }
1130
1131         eDebug("demux %d mask %02x prevhash %08x", data_demux, demux_mask, m_prev_build_hash);
1132
1133         unsigned int build_hash = ( pmtpid << 16);
1134         build_hash |= (demux_mask << 8);
1135         build_hash |= (pmt_version&0xFF);
1136
1137         if ( build_hash == m_prev_build_hash )
1138         {
1139                 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
1140                 return;
1141         }
1142
1143         std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
1144         if ( i != ptr->getSections().end() )
1145         {
1146                 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
1147
1148                 while( i != ptr->getSections().end() )
1149                 {
1150 //                      eDebug("append");
1151                         capmt.append(*i++);
1152                 }
1153
1154                 // add our private descriptors to capmt
1155                 uint8_t tmp[10];
1156
1157                 tmp[0]=0x84;  // pmt pid
1158                 tmp[1]=0x02;
1159                 tmp[2]=pmtpid>>8;
1160                 tmp[3]=pmtpid&0xFF;
1161                 capmt.injectDescriptor(tmp, false);
1162
1163                 tmp[0] = 0x82; // demux
1164                 tmp[1] = 0x02;
1165                 tmp[2] = demux_mask;    // descramble bitmask
1166                 tmp[3] = data_demux&0xFF; // read section data from demux number
1167                 capmt.injectDescriptor(tmp, false);
1168
1169                 tmp[0] = 0x81; // dvbnamespace
1170                 tmp[1] = 0x08;
1171                 tmp[2] = m_service.getDVBNamespace().get()>>24;
1172                 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
1173                 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
1174                 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
1175                 tmp[6]=m_service.getTransportStreamID().get()>>8;
1176                 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
1177                 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
1178                 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
1179                 capmt.injectDescriptor(tmp, false);
1180
1181                 capmt.writeToBuffer(m_capmt);
1182         }
1183
1184         m_prev_build_hash = build_hash;
1185
1186         if ( m_sendstate != 0xFFFFFFFF )
1187                 m_sendstate=0;
1188         sendCAPMT();
1189 }
1190
1191 void eDVBCAService::sendCAPMT()
1192 {
1193         if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
1194         {
1195                 ::close(m_sock);
1196                 Connect();
1197         }
1198
1199         int wp=0;
1200         if ( m_capmt[3] & 0x80 )
1201         {
1202                 int i=0;
1203                 int lenbytes = m_capmt[3] & ~0x80;
1204                 while(i < lenbytes)
1205                         wp = (wp << 8) | m_capmt[4 + i++];
1206                 wp+=4;
1207                 wp+=lenbytes;
1208         }
1209         else
1210         {
1211                 wp = m_capmt[3];
1212                 wp+=4;
1213         }
1214
1215         if ( write(m_sock, m_capmt, wp) == wp )
1216         {
1217                 m_sendstate=0xFFFFFFFF;
1218                 eDebug("[eDVBCAService] send %d bytes",wp);
1219                 eDVBChannelID chid;
1220                 m_service.getChannelID(chid);
1221                 channel_data *data = getChannelData(chid);
1222                 if (data)
1223                 {
1224                         int lenbytes = m_capmt[3] & 0x80 ? m_capmt[3] & ~0x80 : 0;
1225                         data->m_dataDemux = m_capmt[24+lenbytes];
1226                 }
1227 #if 1
1228                 for(int i=0;i<wp;i++)
1229                         eDebugNoNewLine("%02x ", m_capmt[i]);
1230                 eDebug("");
1231 #endif
1232         }
1233         else
1234         {
1235                 switch(m_sendstate)
1236                 {
1237                         case 0xFFFFFFFF:
1238                                 ++m_sendstate;
1239                                 m_retryTimer->start(0,true);
1240 //                              eDebug("[eDVBCAService] send failed .. immediate retry");
1241                                 break;
1242                         default:
1243                                 m_retryTimer->start(5000,true);
1244 //                              eDebug("[eDVBCAService] send failed .. retry in 5 sec");
1245                                 break;
1246                 }
1247                 ++m_sendstate;
1248         }
1249 }
1250
1251 static PyObject *createTuple(int pid, const char *type)
1252 {
1253         PyObject *r = PyTuple_New(2);
1254         PyTuple_SET_ITEM(r, 0, PyInt_FromLong(pid));
1255         PyTuple_SET_ITEM(r, 1, PyString_FromString(type));
1256         return r;
1257 }
1258
1259 static inline void PyList_AppendSteal(PyObject *list, PyObject *item)
1260 {
1261         PyList_Append(list, item);
1262         Py_DECREF(item);
1263 }
1264
1265 extern void PutToDict(ePyObject &dict, const char*key, ePyObject item); // defined in dvb/frontend.cpp
1266
1267 PyObject *eDVBServicePMTHandler::program::createPythonObject()
1268 {
1269         ePyObject r = PyDict_New();
1270         ePyObject l = PyList_New(0);
1271
1272         PyList_AppendSteal(l, createTuple(0, "pat"));
1273
1274         if (pmtPid != -1)
1275                 PyList_AppendSteal(l, createTuple(pmtPid, "pmt"));
1276
1277         for (std::vector<eDVBServicePMTHandler::videoStream>::const_iterator
1278                         i(videoStreams.begin()); 
1279                         i != videoStreams.end(); ++i)
1280                 PyList_AppendSteal(l, createTuple(i->pid, "video"));
1281
1282         for (std::vector<eDVBServicePMTHandler::audioStream>::const_iterator
1283                         i(audioStreams.begin()); 
1284                         i != audioStreams.end(); ++i)
1285                 PyList_AppendSteal(l, createTuple(i->pid, "audio"));
1286
1287         for (std::vector<eDVBServicePMTHandler::subtitleStream>::const_iterator
1288                         i(subtitleStreams.begin());
1289                         i != subtitleStreams.end(); ++i)
1290                 PyList_AppendSteal(l, createTuple(i->pid, "subtitle"));
1291
1292         PyList_AppendSteal(l, createTuple(pcrPid, "pcr"));
1293
1294         if (textPid != -1)
1295                 PyList_AppendSteal(l, createTuple(textPid, "text"));
1296
1297         PutToDict(r, "pids", l);
1298
1299         return r;
1300 }