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::evtEOF:
79 serviceEvent(eventEOF);
81 case iDVBChannel::evtSOF:
82 serviceEvent(eventSOF);
89 void eDVBServicePMTHandler::PMTready(int error)
92 serviceEvent(eventNoPMT);
95 m_have_cached_program = false;
96 serviceEvent(eventNewProgramInfo);
97 if (!m_pvr_channel) // don't send campmt to camd.socket for playbacked services
99 eEPGCache::getInstance()->PMTready(this);
102 int demuxes[2] = {0,0};
104 m_demux->getCADemuxID(tmp);
106 if (m_decode_demux_num != 0xFF)
107 demuxes[1]=m_decode_demux_num;
109 demuxes[1]=demuxes[0];
110 eDVBCAService::register_service(m_reference, demuxes, m_ca_servicePtr);
111 eDVBCIInterfaces::getInstance()->recheckPMTHandlers();
113 eDVBCIInterfaces::getInstance()->gotPMT(this);
117 ePtr<eTable<ProgramMapSection> > ptr;
118 if (!m_PMT.getCurrent(ptr))
119 m_ca_servicePtr->buildCAPMT(ptr);
121 eDebug("eDVBServicePMTHandler cannot call buildCAPMT");
126 void eDVBServicePMTHandler::PATready(int)
128 ePtr<eTable<ProgramAssociationSection> > ptr;
129 if (!m_PAT.getCurrent(ptr))
132 std::vector<ProgramAssociationSection*>::const_iterator i;
133 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
135 const ProgramAssociationSection &pat = **i;
136 ProgramAssociationConstIterator program;
137 for (program = pat.getPrograms()->begin(); program != pat.getPrograms()->end(); ++program)
138 if (eServiceID((*program)->getProgramNumber()) == m_reference.getServiceID())
139 pmtpid = (*program)->getProgramMapPid();
142 serviceEvent(eventNoPATEntry);
144 m_PMT.begin(eApp, eDVBPMTSpec(pmtpid, m_reference.getServiceID().get()), m_demux);
146 serviceEvent(eventNoPAT);
149 PyObject *eDVBServicePMTHandler::getCaIds()
155 if ( !getProgramInfo(prog) )
157 int cnt=prog.caids.size();
161 std::set<uint16_t>::iterator it(prog.caids.begin());
163 PyList_SET_ITEM(ret, cnt, PyInt_FromLong(*it++));
167 return ret ? (PyObject*)ret : (PyObject*)PyList_New(0);
170 int eDVBServicePMTHandler::getProgramInfo(struct program &program)
172 ePtr<eTable<ProgramMapSection> > ptr;
173 int cached_apid_ac3 = -1;
174 int cached_apid_mpeg = -1;
175 int cached_vpid = -1;
176 int cached_tpid = -1;
179 program.videoStreams.clear();
180 program.audioStreams.clear();
183 program.textPid = -1;
186 program.defaultAudioStream = 0;
187 audioStream *prev_audio = 0;
189 if ( m_service && !m_service->cacheEmpty() )
191 cached_vpid = m_service->getCacheEntry(eDVBService::cVPID);
192 cached_apid_mpeg = m_service->getCacheEntry(eDVBService::cAPID);
193 cached_apid_ac3 = m_service->getCacheEntry(eDVBService::cAC3PID);
194 cached_tpid = m_service->getCacheEntry(eDVBService::cTPID);
197 if ( ((m_service && m_service->usePMT()) || !m_service) && !m_PMT.getCurrent(ptr))
199 if (m_have_cached_program)
201 program = m_cached_program;
206 eDVBTableSpec table_spec;
207 ptr->getSpec(table_spec);
208 program.pmtPid = table_spec.pid < 0x1fff ? table_spec.pid : -1;
209 std::vector<ProgramMapSection*>::const_iterator i;
210 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
212 const ProgramMapSection &pmt = **i;
213 program.pcrPid = pmt.getPcrPid();
215 ElementaryStreamInfoConstIterator es;
216 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
218 int isaudio = 0, isvideo = 0, issubtitle = 0, forced_video = 0, forced_audio = 0, isteletext = 0;
219 int streamtype = (*es)->getType();
222 audio.component_tag=video.component_tag=-1;
223 video.type = videoStream::vtMPEG2;
224 audio.type = audioStream::atMPEG;
229 case 0x1b: // AVC Video Stream (MPEG4 H264)
230 video.type = videoStream::vtMPEG4_H264;
232 //break; fall through !!!
233 case 0x10: // MPEG 4 Part 2
236 video.type = videoStream::vtMPEG4_Part2;
239 //break; fall through !!!
240 case 0x01: // MPEG 1 video
242 video.type = videoStream::vtMPEG1;
243 //break; fall through !!!
244 case 0x02: // MPEG 2 video
247 //break; fall through !!!
248 case 0x03: // MPEG 1 audio
249 case 0x04: // MPEG 2 audio:
254 //break; fall through !!!
255 case 0x0f: // MPEG 2 AAC
256 if (!isvideo && !isaudio)
259 audio.type = audioStream::atAAC;
262 //break; fall through !!!
263 case 0x11: // MPEG 4 AAC
264 if (!isvideo && !isaudio)
267 audio.type = audioStream::atAACHE;
270 case 0x80: // user private ... but blueray LPCM
271 if (!isvideo && !isaudio)
274 audio.type = audioStream::atLPCM;
276 case 0x81: // user private ... but blueray AC3
277 if (!isvideo && !isaudio)
280 audio.type = audioStream::atAC3;
282 case 0x82: // Blueray DTS (dvb user private...)
283 case 0xA2: // Blueray secondary DTS
284 if (!isvideo && !isaudio)
287 audio.type = audioStream::atDTS;
289 case 0x06: // PES Private
290 case 0xEA: // TS_PSI_ST_SMPTE_VC1
292 int num_descriptors = 0;
293 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
294 desc != (*es)->getDescriptors()->end(); ++desc)
296 uint8_t tag = (*desc)->getTag();
297 /* check descriptors to get the exakt stream type. */
299 if (!forced_video && !forced_audio)
303 case AUDIO_STREAM_DESCRIPTOR:
306 case VIDEO_STREAM_DESCRIPTOR:
309 VideoStreamDescriptor *d = (VideoStreamDescriptor*)(*desc);
310 if (d->getMpeg1OnlyFlag())
311 video.type = videoStream::vtMPEG1;
314 case SUBTITLING_DESCRIPTOR:
316 SubtitlingDescriptor *d = (SubtitlingDescriptor*)(*desc);
317 const SubtitlingList *list = d->getSubtitlings();
319 s.pid = (*es)->getPid();
320 for (SubtitlingConstIterator it(list->begin()); it != list->end(); ++it)
322 s.subtitling_type = (*it)->getSubtitlingType();
323 switch(s.subtitling_type)
326 case 0x20 ... 0x23: // dvb subtitles
329 eDebug("dvb subtitle %s PID %04x with wrong subtitling type (%02x)... force 0x10!!",
330 s.language_code.c_str(), s.pid, s.subtitling_type);
331 s.subtitling_type = 0x10;
334 s.composition_page_id = (*it)->getCompositionPageId();
335 s.ancillary_page_id = (*it)->getAncillaryPageId();
336 s.language_code = (*it)->getIso639LanguageCode();
337 // eDebug("add dvb subtitle %s PID %04x, type %d, composition page %d, ancillary_page %d",
338 // s.language_code.c_str(), s.pid, s.subtitling_type, s.composition_page_id, s.ancillary_page_id);
340 program.subtitleStreams.push_back(s);
344 case TELETEXT_DESCRIPTOR:
345 if ( program.textPid == -1 || (*es)->getPid() == cached_tpid )
348 s.subtitling_type = 0x01; // EBU TELETEXT SUBTITLES
349 s.pid = program.textPid = (*es)->getPid();
350 TeletextDescriptor *d = (TeletextDescriptor*)(*desc);
352 const VbiTeletextList *list = d->getVbiTeletexts();
353 for (VbiTeletextConstIterator it(list->begin()); it != list->end(); ++it)
355 switch((*it)->getTeletextType())
357 case 0x02: // Teletext subtitle page
358 case 0x05: // Teletext subtitle page for hearing impaired pepople
359 s.language_code = (*it)->getIso639LanguageCode();
360 s.teletext_page_number = (*it)->getTeletextPageNumber();
361 s.teletext_magazine_number = (*it)->getTeletextMagazineNumber();
362 // eDebug("add teletext subtitle %s PID %04x, page number %d, magazine number %d",
363 // s.language_code.c_str(), s.pid, s.teletext_page_number, s.teletext_magazine_number);
364 program.subtitleStreams.push_back(s);
374 audio.type = audioStream::atDTS;
376 case 0x2B: // TS_PSI_DT_MPEG2_AAC
378 audio.type = audioStream::atAAC; // MPEG2-AAC
380 case 0x1C: // TS_PSI_DT_MPEG4_Audio
383 audio.type = audioStream::atAACHE; // MPEG4-AAC
387 audio.type = audioStream::atAC3;
389 case REGISTRATION_DESCRIPTOR: /* some services don't have a separate AC3 descriptor */
391 RegistrationDescriptor *d = (RegistrationDescriptor*)(*desc);
392 switch (d->getFormatIdentifier())
394 case 0x44545331 ... 0x44545333: // DTS1/DTS2/DTS3
396 audio.type = audioStream::atDTS;
398 case 0x41432d33: // == 'AC-3'
400 audio.type = audioStream::atAC3;
402 case 0x42535344: // == 'BSSD' (LPCM)
404 audio.type = audioStream::atLPCM;
406 case 0x56432d31: // == 'VC-1'
408 const AdditionalIdentificationInfoVector *vec = d->getAdditionalIdentificationInfo();
409 if (vec->size() > 1 && (*vec)[0] == 0x01) // subdescriptor tag
411 if ((*vec)[1] >= 0x90) // profile_level
412 video.type = videoStream::vtVC1; // advanced profile
414 video.type = videoStream::vtVC1_SM; // simple main
423 case 0x28: // TS_PSI_DT_AVC
425 video.type = videoStream::vtMPEG4_H264;
427 case 0x1B: // TS_PSI_DT_MPEG4_Video
429 video.type = videoStream::vtMPEG4_Part2;
437 case ISO_639_LANGUAGE_DESCRIPTOR:
441 const Iso639LanguageList *languages = ((Iso639LanguageDescriptor*)*desc)->getIso639Languages();
442 /* use last language code */
443 for (Iso639LanguageConstIterator i(languages->begin()); i != languages->end(); ++i, ++cnt)
446 audio.language_code = (*i)->getIso639LanguageCode();
448 audio.language_code += "/" + (*i)->getIso639LanguageCode();
452 case STREAM_IDENTIFIER_DESCRIPTOR:
453 audio.component_tag =
454 video.component_tag =
455 ((StreamIdentifierDescriptor*)*desc)->getComponentTag();
459 CaDescriptor *descr = (CaDescriptor*)(*desc);
460 program.caids.insert(descr->getCaSystemId());
467 if (!num_descriptors && streamtype == 0x06 && prev_audio)
469 prev_audio->rdsPid = (*es)->getPid();
470 eDebug("Rds PID %04x detected ? ! ?", prev_audio->rdsPid);
477 if (isteletext && (isaudio || isvideo))
479 eDebug("ambiguous streamtype for PID %04x detected.. forced as teletext!", (*es)->getPid());
480 continue; // continue with next PID
482 else if (issubtitle && (isaudio || isvideo))
483 eDebug("ambiguous streamtype for PID %04x detected.. forced as subtitle!", (*es)->getPid());
484 else if (isaudio && isvideo)
485 eDebug("ambiguous streamtype for PID %04x detected.. forced as video!", (*es)->getPid());
486 if (issubtitle) // continue with next PID
490 video.pid = (*es)->getPid();
491 if ( !program.videoStreams.empty() && video.pid == cached_vpid )
493 program.videoStreams.push_back(program.videoStreams[0]);
494 program.videoStreams[0] = video;
497 program.videoStreams.push_back(video);
501 audio.pid = (*es)->getPid();
503 /* if we find the cached pids, this will be our default stream */
504 if (audio.pid == cached_apid_ac3 || audio.pid == cached_apid_mpeg)
505 program.defaultAudioStream = program.audioStreams.size();
507 /* also, we need to know the first non-mpeg (i.e. "ac3"/dts/...) stream */
508 if ((audio.type != audioStream::atMPEG) && ((first_ac3 == -1) || (audio.pid == cached_apid_ac3)))
509 first_ac3 = program.audioStreams.size();
511 program.audioStreams.push_back(audio);
512 prev_audio = &program.audioStreams.back();
517 for (DescriptorConstIterator desc = pmt.getDescriptors()->begin();
518 desc != pmt.getDescriptors()->end(); ++desc)
520 if ((*desc)->getTag() == CA_DESCRIPTOR)
522 CaDescriptor *descr = (CaDescriptor*)(*desc);
523 program.caids.insert(descr->getCaSystemId());
529 /* finally some fixup: if our default audio stream is an MPEG audio stream,
530 and we have 'defaultac3' set, use the first available ac3 stream instead.
531 (note: if an ac3 audio stream was selected before, this will be also stored
532 in 'fisrt_ac3', so we don't need to worry. */
533 bool defaultac3 = false;
534 std::string default_ac3;
536 if (!ePythonConfigQuery::getConfigValue("config.av.defaultac3", default_ac3))
537 defaultac3 = default_ac3 == "True";
539 if (defaultac3 && (first_ac3 != -1))
540 program.defaultAudioStream = first_ac3;
542 m_cached_program = program;
543 m_have_cached_program = true;
545 } else if ( m_service && !m_service->cacheEmpty() )
547 int cached_pcrpid = m_service->getCacheEntry(eDVBService::cPCRPID),
548 vpidtype = m_service->getCacheEntry(eDVBService::cVTYPE),
550 if ( vpidtype == -1 )
551 vpidtype = videoStream::vtMPEG2;
552 if ( cached_vpid != -1 )
557 program.videoStreams.push_back(s);
560 if ( cached_apid_ac3 != -1 )
563 s.type = audioStream::atAC3;
564 s.pid = cached_apid_ac3;
566 program.audioStreams.push_back(s);
569 if ( cached_apid_mpeg != -1 )
572 s.type = audioStream::atMPEG;
573 s.pid = cached_apid_mpeg;
575 program.audioStreams.push_back(s);
578 if ( cached_pcrpid != -1 )
581 program.pcrPid = cached_pcrpid;
583 if ( cached_tpid != -1 )
586 program.textPid = cached_tpid;
588 CAID_LIST &caids = m_service->m_ca;
589 for (CAID_LIST::iterator it(caids.begin()); it != caids.end(); ++it)
590 program.caids.insert(*it);
597 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
606 int eDVBServicePMTHandler::getDataDemux(ePtr<iDVBDemux> &demux)
615 int eDVBServicePMTHandler::getDecodeDemux(ePtr<iDVBDemux> &demux)
618 /* if we're using the decoding demux as data source
619 (for example in pvr playbacks), return that one. */
620 if (m_use_decode_demux)
626 ASSERT(m_channel); /* calling without a previous ::tune is certainly bad. */
628 ret = m_channel->getDemux(demux, iDVBChannel::capDecode);
630 demux->getCADemuxID(m_decode_demux_num);
635 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
637 pvr_channel = m_pvr_channel;
644 void eDVBServicePMTHandler::SDTScanEvent(int event)
648 case eDVBScan::evtFinish:
650 ePtr<iDVBChannelList> db;
651 if (m_resourceManager->getChannelList(db) != 0)
652 eDebug("no channel list");
656 m_reference.getChannelID(chid);
657 if (chid == m_dvb_scan->getCurrentChannelID())
659 m_dvb_scan->insertInto(db, true);
660 eDebug("sdt update done!");
663 eDebug("ignore sdt update data.... incorrect transponder tuned!!!");
673 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref, int use_decode_demux, eCueSheet *cue, bool simulate, eDVBService *service)
678 m_use_decode_demux = use_decode_demux;
680 /* 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 */
683 /* is this a normal (non PVR) channel? */
684 if (ref.path.empty())
687 ref.getChannelID(chid);
688 res = m_resourceManager->allocateChannel(chid, m_channel, simulate);
690 eDebug("allocate Channel: res %d", res);
692 ePtr<iDVBChannelList> db;
693 if (!m_resourceManager->getChannelList(db))
694 db->getService((eServiceReferenceDVB&)m_reference, m_service);
696 if (!res && !simulate)
697 eDVBCIInterfaces::getInstance()->addPMTHandler(this);
698 } else if (!simulate) // no simulation of playback services
700 if (!ref.getServiceID().get() /* incorrect sid in meta file or recordings.epl*/ )
702 eWarning("no .meta file found, trying to find PMT pid");
704 if (tstools.openFile(ref.path.c_str()))
705 eWarning("failed to open file");
708 int service_id, pmt_pid;
709 if (!tstools.findPMT(pmt_pid, service_id))
711 eDebug("PMT pid found on pid %04x, service id %d", pmt_pid, service_id);
712 m_reference.setServiceID(service_id);
719 res = m_resourceManager->allocatePVRChannel(m_pvr_channel);
721 eDebug("allocatePVRChannel failed!\n");
722 m_channel = m_pvr_channel;
729 m_channel->connectStateChange(
730 slot(*this, &eDVBServicePMTHandler::channelStateChanged),
731 m_channelStateChanged_connection);
732 m_last_channel_state = -1;
733 channelStateChanged(m_channel);
735 m_channel->connectEvent(
736 slot(*this, &eDVBServicePMTHandler::channelEvent),
737 m_channelEvent_connection);
739 if (ref.path.empty())
742 m_dvb_scan = new eDVBScan(m_channel, true, false);
743 m_dvb_scan->connectEvent(slot(*this, &eDVBServicePMTHandler::SDTScanEvent), m_scan_event_connection);
747 if (res == eDVBResourceManager::errAllSourcesBusy)
748 serviceEvent(eventNoResources);
749 else /* errChidNotFound, errNoChannelList, errChannelNotInList, errNoSourceFound */
750 serviceEvent(eventMisconfiguration);
756 m_pvr_channel->setCueSheet(cue);
757 m_pvr_channel->playFile(ref.path.c_str());
764 void eDVBServicePMTHandler::free()
770 int demuxes[2] = {0,0};
772 m_demux->getCADemuxID(tmp);
774 if (m_decode_demux_num != 0xFF)
775 demuxes[1]=m_decode_demux_num;
777 demuxes[1]=demuxes[0];
778 ePtr<eTable<ProgramMapSection> > ptr;
779 m_PMT.getCurrent(ptr);
780 eDVBCAService::unregister_service(m_reference, demuxes, ptr);
785 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
789 m_pvr_channel->stopFile();
790 m_pvr_channel->setCueSheet(0);
801 CAServiceMap eDVBCAService::exist;
802 ChannelMap eDVBCAService::exist_channels;
803 ePtr<eConnection> eDVBCAService::m_chanAddedConn;
805 eDVBCAService::eDVBCAService()
806 :m_buffer(512), m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eTimer::create(eApp))
808 memset(m_used_demux, 0xFF, sizeof(m_used_demux));
809 CONNECT(m_retryTimer->timeout, eDVBCAService::sendCAPMT);
813 eDVBCAService::~eDVBCAService()
815 eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
819 // begin static methods
820 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_nums[2], eDVBCAService *&caservice )
822 CAServiceMap::iterator it = exist.find(ref);
823 if ( it != exist.end() )
824 caservice = it->second;
827 caservice = (exist[ref]=new eDVBCAService());
828 caservice->m_service = ref;
829 eDebug("[eDVBCAService] new service %s", ref.toString().c_str() );
832 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
833 for (int i=0; i < loops; ++i)
835 // search free demux entry
836 int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
838 while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
841 if ( iter < max_demux_slots )
843 caservice->m_used_demux[iter] = demux_nums[i] & 0xFF;
844 eDebug("[eDVBCAService] add demux %d to slot %d service %s", caservice->m_used_demux[iter], iter, ref.toString().c_str());
848 eDebug("[eDVBCAService] no more demux slots free for service %s!!", ref.toString().c_str());
855 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_nums[2], eTable<ProgramMapSection> *ptr )
857 CAServiceMap::iterator it = exist.find(ref);
858 if ( it == exist.end() )
860 eDebug("[eDVBCAService] try to unregister non registered %s", ref.toString().c_str());
865 eDVBCAService *caservice = it->second;
866 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
867 for (int i=0; i < loops; ++i)
871 used_demux_slots = 0,
872 max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
873 while ( iter < max_demux_slots )
875 if ( caservice->m_used_demux[iter] != 0xFF )
877 if ( !freed && caservice->m_used_demux[iter] == demux_nums[i] )
879 eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
880 caservice->m_used_demux[iter] = 0xFF;
889 eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_nums[i]);
892 if (!used_demux_slots) // no more used.. so we remove it
900 it->second->buildCAPMT(ptr);
902 eDebug("[eDVBCAService] can not send updated demux info");
910 void eDVBCAService::registerChannelCallback(eDVBResourceManager *res_mgr)
912 res_mgr->connectChannelAdded(slot(&DVBChannelAdded), m_chanAddedConn);
915 void eDVBCAService::DVBChannelAdded(eDVBChannel *chan)
919 eDebug("[eDVBCAService] new channel %p!", chan);
920 channel_data *data = new channel_data();
921 data->m_channel = chan;
922 data->m_prevChannelState = -1;
923 data->m_dataDemux = -1;
924 exist_channels[chan] = data;
925 chan->connectStateChange(slot(&DVBChannelStateChanged), data->m_stateChangedConn);
929 void eDVBCAService::DVBChannelStateChanged(iDVBChannel *chan)
931 ChannelMap::iterator it =
932 exist_channels.find(chan);
933 if ( it != exist_channels.end() )
936 chan->getState(state);
937 if ( it->second->m_prevChannelState != state )
941 case iDVBChannel::state_ok:
943 eDebug("[eDVBCAService] channel %p running", chan);
946 case iDVBChannel::state_release:
948 eDebug("[eDVBCAService] remove channel %p", chan);
949 unsigned char msg[8] = { 0x9f,0x80,0x3f,0x04,0x83,0x02,0x00,0x00 };
950 msg[7] = it->second->m_dataDemux & 0xFF;
952 struct sockaddr_un servaddr;
953 memset(&servaddr, 0, sizeof(struct sockaddr_un));
954 servaddr.sun_family = AF_UNIX;
955 strcpy(servaddr.sun_path, "/tmp/camd.socket");
956 clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
957 sock = socket(PF_UNIX, SOCK_STREAM, 0);
960 connect(sock, (struct sockaddr *) &servaddr, clilen);
961 fcntl(sock, F_SETFL, O_NONBLOCK);
963 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
964 if (write(sock, msg, 8) != 8)
965 eDebug("[eDVBCAService] write leave transponder failed!!");
968 exist_channels.erase(it);
973 default: // ignore all other events
977 it->second->m_prevChannelState = state;
982 channel_data *eDVBCAService::getChannelData(eDVBChannelID &chid)
984 for (ChannelMap::iterator it(exist_channels.begin()); it != exist_channels.end(); ++it)
986 if (chid == it->second->m_channel->getChannelID())
991 // end static methods
993 #define CA_REPLY_DEBUG
994 #define MAX_LENGTH_BYTES 4
995 #define MIN_LENGTH_BYTES 1
997 void eDVBCAService::socketCB(int what)
999 if (what & (eSocketNotifier::Read | eSocketNotifier::Priority))
1001 char msgbuffer[4096];
1002 ssize_t length = read(m_sock, msgbuffer, sizeof(msgbuffer));
1005 if (errno != EAGAIN && errno != EINTR && errno != EBUSY)
1007 eDebug("[eSocketMMIHandler] read (%m)");
1008 what |= eSocketNotifier::Error;
1010 } else if (length == 0)
1012 what |= eSocketNotifier::Hungup;
1016 unsigned char *data = (unsigned char*)msgbuffer;
1018 // If a new message starts, then the previous message
1019 // should already have been processed. Otherwise the
1020 // previous message was incomplete and should therefore
1022 if ((len >= 1) && ((data[0] & 0xFF) != 0x9f))
1024 if ((len >= 2) && ((data[1] & 0x80) != 0x80))
1026 if ((len >= 3) && ((data[2] & 0x80) != 0x00))
1031 #ifdef CA_REPLY_DEBUG
1032 eDebug("clear buffer");
1035 #ifdef CA_REPLY_DEBUG
1036 eDebug("Put to buffer:");
1037 for (int i=0; i < len; ++i)
1038 eDebugNoNewLine("%02x ", data[i]);
1039 eDebug("\n--------");
1041 m_buffer.write( data, len );
1043 while ( m_buffer.size() >= (3 + MIN_LENGTH_BYTES) )
1045 unsigned char tmp[3+MAX_LENGTH_BYTES];
1046 m_buffer.peek(tmp, 3+MIN_LENGTH_BYTES);
1047 if (((tmp[0] & 0xFF) != 0x9f) || ((tmp[1] & 0x80) != 0x80) || ((tmp[2] & 0x80) != 0x00))
1050 #ifdef CA_REPLY_DEBUG
1051 eDebug("skip %02x", tmp[0]);
1057 int peekLength = (tmp[3] & 0x7f) + 4;
1058 if (m_buffer.size() < peekLength)
1060 m_buffer.peek(tmp, peekLength);
1063 int LengthBytes=eDVBCISession::parseLengthField(tmp+3, size);
1064 int messageLength = 3+LengthBytes+size;
1065 if ( m_buffer.size() >= messageLength )
1067 unsigned char dest[messageLength];
1068 m_buffer.read(dest, messageLength);
1069 #ifdef CA_REPLY_DEBUG
1070 eDebug("dump ca reply:");
1071 for (int i=0; i < messageLength; ++i)
1072 eDebugNoNewLine("%02x ", dest[i]);
1073 eDebug("\n--------");
1075 // /*emit*/ mmi_progress(0, dest, (const void*)(dest+3+LengthBytes), messageLength-3-LengthBytes);
1080 if (what & eSocketNotifier::Hungup) {
1081 /*eDebug("[eDVBCAService] connection closed")*/;
1085 if (what & eSocketNotifier::Error)
1086 eDebug("[eDVBCAService] connection error");
1089 void eDVBCAService::Connect()
1092 memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
1093 m_servaddr.sun_family = AF_UNIX;
1094 strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
1095 m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
1096 m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
1099 if (!connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen))
1102 fcntl(m_sock, F_SETFL, O_NONBLOCK);
1103 setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
1104 m_sn = eSocketNotifier::create(eApp, m_sock,
1105 eSocketNotifier::Read|eSocketNotifier::Priority|eSocketNotifier::Error|eSocketNotifier::Hungup);
1106 CONNECT(m_sn->activated, eDVBCAService::socketCB);
1110 // eDebug("[eDVBCAService] connect failed %m");
1113 eDebug("[eDVBCAService] create socket failed %m");
1116 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
1121 eDVBTableSpec table_spec;
1122 ptr->getSpec(table_spec);
1124 int pmtpid = table_spec.pid,
1125 pmt_version = table_spec.version;
1127 uint8_t demux_mask = 0;
1128 int data_demux = -1;
1130 int iter=0, max_demux_slots = sizeof(m_used_demux);
1131 while ( iter < max_demux_slots )
1133 if ( m_used_demux[iter] != 0xFF )
1135 if ( m_used_demux[iter] > data_demux )
1136 data_demux = m_used_demux[iter];
1137 demux_mask |= (1 << m_used_demux[iter]);
1142 if ( data_demux == -1 )
1144 eDebug("[eDVBCAService] no data demux found for service %s", m_service.toString().c_str() );
1148 eDebug("demux %d mask %02x prevhash %08x", data_demux, demux_mask, m_prev_build_hash);
1150 unsigned int build_hash = ( pmtpid << 16);
1151 build_hash |= (demux_mask << 8);
1152 build_hash |= (pmt_version&0xFF);
1154 if ( build_hash == m_prev_build_hash )
1156 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
1160 std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
1161 if ( i != ptr->getSections().end() )
1163 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
1165 while( i != ptr->getSections().end() )
1167 // eDebug("append");
1171 // add our private descriptors to capmt
1174 tmp[0]=0x84; // pmt pid
1178 capmt.injectDescriptor(tmp, false);
1180 tmp[0] = 0x82; // demux
1182 tmp[2] = demux_mask; // descramble bitmask
1183 tmp[3] = data_demux&0xFF; // read section data from demux number
1184 capmt.injectDescriptor(tmp, false);
1186 tmp[0] = 0x81; // dvbnamespace
1188 tmp[2] = m_service.getDVBNamespace().get()>>24;
1189 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
1190 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
1191 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
1192 tmp[6]=m_service.getTransportStreamID().get()>>8;
1193 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
1194 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
1195 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
1196 capmt.injectDescriptor(tmp, false);
1198 capmt.writeToBuffer(m_capmt);
1201 m_prev_build_hash = build_hash;
1203 if ( m_sendstate != 0xFFFFFFFF )
1208 void eDVBCAService::sendCAPMT()
1210 if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
1217 if ( m_capmt[3] & 0x80 )
1220 int lenbytes = m_capmt[3] & ~0x80;
1222 wp = (wp << 8) | m_capmt[4 + i++];
1232 if ( write(m_sock, m_capmt, wp) == wp )
1234 m_sendstate=0xFFFFFFFF;
1235 eDebug("[eDVBCAService] send %d bytes",wp);
1237 m_service.getChannelID(chid);
1238 channel_data *data = getChannelData(chid);
1241 int lenbytes = m_capmt[3] & 0x80 ? m_capmt[3] & ~0x80 : 0;
1242 data->m_dataDemux = m_capmt[24+lenbytes];
1245 for(int i=0;i<wp;i++)
1246 eDebugNoNewLine("%02x ", m_capmt[i]);
1256 m_retryTimer->start(0,true);
1257 // eDebug("[eDVBCAService] send failed .. immediate retry");
1260 m_retryTimer->start(5000,true);
1261 // eDebug("[eDVBCAService] send failed .. retry in 5 sec");
1268 static PyObject *createTuple(int pid, const char *type)
1270 PyObject *r = PyTuple_New(2);
1271 PyTuple_SET_ITEM(r, 0, PyInt_FromLong(pid));
1272 PyTuple_SET_ITEM(r, 1, PyString_FromString(type));
1276 static inline void PyList_AppendSteal(PyObject *list, PyObject *item)
1278 PyList_Append(list, item);
1282 extern void PutToDict(ePyObject &dict, const char*key, ePyObject item); // defined in dvb/frontend.cpp
1284 PyObject *eDVBServicePMTHandler::program::createPythonObject()
1286 ePyObject r = PyDict_New();
1287 ePyObject l = PyList_New(0);
1289 PyList_AppendSteal(l, createTuple(0, "pat"));
1292 PyList_AppendSteal(l, createTuple(pmtPid, "pmt"));
1294 for (std::vector<eDVBServicePMTHandler::videoStream>::const_iterator
1295 i(videoStreams.begin());
1296 i != videoStreams.end(); ++i)
1297 PyList_AppendSteal(l, createTuple(i->pid, "video"));
1299 for (std::vector<eDVBServicePMTHandler::audioStream>::const_iterator
1300 i(audioStreams.begin());
1301 i != audioStreams.end(); ++i)
1302 PyList_AppendSteal(l, createTuple(i->pid, "audio"));
1304 for (std::vector<eDVBServicePMTHandler::subtitleStream>::const_iterator
1305 i(subtitleStreams.begin());
1306 i != subtitleStreams.end(); ++i)
1307 PyList_AppendSteal(l, createTuple(i->pid, "subtitle"));
1309 PyList_AppendSteal(l, createTuple(pcrPid, "pcr"));
1312 PyList_AppendSteal(l, createTuple(textPid, "text"));
1314 PutToDict(r, "pids", l);