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