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