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