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