1 #include <lib/base/nconfig.h> // access to python config
2 #include <lib/base/eerror.h>
3 #include <lib/dvb/pmt.h>
4 #include <lib/dvb/specs.h>
5 #include <lib/dvb/dvb.h>
6 #include <lib/dvb/metaparser.h>
7 #include <lib/dvb_ci/dvbci.h>
8 #include <lib/dvb/epgcache.h>
9 #include <lib/dvb/scan.h>
10 #include <lib/dvb_ci/dvbci_session.h>
11 #include <dvbsi++/ca_descriptor.h>
12 #include <dvbsi++/ca_program_map_section.h>
13 #include <dvbsi++/teletext_descriptor.h>
14 #include <dvbsi++/descriptor_tag.h>
15 #include <dvbsi++/iso639_language_descriptor.h>
16 #include <dvbsi++/stream_identifier_descriptor.h>
17 #include <dvbsi++/subtitling_descriptor.h>
18 #include <dvbsi++/teletext_descriptor.h>
19 #include <dvbsi++/video_stream_descriptor.h>
20 #include <dvbsi++/registration_descriptor.h>
22 eDVBServicePMTHandler::eDVBServicePMTHandler()
23 :m_ca_servicePtr(0), m_dvb_scan(0), m_decode_demux_num(0xFF)
25 m_use_decode_demux = 0;
27 eDVBResourceManager::getInstance(m_resourceManager);
28 CONNECT(m_PMT.tableReady, eDVBServicePMTHandler::PMTready);
29 CONNECT(m_PAT.tableReady, eDVBServicePMTHandler::PATready);
32 eDVBServicePMTHandler::~eDVBServicePMTHandler()
37 void eDVBServicePMTHandler::channelStateChanged(iDVBChannel *channel)
40 channel->getState(state);
42 if ((m_last_channel_state != iDVBChannel::state_ok)
43 && (state == iDVBChannel::state_ok) && (!m_demux))
46 if (m_channel->getDemux(m_demux, (!m_use_decode_demux) ? 0 : iDVBChannel::capDecode))
47 eDebug("Allocating %s-decoding a demux for now tuned-in channel failed.", m_use_decode_demux ? "" : "non-");
49 serviceEvent(eventTuned);
53 eDebug("ok ... now we start!!");
55 if (!m_service || m_service->usePMT())
58 m_PAT.begin(eApp, eDVBPATSpec(), m_demux);
60 m_PMT.begin(eApp, eDVBPMTSpec(m_pmt_pid, m_reference.getServiceID().get()), m_demux);
63 if ( m_service && !m_service->cacheEmpty() )
64 serviceEvent(eventNewProgramInfo);
66 } else if ((m_last_channel_state != iDVBChannel::state_failed) &&
67 (state == iDVBChannel::state_failed))
69 eDebug("tune failed.");
70 serviceEvent(eventTuneFailed);
74 void eDVBServicePMTHandler::channelEvent(iDVBChannel *channel, int event)
78 case iDVBChannel::evtPreStart:
79 serviceEvent(eventPreStart);
81 case iDVBChannel::evtEOF:
82 serviceEvent(eventEOF);
84 case iDVBChannel::evtSOF:
85 serviceEvent(eventSOF);
92 void eDVBServicePMTHandler::PMTready(int error)
95 serviceEvent(eventNoPMT);
98 m_have_cached_program = false;
99 serviceEvent(eventNewProgramInfo);
100 if (!m_pvr_channel) // don't send campmt to camd.socket for playbacked services
102 eEPGCache::getInstance()->PMTready(this);
105 int demuxes[2] = {0,0};
107 m_demux->getCADemuxID(tmp);
109 if (m_decode_demux_num != 0xFF)
110 demuxes[1]=m_decode_demux_num;
112 demuxes[1]=demuxes[0];
113 eDVBCAService::register_service(m_reference, demuxes, m_ca_servicePtr);
114 eDVBCIInterfaces::getInstance()->recheckPMTHandlers();
116 eDVBCIInterfaces::getInstance()->gotPMT(this);
120 ePtr<eTable<ProgramMapSection> > ptr;
121 if (!m_PMT.getCurrent(ptr))
122 m_ca_servicePtr->buildCAPMT(ptr);
124 eDebug("eDVBServicePMTHandler cannot call buildCAPMT");
129 void eDVBServicePMTHandler::PATready(int)
131 ePtr<eTable<ProgramAssociationSection> > ptr;
132 if (!m_PAT.getCurrent(ptr))
135 std::vector<ProgramAssociationSection*>::const_iterator i;
136 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
138 const ProgramAssociationSection &pat = **i;
139 ProgramAssociationConstIterator program;
140 for (program = pat.getPrograms()->begin(); program != pat.getPrograms()->end(); ++program)
141 if (eServiceID((*program)->getProgramNumber()) == m_reference.getServiceID())
142 pmtpid = (*program)->getProgramMapPid();
145 serviceEvent(eventNoPATEntry);
147 m_PMT.begin(eApp, eDVBPMTSpec(pmtpid, m_reference.getServiceID().get()), m_demux);
149 serviceEvent(eventNoPAT);
152 PyObject *eDVBServicePMTHandler::getCaIds()
158 if ( !getProgramInfo(prog) )
160 int cnt=prog.caids.size();
164 std::set<uint16_t>::iterator it(prog.caids.begin());
166 PyList_SET_ITEM(ret, cnt, PyInt_FromLong(*it++));
170 return ret ? (PyObject*)ret : (PyObject*)PyList_New(0);
173 int eDVBServicePMTHandler::getProgramInfo(struct program &program)
175 ePtr<eTable<ProgramMapSection> > ptr;
176 int cached_apid_ac3 = -1;
177 int cached_apid_mpeg = -1;
178 int cached_vpid = -1;
179 int cached_tpid = -1;
182 program.videoStreams.clear();
183 program.audioStreams.clear();
186 program.textPid = -1;
189 program.defaultAudioStream = 0;
190 audioStream *prev_audio = 0;
192 if ( m_service && !m_service->cacheEmpty() )
194 cached_vpid = m_service->getCacheEntry(eDVBService::cVPID);
195 cached_apid_mpeg = m_service->getCacheEntry(eDVBService::cAPID);
196 cached_apid_ac3 = m_service->getCacheEntry(eDVBService::cAC3PID);
197 cached_tpid = m_service->getCacheEntry(eDVBService::cTPID);
200 if ( ((m_service && m_service->usePMT()) || !m_service) && !m_PMT.getCurrent(ptr))
202 if (m_have_cached_program)
204 program = m_cached_program;
209 eDVBTableSpec table_spec;
210 ptr->getSpec(table_spec);
211 program.pmtPid = table_spec.pid < 0x1fff ? table_spec.pid : -1;
212 std::vector<ProgramMapSection*>::const_iterator i;
213 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
215 const ProgramMapSection &pmt = **i;
216 program.pcrPid = pmt.getPcrPid();
218 ElementaryStreamInfoConstIterator es;
219 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
221 int isaudio = 0, isvideo = 0, issubtitle = 0, forced_video = 0, forced_audio = 0, isteletext = 0;
222 int streamtype = (*es)->getType();
225 audio.component_tag=video.component_tag=-1;
226 video.type = videoStream::vtMPEG2;
227 audio.type = audioStream::atMPEG;
232 case 0x1b: // AVC Video Stream (MPEG4 H264)
233 video.type = videoStream::vtMPEG4_H264;
235 //break; fall through !!!
236 case 0x10: // MPEG 4 Part 2
239 video.type = videoStream::vtMPEG4_Part2;
242 //break; fall through !!!
243 case 0x01: // MPEG 1 video
245 video.type = videoStream::vtMPEG1;
246 //break; fall through !!!
247 case 0x02: // MPEG 2 video
250 //break; fall through !!!
251 case 0x03: // MPEG 1 audio
252 case 0x04: // MPEG 2 audio:
257 //break; fall through !!!
258 case 0x0f: // MPEG 2 AAC
259 if (!isvideo && !isaudio)
262 audio.type = audioStream::atAAC;
265 //break; fall through !!!
266 case 0x11: // MPEG 4 AAC
267 if (!isvideo && !isaudio)
270 audio.type = audioStream::atAACHE;
273 case 0x80: // user private ... but blueray LPCM
274 if (!isvideo && !isaudio)
277 audio.type = audioStream::atLPCM;
279 case 0x81: // user private ... but blueray AC3
280 if (!isvideo && !isaudio)
283 audio.type = audioStream::atAC3;
285 case 0x82: // Blueray DTS (dvb user private...)
286 case 0xA2: // Blueray secondary DTS
287 if (!isvideo && !isaudio)
290 audio.type = audioStream::atDTS;
292 case 0x06: // PES Private
293 case 0xEA: // TS_PSI_ST_SMPTE_VC1
295 int num_descriptors = 0;
296 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
297 desc != (*es)->getDescriptors()->end(); ++desc)
299 uint8_t tag = (*desc)->getTag();
300 /* check descriptors to get the exakt stream type. */
302 if (!forced_video && !forced_audio)
306 case AUDIO_STREAM_DESCRIPTOR:
309 case VIDEO_STREAM_DESCRIPTOR:
312 VideoStreamDescriptor *d = (VideoStreamDescriptor*)(*desc);
313 if (d->getMpeg1OnlyFlag())
314 video.type = videoStream::vtMPEG1;
317 case SUBTITLING_DESCRIPTOR:
319 SubtitlingDescriptor *d = (SubtitlingDescriptor*)(*desc);
320 const SubtitlingList *list = d->getSubtitlings();
322 s.pid = (*es)->getPid();
323 for (SubtitlingConstIterator it(list->begin()); it != list->end(); ++it)
325 s.subtitling_type = (*it)->getSubtitlingType();
326 switch(s.subtitling_type)
329 case 0x20 ... 0x23: // dvb subtitles
332 eDebug("dvb subtitle %s PID %04x with wrong subtitling type (%02x)... force 0x10!!",
333 s.language_code.c_str(), s.pid, s.subtitling_type);
334 s.subtitling_type = 0x10;
337 s.composition_page_id = (*it)->getCompositionPageId();
338 s.ancillary_page_id = (*it)->getAncillaryPageId();
339 s.language_code = (*it)->getIso639LanguageCode();
340 // eDebug("add dvb subtitle %s PID %04x, type %d, composition page %d, ancillary_page %d",
341 // s.language_code.c_str(), s.pid, s.subtitling_type, s.composition_page_id, s.ancillary_page_id);
343 program.subtitleStreams.push_back(s);
347 case TELETEXT_DESCRIPTOR:
348 if ( program.textPid == -1 || (*es)->getPid() == cached_tpid )
351 s.subtitling_type = 0x01; // EBU TELETEXT SUBTITLES
352 s.pid = program.textPid = (*es)->getPid();
353 TeletextDescriptor *d = (TeletextDescriptor*)(*desc);
355 const VbiTeletextList *list = d->getVbiTeletexts();
356 for (VbiTeletextConstIterator it(list->begin()); it != list->end(); ++it)
358 switch((*it)->getTeletextType())
360 case 0x02: // Teletext subtitle page
361 case 0x05: // Teletext subtitle page for hearing impaired pepople
362 s.language_code = (*it)->getIso639LanguageCode();
363 s.teletext_page_number = (*it)->getTeletextPageNumber();
364 s.teletext_magazine_number = (*it)->getTeletextMagazineNumber();
365 // eDebug("add teletext subtitle %s PID %04x, page number %d, magazine number %d",
366 // s.language_code.c_str(), s.pid, s.teletext_page_number, s.teletext_magazine_number);
367 program.subtitleStreams.push_back(s);
377 audio.type = audioStream::atDTS;
379 case 0x2B: // TS_PSI_DT_MPEG2_AAC
381 audio.type = audioStream::atAAC; // MPEG2-AAC
383 case 0x1C: // TS_PSI_DT_MPEG4_Audio
386 audio.type = audioStream::atAACHE; // MPEG4-AAC
390 audio.type = audioStream::atAC3;
392 case REGISTRATION_DESCRIPTOR: /* some services don't have a separate AC3 descriptor */
394 RegistrationDescriptor *d = (RegistrationDescriptor*)(*desc);
395 switch (d->getFormatIdentifier())
397 case 0x44545331 ... 0x44545333: // DTS1/DTS2/DTS3
399 audio.type = audioStream::atDTS;
401 case 0x41432d33: // == 'AC-3'
403 audio.type = audioStream::atAC3;
405 case 0x42535344: // == 'BSSD' (LPCM)
407 audio.type = audioStream::atLPCM;
409 case 0x56432d31: // == 'VC-1'
411 const AdditionalIdentificationInfoVector *vec = d->getAdditionalIdentificationInfo();
412 if (vec->size() > 1 && (*vec)[0] == 0x01) // subdescriptor tag
414 if ((*vec)[1] >= 0x90) // profile_level
415 video.type = videoStream::vtVC1; // advanced profile
417 video.type = videoStream::vtVC1_SM; // simple main
426 case 0x28: // TS_PSI_DT_AVC
428 video.type = videoStream::vtMPEG4_H264;
430 case 0x1B: // TS_PSI_DT_MPEG4_Video
432 video.type = videoStream::vtMPEG4_Part2;
440 case ISO_639_LANGUAGE_DESCRIPTOR:
444 const Iso639LanguageList *languages = ((Iso639LanguageDescriptor*)*desc)->getIso639Languages();
445 /* use last language code */
446 for (Iso639LanguageConstIterator i(languages->begin()); i != languages->end(); ++i, ++cnt)
449 audio.language_code = (*i)->getIso639LanguageCode();
451 audio.language_code += "/" + (*i)->getIso639LanguageCode();
455 case STREAM_IDENTIFIER_DESCRIPTOR:
456 audio.component_tag =
457 video.component_tag =
458 ((StreamIdentifierDescriptor*)*desc)->getComponentTag();
462 CaDescriptor *descr = (CaDescriptor*)(*desc);
463 program.caids.insert(descr->getCaSystemId());
470 if (!num_descriptors && streamtype == 0x06 && prev_audio)
472 prev_audio->rdsPid = (*es)->getPid();
473 eDebug("Rds PID %04x detected ? ! ?", prev_audio->rdsPid);
480 if (isteletext && (isaudio || isvideo))
482 eDebug("ambiguous streamtype for PID %04x detected.. forced as teletext!", (*es)->getPid());
483 continue; // continue with next PID
485 else if (issubtitle && (isaudio || isvideo))
486 eDebug("ambiguous streamtype for PID %04x detected.. forced as subtitle!", (*es)->getPid());
487 else if (isaudio && isvideo)
488 eDebug("ambiguous streamtype for PID %04x detected.. forced as video!", (*es)->getPid());
489 if (issubtitle) // continue with next PID
493 video.pid = (*es)->getPid();
494 if ( !program.videoStreams.empty() && video.pid == cached_vpid )
496 program.videoStreams.push_back(program.videoStreams[0]);
497 program.videoStreams[0] = video;
500 program.videoStreams.push_back(video);
504 audio.pid = (*es)->getPid();
506 /* if we find the cached pids, this will be our default stream */
507 if (audio.pid == cached_apid_ac3 || audio.pid == cached_apid_mpeg)
508 program.defaultAudioStream = program.audioStreams.size();
510 /* also, we need to know the first non-mpeg (i.e. "ac3"/dts/...) stream */
511 if ((audio.type != audioStream::atMPEG) && ((first_ac3 == -1) || (audio.pid == cached_apid_ac3)))
512 first_ac3 = program.audioStreams.size();
514 program.audioStreams.push_back(audio);
515 prev_audio = &program.audioStreams.back();
520 for (DescriptorConstIterator desc = pmt.getDescriptors()->begin();
521 desc != pmt.getDescriptors()->end(); ++desc)
523 if ((*desc)->getTag() == CA_DESCRIPTOR)
525 CaDescriptor *descr = (CaDescriptor*)(*desc);
526 program.caids.insert(descr->getCaSystemId());
532 /* finally some fixup: if our default audio stream is an MPEG audio stream,
533 and we have 'defaultac3' set, use the first available ac3 stream instead.
534 (note: if an ac3 audio stream was selected before, this will be also stored
535 in 'fisrt_ac3', so we don't need to worry. */
536 bool defaultac3 = false;
537 std::string default_ac3;
539 if (!ePythonConfigQuery::getConfigValue("config.av.defaultac3", default_ac3))
540 defaultac3 = default_ac3 == "True";
542 if (defaultac3 && (first_ac3 != -1))
543 program.defaultAudioStream = first_ac3;
545 m_cached_program = program;
546 m_have_cached_program = true;
548 } else if ( m_service && !m_service->cacheEmpty() )
550 int cached_pcrpid = m_service->getCacheEntry(eDVBService::cPCRPID),
551 vpidtype = m_service->getCacheEntry(eDVBService::cVTYPE),
553 if ( vpidtype == -1 )
554 vpidtype = videoStream::vtMPEG2;
555 if ( cached_vpid != -1 )
560 program.videoStreams.push_back(s);
563 if ( cached_apid_ac3 != -1 )
566 s.type = audioStream::atAC3;
567 s.pid = cached_apid_ac3;
569 program.audioStreams.push_back(s);
572 if ( cached_apid_mpeg != -1 )
575 s.type = audioStream::atMPEG;
576 s.pid = cached_apid_mpeg;
578 program.audioStreams.push_back(s);
581 if ( cached_pcrpid != -1 )
584 program.pcrPid = cached_pcrpid;
586 if ( cached_tpid != -1 )
589 program.textPid = cached_tpid;
591 CAID_LIST &caids = m_service->m_ca;
592 for (CAID_LIST::iterator it(caids.begin()); it != caids.end(); ++it)
593 program.caids.insert(*it);
600 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
609 int eDVBServicePMTHandler::getDataDemux(ePtr<iDVBDemux> &demux)
618 int eDVBServicePMTHandler::getDecodeDemux(ePtr<iDVBDemux> &demux)
621 /* if we're using the decoding demux as data source
622 (for example in pvr playbacks), return that one. */
623 if (m_use_decode_demux)
629 ASSERT(m_channel); /* calling without a previous ::tune is certainly bad. */
631 ret = m_channel->getDemux(demux, iDVBChannel::capDecode);
633 demux->getCADemuxID(m_decode_demux_num);
638 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
640 pvr_channel = m_pvr_channel;
647 void eDVBServicePMTHandler::SDTScanEvent(int event)
651 case eDVBScan::evtFinish:
653 ePtr<iDVBChannelList> db;
654 if (m_resourceManager->getChannelList(db) != 0)
655 eDebug("no channel list");
659 m_reference.getChannelID(chid);
660 if (chid == m_dvb_scan->getCurrentChannelID())
662 m_dvb_scan->insertInto(db, true);
663 eDebug("sdt update done!");
666 eDebug("ignore sdt update data.... incorrect transponder tuned!!!");
676 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref, int use_decode_demux, eCueSheet *cue, bool simulate, eDVBService *service)
681 m_use_decode_demux = use_decode_demux;
683 /* use given service as backup. This is used for timeshift where we want to clone the live stream using the cache, but in fact have a PVR channel */
686 /* is this a normal (non PVR) channel? */
687 if (ref.path.empty())
690 ref.getChannelID(chid);
691 res = m_resourceManager->allocateChannel(chid, m_channel, simulate);
693 eDebug("allocate Channel: res %d", res);
695 ePtr<iDVBChannelList> db;
696 if (!m_resourceManager->getChannelList(db))
697 db->getService((eServiceReferenceDVB&)m_reference, m_service);
699 if (!res && !simulate)
700 eDVBCIInterfaces::getInstance()->addPMTHandler(this);
701 } else if (!simulate) // no simulation of playback services
703 if (!ref.getServiceID().get() /* incorrect sid in meta file or recordings.epl*/ )
705 eWarning("no .meta file found, trying to find PMT pid");
707 if (tstools.openFile(ref.path.c_str()))
708 eWarning("failed to open file");
711 int service_id, pmt_pid;
712 if (!tstools.findPMT(pmt_pid, service_id))
714 eDebug("PMT pid found on pid %04x, service id %d", pmt_pid, service_id);
715 m_reference.setServiceID(service_id);
722 res = m_resourceManager->allocatePVRChannel(m_pvr_channel);
724 eDebug("allocatePVRChannel failed!\n");
725 m_channel = m_pvr_channel;
732 m_channel->connectStateChange(
733 slot(*this, &eDVBServicePMTHandler::channelStateChanged),
734 m_channelStateChanged_connection);
735 m_last_channel_state = -1;
736 channelStateChanged(m_channel);
738 m_channel->connectEvent(
739 slot(*this, &eDVBServicePMTHandler::channelEvent),
740 m_channelEvent_connection);
742 if (ref.path.empty())
745 m_dvb_scan = new eDVBScan(m_channel, true, false);
746 m_dvb_scan->connectEvent(slot(*this, &eDVBServicePMTHandler::SDTScanEvent), m_scan_event_connection);
750 if (res == eDVBResourceManager::errAllSourcesBusy)
751 serviceEvent(eventNoResources);
752 else /* errChidNotFound, errNoChannelList, errChannelNotInList, errNoSourceFound */
753 serviceEvent(eventMisconfiguration);
759 m_pvr_channel->setCueSheet(cue);
760 m_pvr_channel->playFile(ref.path.c_str());
767 void eDVBServicePMTHandler::free()
773 int demuxes[2] = {0,0};
775 m_demux->getCADemuxID(tmp);
777 if (m_decode_demux_num != 0xFF)
778 demuxes[1]=m_decode_demux_num;
780 demuxes[1]=demuxes[0];
781 ePtr<eTable<ProgramMapSection> > ptr;
782 m_PMT.getCurrent(ptr);
783 eDVBCAService::unregister_service(m_reference, demuxes, ptr);
788 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
792 m_pvr_channel->stopFile();
793 m_pvr_channel->setCueSheet(0);
804 CAServiceMap eDVBCAService::exist;
805 ChannelMap eDVBCAService::exist_channels;
806 ePtr<eConnection> eDVBCAService::m_chanAddedConn;
808 eDVBCAService::eDVBCAService()
809 :m_buffer(512), m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eTimer::create(eApp))
811 memset(m_used_demux, 0xFF, sizeof(m_used_demux));
812 CONNECT(m_retryTimer->timeout, eDVBCAService::sendCAPMT);
816 eDVBCAService::~eDVBCAService()
818 eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
822 // begin static methods
823 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_nums[2], eDVBCAService *&caservice )
825 CAServiceMap::iterator it = exist.find(ref);
826 if ( it != exist.end() )
827 caservice = it->second;
830 caservice = (exist[ref]=new eDVBCAService());
831 caservice->m_service = ref;
832 eDebug("[eDVBCAService] new service %s", ref.toString().c_str() );
835 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
836 for (int i=0; i < loops; ++i)
838 // search free demux entry
839 int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
841 while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
844 if ( iter < max_demux_slots )
846 caservice->m_used_demux[iter] = demux_nums[i] & 0xFF;
847 eDebug("[eDVBCAService] add demux %d to slot %d service %s", caservice->m_used_demux[iter], iter, ref.toString().c_str());
851 eDebug("[eDVBCAService] no more demux slots free for service %s!!", ref.toString().c_str());
858 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_nums[2], eTable<ProgramMapSection> *ptr )
860 CAServiceMap::iterator it = exist.find(ref);
861 if ( it == exist.end() )
863 eDebug("[eDVBCAService] try to unregister non registered %s", ref.toString().c_str());
868 eDVBCAService *caservice = it->second;
869 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
870 for (int i=0; i < loops; ++i)
874 used_demux_slots = 0,
875 max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
876 while ( iter < max_demux_slots )
878 if ( caservice->m_used_demux[iter] != 0xFF )
880 if ( !freed && caservice->m_used_demux[iter] == demux_nums[i] )
882 eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
883 caservice->m_used_demux[iter] = 0xFF;
892 eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_nums[i]);
895 if (!used_demux_slots) // no more used.. so we remove it
903 it->second->buildCAPMT(ptr);
905 eDebug("[eDVBCAService] can not send updated demux info");
913 void eDVBCAService::registerChannelCallback(eDVBResourceManager *res_mgr)
915 res_mgr->connectChannelAdded(slot(&DVBChannelAdded), m_chanAddedConn);
918 void eDVBCAService::DVBChannelAdded(eDVBChannel *chan)
922 eDebug("[eDVBCAService] new channel %p!", chan);
923 channel_data *data = new channel_data();
924 data->m_channel = chan;
925 data->m_prevChannelState = -1;
926 data->m_dataDemux = -1;
927 exist_channels[chan] = data;
928 chan->connectStateChange(slot(&DVBChannelStateChanged), data->m_stateChangedConn);
932 void eDVBCAService::DVBChannelStateChanged(iDVBChannel *chan)
934 ChannelMap::iterator it =
935 exist_channels.find(chan);
936 if ( it != exist_channels.end() )
939 chan->getState(state);
940 if ( it->second->m_prevChannelState != state )
944 case iDVBChannel::state_ok:
946 eDebug("[eDVBCAService] channel %p running", chan);
949 case iDVBChannel::state_release:
951 eDebug("[eDVBCAService] remove channel %p", chan);
952 unsigned char msg[8] = { 0x9f,0x80,0x3f,0x04,0x83,0x02,0x00,0x00 };
953 msg[7] = it->second->m_dataDemux & 0xFF;
955 struct sockaddr_un servaddr;
956 memset(&servaddr, 0, sizeof(struct sockaddr_un));
957 servaddr.sun_family = AF_UNIX;
958 strcpy(servaddr.sun_path, "/tmp/camd.socket");
959 clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
960 sock = socket(PF_UNIX, SOCK_STREAM, 0);
963 connect(sock, (struct sockaddr *) &servaddr, clilen);
964 fcntl(sock, F_SETFL, O_NONBLOCK);
966 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
967 if (write(sock, msg, 8) != 8)
968 eDebug("[eDVBCAService] write leave transponder failed!!");
971 exist_channels.erase(it);
976 default: // ignore all other events
980 it->second->m_prevChannelState = state;
985 channel_data *eDVBCAService::getChannelData(eDVBChannelID &chid)
987 for (ChannelMap::iterator it(exist_channels.begin()); it != exist_channels.end(); ++it)
989 if (chid == it->second->m_channel->getChannelID())
994 // end static methods
996 #define CA_REPLY_DEBUG
997 #define MAX_LENGTH_BYTES 4
998 #define MIN_LENGTH_BYTES 1
1000 void eDVBCAService::socketCB(int what)
1002 if (what & (eSocketNotifier::Read | eSocketNotifier::Priority))
1004 char msgbuffer[4096];
1005 ssize_t length = read(m_sock, msgbuffer, sizeof(msgbuffer));
1008 if (errno != EAGAIN && errno != EINTR && errno != EBUSY)
1010 eDebug("[eSocketMMIHandler] read (%m)");
1011 what |= eSocketNotifier::Error;
1013 } else if (length == 0)
1015 what |= eSocketNotifier::Hungup;
1019 unsigned char *data = (unsigned char*)msgbuffer;
1021 // If a new message starts, then the previous message
1022 // should already have been processed. Otherwise the
1023 // previous message was incomplete and should therefore
1025 if ((len >= 1) && ((data[0] & 0xFF) != 0x9f))
1027 if ((len >= 2) && ((data[1] & 0x80) != 0x80))
1029 if ((len >= 3) && ((data[2] & 0x80) != 0x00))
1034 #ifdef CA_REPLY_DEBUG
1035 eDebug("clear buffer");
1038 #ifdef CA_REPLY_DEBUG
1039 eDebug("Put to buffer:");
1040 for (int i=0; i < len; ++i)
1041 eDebugNoNewLine("%02x ", data[i]);
1042 eDebug("\n--------");
1044 m_buffer.write( data, len );
1046 while ( m_buffer.size() >= (3 + MIN_LENGTH_BYTES) )
1048 unsigned char tmp[3+MAX_LENGTH_BYTES];
1049 m_buffer.peek(tmp, 3+MIN_LENGTH_BYTES);
1050 if (((tmp[0] & 0xFF) != 0x9f) || ((tmp[1] & 0x80) != 0x80) || ((tmp[2] & 0x80) != 0x00))
1053 #ifdef CA_REPLY_DEBUG
1054 eDebug("skip %02x", tmp[0]);
1060 int peekLength = (tmp[3] & 0x7f) + 4;
1061 if (m_buffer.size() < peekLength)
1063 m_buffer.peek(tmp, peekLength);
1066 int LengthBytes=eDVBCISession::parseLengthField(tmp+3, size);
1067 int messageLength = 3+LengthBytes+size;
1068 if ( m_buffer.size() >= messageLength )
1070 unsigned char dest[messageLength];
1071 m_buffer.read(dest, messageLength);
1072 #ifdef CA_REPLY_DEBUG
1073 eDebug("dump ca reply:");
1074 for (int i=0; i < messageLength; ++i)
1075 eDebugNoNewLine("%02x ", dest[i]);
1076 eDebug("\n--------");
1078 // /*emit*/ mmi_progress(0, dest, (const void*)(dest+3+LengthBytes), messageLength-3-LengthBytes);
1083 if (what & eSocketNotifier::Hungup) {
1084 /*eDebug("[eDVBCAService] connection closed")*/;
1088 if (what & eSocketNotifier::Error)
1089 eDebug("[eDVBCAService] connection error");
1092 void eDVBCAService::Connect()
1095 memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
1096 m_servaddr.sun_family = AF_UNIX;
1097 strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
1098 m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
1099 m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
1102 if (!connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen))
1105 fcntl(m_sock, F_SETFL, O_NONBLOCK);
1106 setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
1107 m_sn = eSocketNotifier::create(eApp, m_sock,
1108 eSocketNotifier::Read|eSocketNotifier::Priority|eSocketNotifier::Error|eSocketNotifier::Hungup);
1109 CONNECT(m_sn->activated, eDVBCAService::socketCB);
1113 // eDebug("[eDVBCAService] connect failed %m");
1116 eDebug("[eDVBCAService] create socket failed %m");
1119 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
1124 eDVBTableSpec table_spec;
1125 ptr->getSpec(table_spec);
1127 int pmtpid = table_spec.pid,
1128 pmt_version = table_spec.version;
1130 uint8_t demux_mask = 0;
1131 int data_demux = -1;
1133 int iter=0, max_demux_slots = sizeof(m_used_demux);
1134 while ( iter < max_demux_slots )
1136 if ( m_used_demux[iter] != 0xFF )
1138 if ( m_used_demux[iter] > data_demux )
1139 data_demux = m_used_demux[iter];
1140 demux_mask |= (1 << m_used_demux[iter]);
1145 if ( data_demux == -1 )
1147 eDebug("[eDVBCAService] no data demux found for service %s", m_service.toString().c_str() );
1151 eDebug("demux %d mask %02x prevhash %08x", data_demux, demux_mask, m_prev_build_hash);
1153 unsigned int build_hash = ( pmtpid << 16);
1154 build_hash |= (demux_mask << 8);
1155 build_hash |= (pmt_version&0xFF);
1157 if ( build_hash == m_prev_build_hash )
1159 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
1163 std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
1164 if ( i != ptr->getSections().end() )
1166 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
1168 while( i != ptr->getSections().end() )
1170 // eDebug("append");
1174 // add our private descriptors to capmt
1177 tmp[0]=0x84; // pmt pid
1181 capmt.injectDescriptor(tmp, false);
1183 tmp[0] = 0x82; // demux
1185 tmp[2] = demux_mask; // descramble bitmask
1186 tmp[3] = data_demux&0xFF; // read section data from demux number
1187 capmt.injectDescriptor(tmp, false);
1189 tmp[0] = 0x81; // dvbnamespace
1191 tmp[2] = m_service.getDVBNamespace().get()>>24;
1192 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
1193 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
1194 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
1195 tmp[6]=m_service.getTransportStreamID().get()>>8;
1196 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
1197 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
1198 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
1199 capmt.injectDescriptor(tmp, false);
1201 capmt.writeToBuffer(m_capmt);
1204 m_prev_build_hash = build_hash;
1206 if ( m_sendstate != 0xFFFFFFFF )
1211 void eDVBCAService::sendCAPMT()
1213 if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
1220 if ( m_capmt[3] & 0x80 )
1223 int lenbytes = m_capmt[3] & ~0x80;
1225 wp = (wp << 8) | m_capmt[4 + i++];
1235 if ( write(m_sock, m_capmt, wp) == wp )
1237 m_sendstate=0xFFFFFFFF;
1238 eDebug("[eDVBCAService] send %d bytes",wp);
1240 m_service.getChannelID(chid);
1241 channel_data *data = getChannelData(chid);
1244 int lenbytes = m_capmt[3] & 0x80 ? m_capmt[3] & ~0x80 : 0;
1245 data->m_dataDemux = m_capmt[24+lenbytes];
1248 for(int i=0;i<wp;i++)
1249 eDebugNoNewLine("%02x ", m_capmt[i]);
1259 m_retryTimer->start(0,true);
1260 // eDebug("[eDVBCAService] send failed .. immediate retry");
1263 m_retryTimer->start(5000,true);
1264 // eDebug("[eDVBCAService] send failed .. retry in 5 sec");
1271 static PyObject *createTuple(int pid, const char *type)
1273 PyObject *r = PyTuple_New(2);
1274 PyTuple_SET_ITEM(r, 0, PyInt_FromLong(pid));
1275 PyTuple_SET_ITEM(r, 1, PyString_FromString(type));
1279 static inline void PyList_AppendSteal(PyObject *list, PyObject *item)
1281 PyList_Append(list, item);
1285 extern void PutToDict(ePyObject &dict, const char*key, ePyObject item); // defined in dvb/frontend.cpp
1287 PyObject *eDVBServicePMTHandler::program::createPythonObject()
1289 ePyObject r = PyDict_New();
1290 ePyObject l = PyList_New(0);
1292 PyList_AppendSteal(l, createTuple(0, "pat"));
1295 PyList_AppendSteal(l, createTuple(pmtPid, "pmt"));
1297 for (std::vector<eDVBServicePMTHandler::videoStream>::const_iterator
1298 i(videoStreams.begin());
1299 i != videoStreams.end(); ++i)
1300 PyList_AppendSteal(l, createTuple(i->pid, "video"));
1302 for (std::vector<eDVBServicePMTHandler::audioStream>::const_iterator
1303 i(audioStreams.begin());
1304 i != audioStreams.end(); ++i)
1305 PyList_AppendSteal(l, createTuple(i->pid, "audio"));
1307 for (std::vector<eDVBServicePMTHandler::subtitleStream>::const_iterator
1308 i(subtitleStreams.begin());
1309 i != subtitleStreams.end(); ++i)
1310 PyList_AppendSteal(l, createTuple(i->pid, "subtitle"));
1312 PyList_AppendSteal(l, createTuple(pcrPid, "pcr"));
1315 PyList_AppendSteal(l, createTuple(textPid, "text"));
1317 PutToDict(r, "pids", l);