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