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