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>
21 eDVBServicePMTHandler::eDVBServicePMTHandler()
22 :m_ca_servicePtr(0), m_dvb_scan(0), m_decode_demux_num(0xFF)
24 m_use_decode_demux = 0;
26 eDVBResourceManager::getInstance(m_resourceManager);
27 CONNECT(m_PMT.tableReady, eDVBServicePMTHandler::PMTready);
28 CONNECT(m_PAT.tableReady, eDVBServicePMTHandler::PATready);
31 eDVBServicePMTHandler::~eDVBServicePMTHandler()
36 void eDVBServicePMTHandler::channelStateChanged(iDVBChannel *channel)
39 channel->getState(state);
41 if ((m_last_channel_state != iDVBChannel::state_ok)
42 && (state == iDVBChannel::state_ok) && (!m_demux))
45 if (m_channel->getDemux(m_demux, (!m_use_decode_demux) ? 0 : iDVBChannel::capDecode))
46 eDebug("Allocating %s-decoding a demux for now tuned-in channel failed.", m_use_decode_demux ? "" : "non-");
48 serviceEvent(eventTuned);
52 eDebug("ok ... now we start!!");
54 if (!m_service || m_service->usePMT())
57 m_PAT.begin(eApp, eDVBPATSpec(), m_demux);
59 m_PMT.begin(eApp, eDVBPMTSpec(m_pmt_pid, m_reference.getServiceID().get()), m_demux);
62 if ( m_service && !m_service->cacheEmpty() )
63 serviceEvent(eventNewProgramInfo);
65 } else if ((m_last_channel_state != iDVBChannel::state_failed) &&
66 (state == iDVBChannel::state_failed))
68 eDebug("tune failed.");
69 serviceEvent(eventTuneFailed);
73 void eDVBServicePMTHandler::channelEvent(iDVBChannel *channel, int event)
77 case iDVBChannel::evtEOF:
78 serviceEvent(eventEOF);
80 case iDVBChannel::evtSOF:
81 serviceEvent(eventSOF);
88 void eDVBServicePMTHandler::PMTready(int error)
91 serviceEvent(eventNoPMT);
94 m_have_cached_program = false;
95 serviceEvent(eventNewProgramInfo);
96 if (!m_pvr_channel) // don't send campmt to camd.socket for playbacked services
98 eEPGCache::getInstance()->PMTready(this);
101 int demuxes[2] = {0,0};
103 m_demux->getCADemuxID(tmp);
105 if (m_decode_demux_num != 0xFF)
106 demuxes[1]=m_decode_demux_num;
108 demuxes[1]=demuxes[0];
109 eDVBCAService::register_service(m_reference, demuxes, m_ca_servicePtr);
110 eDVBCIInterfaces::getInstance()->recheckPMTHandlers();
112 eDVBCIInterfaces::getInstance()->gotPMT(this);
116 ePtr<eTable<ProgramMapSection> > ptr;
117 if (!m_PMT.getCurrent(ptr))
118 m_ca_servicePtr->buildCAPMT(ptr);
120 eDebug("eDVBServicePMTHandler cannot call buildCAPMT");
125 void eDVBServicePMTHandler::PATready(int)
127 ePtr<eTable<ProgramAssociationSection> > ptr;
128 if (!m_PAT.getCurrent(ptr))
131 std::vector<ProgramAssociationSection*>::const_iterator i;
132 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
134 const ProgramAssociationSection &pat = **i;
135 ProgramAssociationConstIterator program;
136 for (program = pat.getPrograms()->begin(); program != pat.getPrograms()->end(); ++program)
137 if (eServiceID((*program)->getProgramNumber()) == m_reference.getServiceID())
138 pmtpid = (*program)->getProgramMapPid();
141 serviceEvent(eventNoPATEntry);
143 m_PMT.begin(eApp, eDVBPMTSpec(pmtpid, m_reference.getServiceID().get()), m_demux);
145 serviceEvent(eventNoPAT);
148 PyObject *eDVBServicePMTHandler::getCaIds()
154 if ( !getProgramInfo(prog) )
156 int cnt=prog.caids.size();
160 std::set<uint16_t>::iterator it(prog.caids.begin());
162 PyList_SET_ITEM(ret, cnt, PyInt_FromLong(*it++));
166 return ret ? (PyObject*)ret : (PyObject*)PyList_New(0);
169 int eDVBServicePMTHandler::getProgramInfo(struct program &program)
171 ePtr<eTable<ProgramMapSection> > ptr;
172 int cached_apid_ac3 = -1;
173 int cached_apid_mpeg = -1;
174 int cached_vpid = -1;
175 int cached_tpid = -1;
178 program.videoStreams.clear();
179 program.audioStreams.clear();
182 program.textPid = -1;
185 program.defaultAudioStream = 0;
187 if ( m_service && !m_service->cacheEmpty() )
189 cached_vpid = m_service->getCacheEntry(eDVBService::cVPID);
190 cached_apid_mpeg = m_service->getCacheEntry(eDVBService::cAPID);
191 cached_apid_ac3 = m_service->getCacheEntry(eDVBService::cAC3PID);
192 cached_tpid = m_service->getCacheEntry(eDVBService::cTPID);
195 if ( ((m_service && m_service->usePMT()) || !m_service) && !m_PMT.getCurrent(ptr))
197 if (m_have_cached_program)
199 program = m_cached_program;
204 eDVBTableSpec table_spec;
205 ptr->getSpec(table_spec);
206 program.pmtPid = table_spec.pid < 0x1fff ? table_spec.pid : -1;
207 std::vector<ProgramMapSection*>::const_iterator i;
208 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
210 const ProgramMapSection &pmt = **i;
211 program.pcrPid = pmt.getPcrPid();
213 ElementaryStreamInfoConstIterator es;
214 for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
216 int isaudio = 0, isvideo = 0;
219 audio.component_tag=video.component_tag=-1;
220 video.type = videoStream::vtMPEG2;
221 audio.type = audioStream::atMPEG;
223 switch ((*es)->getType())
225 case 0x1b: // AVC Video Stream (MPEG4 H264)
226 video.type = videoStream::vtMPEG4_H264;
228 //break; fall through !!!
229 case 0x10: // MPEG 4 Part 2
232 video.type = videoStream::vtMPEG4_Part2;
235 //break; fall through !!!
236 case 0x01: // MPEG 1 video
238 video.type = videoStream::vtMPEG1;
239 //break; fall through !!!
240 case 0x02: // MPEG 2 video
242 //break; fall through !!!
243 case 0x03: // MPEG 1 audio
244 case 0x04: // MPEG 2 audio:
247 //break; fall through !!!
248 case 0x0f: // MPEG 2 AAC
249 if (!isvideo && !isaudio)
252 audio.type = audioStream::atAAC;
254 //break; fall through !!!
255 case 0x11: // MPEG 4 AAC
256 if (!isvideo && !isaudio)
259 audio.type = audioStream::atAACHE;
261 case 0x06: // PES Private
262 case 0x81: // user private
263 case 0xEA: // TS_PSI_ST_SMPTE_VC1
264 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
265 desc != (*es)->getDescriptors()->end(); ++desc)
267 uint8_t tag = (*desc)->getTag();
268 if (!isaudio && !isvideo)
270 /* PES private can contain AC-3, DTS or lots of other stuff.
271 check descriptors to get the exakt type. */
274 case AUDIO_STREAM_DESCRIPTOR:
277 case VIDEO_STREAM_DESCRIPTOR:
280 VideoStreamDescriptor *d = (VideoStreamDescriptor*)(*desc);
281 if (d->getMpeg1OnlyFlag())
282 video.type = videoStream::vtMPEG1;
285 case SUBTITLING_DESCRIPTOR:
287 SubtitlingDescriptor *d = (SubtitlingDescriptor*)(*desc);
288 const SubtitlingList *list = d->getSubtitlings();
290 s.pid = (*es)->getPid();
291 for (SubtitlingConstIterator it(list->begin()); it != list->end(); ++it)
293 s.subtitling_type = (*it)->getSubtitlingType();
294 switch(s.subtitling_type)
297 case 0x20 ... 0x23: // dvb subtitles
300 eDebug("dvb subtitle %s PID %04x with wrong subtitling type (%02x)... force 0x10!!",
301 s.language_code.c_str(), s.pid, s.subtitling_type);
302 s.subtitling_type = 0x10;
305 s.composition_page_id = (*it)->getCompositionPageId();
306 s.ancillary_page_id = (*it)->getAncillaryPageId();
307 s.language_code = (*it)->getIso639LanguageCode();
308 // eDebug("add dvb subtitle %s PID %04x, type %d, composition page %d, ancillary_page %d",
309 // s.language_code.c_str(), s.pid, s.subtitling_type, s.composition_page_id, s.ancillary_page_id);
310 program.subtitleStreams.push_back(s);
314 case TELETEXT_DESCRIPTOR:
315 if ( program.textPid == -1 || (*es)->getPid() == cached_tpid )
318 s.subtitling_type = 0x01; // EBU TELETEXT SUBTITLES
319 s.pid = program.textPid = (*es)->getPid();
320 TeletextDescriptor *d = (TeletextDescriptor*)(*desc);
321 const VbiTeletextList *list = d->getVbiTeletexts();
322 for (VbiTeletextConstIterator it(list->begin()); it != list->end(); ++it)
324 switch((*it)->getTeletextType())
326 case 0x02: // Teletext subtitle page
327 case 0x05: // Teletext subtitle page for hearing impaired pepople
328 s.language_code = (*it)->getIso639LanguageCode();
329 s.teletext_page_number = (*it)->getTeletextPageNumber();
330 s.teletext_magazine_number = (*it)->getTeletextMagazineNumber();
331 // eDebug("add teletext subtitle %s PID %04x, page number %d, magazine number %d",
332 // s.language_code.c_str(), s.pid, s.teletext_page_number, s.teletext_magazine_number);
333 program.subtitleStreams.push_back(s);
341 audio.type = audioStream::atDTS;
343 case 0x2B: // TS_PSI_DT_MPEG2_AAC
345 audio.type = audioStream::atAAC; // MPEG2-AAC
347 case 0x1C: // TS_PSI_DT_MPEG4_Audio
350 audio.type = audioStream::atAACHE; // MPEG4-AAC
354 audio.type = audioStream::atAC3;
356 case REGISTRATION_DESCRIPTOR: /* some services don't have a separate AC3 descriptor */
358 /* libdvbsi++ doesn't yet support this descriptor type, so work around. */
359 if ((*desc)->getLength() < 4)
361 unsigned char descr[6];
362 (*desc)->writeToBuffer(descr);
363 int format_identifier = (descr[2] << 24) | (descr[3] << 16) | (descr[4] << 8) | (descr[5]);
364 switch (format_identifier)
368 audio.type = audioStream::atAC3;
371 if (descr[6] == 0x01) // subdescriptor tag
373 if (descr[7] >= 0x90) // profile_level
374 video.type = videoStream::vtVC1; // advanced profile
376 video.type = videoStream::vtVC1_SM; // simple main
385 case 0x28: // TS_PSI_DT_AVC
387 video.type = videoStream::vtMPEG4_H264;
389 case 0x1B: // TS_PSI_DT_MPEG4_Video
391 video.type = videoStream::vtMPEG4_Part2;
399 case ISO_639_LANGUAGE_DESCRIPTOR:
403 const Iso639LanguageList *languages = ((Iso639LanguageDescriptor*)*desc)->getIso639Languages();
404 /* use last language code */
405 for (Iso639LanguageConstIterator i(languages->begin()); i != languages->end(); ++i, ++cnt)
408 audio.language_code = (*i)->getIso639LanguageCode();
410 audio.language_code += "/" + (*i)->getIso639LanguageCode();
414 case STREAM_IDENTIFIER_DESCRIPTOR:
415 audio.component_tag =
416 video.component_tag =
417 ((StreamIdentifierDescriptor*)*desc)->getComponentTag();
421 CaDescriptor *descr = (CaDescriptor*)(*desc);
422 program.caids.insert(descr->getCaSystemId());
433 audio.pid = (*es)->getPid();
435 /* if we find the cached pids, this will be our default stream */
436 if (audio.pid == cached_apid_ac3 || audio.pid == cached_apid_mpeg)
437 program.defaultAudioStream = program.audioStreams.size();
439 /* also, we need to know the first non-mpeg (i.e. "ac3"/dts/...) stream */
440 if ((audio.type != audioStream::atMPEG) && ((first_ac3 == -1) || (audio.pid == cached_apid_ac3)))
441 first_ac3 = program.audioStreams.size();
443 program.audioStreams.push_back(audio);
447 video.pid = (*es)->getPid();
448 if ( !program.videoStreams.empty() && video.pid == cached_vpid )
450 program.videoStreams.push_back(program.videoStreams[0]);
451 program.videoStreams[0] = video;
454 program.videoStreams.push_back(video);
459 for (DescriptorConstIterator desc = pmt.getDescriptors()->begin();
460 desc != pmt.getDescriptors()->end(); ++desc)
462 if ((*desc)->getTag() == CA_DESCRIPTOR)
464 CaDescriptor *descr = (CaDescriptor*)(*desc);
465 program.caids.insert(descr->getCaSystemId());
472 /* finally some fixup: if our default audio stream is an MPEG audio stream,
473 and we have 'defaultac3' set, use the first available ac3 stream instead.
474 (note: if an ac3 audio stream was selected before, this will be also stored
475 in 'fisrt_ac3', so we don't need to worry. */
476 bool defaultac3 = false;
477 std::string default_ac3;
479 if (!ePythonConfigQuery::getConfigValue("config.av.defaultac3", default_ac3))
480 defaultac3 = default_ac3 == "True";
482 if (defaultac3 && (first_ac3 != -1))
483 program.defaultAudioStream = first_ac3;
485 m_cached_program = program;
486 m_have_cached_program = true;
488 } else if ( m_service && !m_service->cacheEmpty() )
490 int cached_pcrpid = m_service->getCacheEntry(eDVBService::cPCRPID),
491 vpidtype = m_service->getCacheEntry(eDVBService::cVTYPE),
493 if ( vpidtype == -1 )
494 vpidtype = videoStream::vtMPEG2;
495 if ( cached_vpid != -1 )
500 program.videoStreams.push_back(s);
503 if ( cached_apid_ac3 != -1 )
506 s.type = audioStream::atAC3;
507 s.pid = cached_apid_ac3;
508 program.audioStreams.push_back(s);
511 if ( cached_apid_mpeg != -1 )
514 s.type = audioStream::atMPEG;
515 s.pid = cached_apid_mpeg;
516 program.audioStreams.push_back(s);
519 if ( cached_pcrpid != -1 )
522 program.pcrPid = cached_pcrpid;
524 if ( cached_tpid != -1 )
527 program.textPid = cached_tpid;
529 CAID_LIST &caids = m_service->m_ca;
530 for (CAID_LIST::iterator it(caids.begin()); it != caids.end(); ++it)
531 program.caids.insert(*it);
538 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
547 int eDVBServicePMTHandler::getDataDemux(ePtr<iDVBDemux> &demux)
556 int eDVBServicePMTHandler::getDecodeDemux(ePtr<iDVBDemux> &demux)
559 /* if we're using the decoding demux as data source
560 (for example in pvr playbacks), return that one. */
561 if (m_use_decode_demux)
567 ASSERT(m_channel); /* calling without a previous ::tune is certainly bad. */
569 ret = m_channel->getDemux(demux, iDVBChannel::capDecode);
571 demux->getCADemuxID(m_decode_demux_num);
576 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
578 pvr_channel = m_pvr_channel;
585 void eDVBServicePMTHandler::SDTScanEvent(int event)
589 case eDVBScan::evtFinish:
591 ePtr<iDVBChannelList> db;
592 if (m_resourceManager->getChannelList(db) != 0)
593 eDebug("no channel list");
597 m_reference.getChannelID(chid);
598 if (chid == m_dvb_scan->getCurrentChannelID())
600 m_dvb_scan->insertInto(db, true);
601 eDebug("sdt update done!");
604 eDebug("ignore sdt update data.... incorrect transponder tuned!!!");
614 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref, int use_decode_demux, eCueSheet *cue, bool simulate, eDVBService *service)
619 m_use_decode_demux = use_decode_demux;
621 /* 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 */
624 /* is this a normal (non PVR) channel? */
625 if (ref.path.empty())
628 ref.getChannelID(chid);
629 res = m_resourceManager->allocateChannel(chid, m_channel, simulate);
631 eDebug("allocate Channel: res %d", res);
633 ePtr<iDVBChannelList> db;
634 if (!m_resourceManager->getChannelList(db))
635 db->getService((eServiceReferenceDVB&)m_reference, m_service);
637 if (!res && !simulate)
638 eDVBCIInterfaces::getInstance()->addPMTHandler(this);
639 } else if (!simulate) // no simulation of playback services
641 eDVBMetaParser parser;
643 int ret=parser.parseFile(ref.path);
644 if (ret || !parser.m_ref.getServiceID().get() /* incorrect sid in meta file or recordings.epl*/ )
646 eWarning("no .meta file found, trying to find PMT pid");
648 if (tstools.openFile(ref.path.c_str()))
649 eWarning("failed to open file");
652 int service_id, pmt_pid;
653 if (!tstools.findPMT(pmt_pid, service_id))
655 eDebug("PMT pid found on pid %04x, service id %d", pmt_pid, service_id);
656 m_reference.setServiceID(service_id);
661 m_reference = parser.m_ref;
665 res = m_resourceManager->allocatePVRChannel(m_pvr_channel);
667 eDebug("allocatePVRChannel failed!\n");
668 m_channel = m_pvr_channel;
675 m_channel->connectStateChange(
676 slot(*this, &eDVBServicePMTHandler::channelStateChanged),
677 m_channelStateChanged_connection);
678 m_last_channel_state = -1;
679 channelStateChanged(m_channel);
681 m_channel->connectEvent(
682 slot(*this, &eDVBServicePMTHandler::channelEvent),
683 m_channelEvent_connection);
685 if (ref.path.empty())
688 m_dvb_scan = new eDVBScan(m_channel, true, false);
689 m_dvb_scan->connectEvent(slot(*this, &eDVBServicePMTHandler::SDTScanEvent), m_scan_event_connection);
693 if (res == eDVBResourceManager::errAllSourcesBusy)
694 serviceEvent(eventNoResources);
695 else /* errChidNotFound, errNoChannelList, errChannelNotInList, errNoSourceFound */
696 serviceEvent(eventMisconfiguration);
702 m_pvr_channel->setCueSheet(cue);
703 m_pvr_channel->playFile(ref.path.c_str());
710 void eDVBServicePMTHandler::free()
716 int demuxes[2] = {0,0};
718 m_demux->getCADemuxID(tmp);
720 if (m_decode_demux_num != 0xFF)
721 demuxes[1]=m_decode_demux_num;
723 demuxes[1]=demuxes[0];
724 ePtr<eTable<ProgramMapSection> > ptr;
725 m_PMT.getCurrent(ptr);
726 eDVBCAService::unregister_service(m_reference, demuxes, ptr);
731 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
735 m_pvr_channel->stopFile();
736 m_pvr_channel->setCueSheet(0);
747 CAServiceMap eDVBCAService::exist;
748 ChannelMap eDVBCAService::exist_channels;
749 ePtr<eConnection> eDVBCAService::m_chanAddedConn;
751 eDVBCAService::eDVBCAService()
752 :m_buffer(512), m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eTimer::create(eApp))
754 memset(m_used_demux, 0xFF, sizeof(m_used_demux));
755 CONNECT(m_retryTimer->timeout, eDVBCAService::sendCAPMT);
759 eDVBCAService::~eDVBCAService()
761 eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
765 // begin static methods
766 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_nums[2], eDVBCAService *&caservice )
768 CAServiceMap::iterator it = exist.find(ref);
769 if ( it != exist.end() )
770 caservice = it->second;
773 caservice = (exist[ref]=new eDVBCAService());
774 caservice->m_service = ref;
775 eDebug("[eDVBCAService] new service %s", ref.toString().c_str() );
778 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
779 for (int i=0; i < loops; ++i)
781 // search free demux entry
782 int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
784 while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
787 if ( iter < max_demux_slots )
789 caservice->m_used_demux[iter] = demux_nums[i] & 0xFF;
790 eDebug("[eDVBCAService] add demux %d to slot %d service %s", caservice->m_used_demux[iter], iter, ref.toString().c_str());
794 eDebug("[eDVBCAService] no more demux slots free for service %s!!", ref.toString().c_str());
801 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_nums[2], eTable<ProgramMapSection> *ptr )
803 CAServiceMap::iterator it = exist.find(ref);
804 if ( it == exist.end() )
806 eDebug("[eDVBCAService] try to unregister non registered %s", ref.toString().c_str());
811 eDVBCAService *caservice = it->second;
812 int loops = demux_nums[0] != demux_nums[1] ? 2 : 1;
813 for (int i=0; i < loops; ++i)
817 used_demux_slots = 0,
818 max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
819 while ( iter < max_demux_slots )
821 if ( caservice->m_used_demux[iter] != 0xFF )
823 if ( !freed && caservice->m_used_demux[iter] == demux_nums[i] )
825 eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
826 caservice->m_used_demux[iter] = 0xFF;
835 eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_nums[i]);
838 if (!used_demux_slots) // no more used.. so we remove it
846 it->second->buildCAPMT(ptr);
848 eDebug("[eDVBCAService] can not send updated demux info");
856 void eDVBCAService::registerChannelCallback(eDVBResourceManager *res_mgr)
858 res_mgr->connectChannelAdded(slot(&DVBChannelAdded), m_chanAddedConn);
861 void eDVBCAService::DVBChannelAdded(eDVBChannel *chan)
865 eDebug("[eDVBCAService] new channel %p!", chan);
866 channel_data *data = new channel_data();
867 data->m_channel = chan;
868 data->m_prevChannelState = -1;
869 data->m_dataDemux = -1;
870 exist_channels[chan] = data;
871 chan->connectStateChange(slot(&DVBChannelStateChanged), data->m_stateChangedConn);
875 void eDVBCAService::DVBChannelStateChanged(iDVBChannel *chan)
877 ChannelMap::iterator it =
878 exist_channels.find(chan);
879 if ( it != exist_channels.end() )
882 chan->getState(state);
883 if ( it->second->m_prevChannelState != state )
887 case iDVBChannel::state_ok:
889 eDebug("[eDVBCAService] channel %p running", chan);
892 case iDVBChannel::state_release:
894 eDebug("[eDVBCAService] remove channel %p", chan);
895 unsigned char msg[8] = { 0x9f,0x80,0x3f,0x04,0x83,0x02,0x00,0x00 };
896 msg[7] = it->second->m_dataDemux & 0xFF;
898 struct sockaddr_un servaddr;
899 memset(&servaddr, 0, sizeof(struct sockaddr_un));
900 servaddr.sun_family = AF_UNIX;
901 strcpy(servaddr.sun_path, "/tmp/camd.socket");
902 clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
903 sock = socket(PF_UNIX, SOCK_STREAM, 0);
906 connect(sock, (struct sockaddr *) &servaddr, clilen);
907 fcntl(sock, F_SETFL, O_NONBLOCK);
909 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
910 if (write(sock, msg, 8) != 8)
911 eDebug("[eDVBCAService] write leave transponder failed!!");
914 exist_channels.erase(it);
919 default: // ignore all other events
923 it->second->m_prevChannelState = state;
928 channel_data *eDVBCAService::getChannelData(eDVBChannelID &chid)
930 for (ChannelMap::iterator it(exist_channels.begin()); it != exist_channels.end(); ++it)
932 if (chid == it->second->m_channel->getChannelID())
937 // end static methods
939 #define CA_REPLY_DEBUG
940 #define MAX_LENGTH_BYTES 4
941 #define MIN_LENGTH_BYTES 1
943 void eDVBCAService::socketCB(int what)
945 if (what & (eSocketNotifier::Read | eSocketNotifier::Priority))
947 char msgbuffer[4096];
948 ssize_t length = read(m_sock, msgbuffer, sizeof(msgbuffer));
951 if (errno != EAGAIN && errno != EINTR && errno != EBUSY)
953 eDebug("[eSocketMMIHandler] read (%m)");
954 what |= eSocketNotifier::Error;
956 } else if (length == 0)
958 what |= eSocketNotifier::Hungup;
962 unsigned char *data = (unsigned char*)msgbuffer;
964 // If a new message starts, then the previous message
965 // should already have been processed. Otherwise the
966 // previous message was incomplete and should therefore
968 if ((len >= 1) && ((data[0] & 0xFF) != 0x9f))
970 if ((len >= 2) && ((data[1] & 0x80) != 0x80))
972 if ((len >= 3) && ((data[2] & 0x80) != 0x00))
977 #ifdef CA_REPLY_DEBUG
978 eDebug("clear buffer");
981 #ifdef CA_REPLY_DEBUG
982 eDebug("Put to buffer:");
983 for (int i=0; i < len; ++i)
984 eDebugNoNewLine("%02x ", data[i]);
985 eDebug("\n--------");
987 m_buffer.write( data, len );
989 while ( m_buffer.size() >= (3 + MIN_LENGTH_BYTES) )
991 unsigned char tmp[3+MAX_LENGTH_BYTES];
992 m_buffer.peek(tmp, 3+MIN_LENGTH_BYTES);
993 if (((tmp[0] & 0xFF) != 0x9f) || ((tmp[1] & 0x80) != 0x80) || ((tmp[2] & 0x80) != 0x00))
996 #ifdef CA_REPLY_DEBUG
997 eDebug("skip %02x", tmp[0]);
1003 int peekLength = (tmp[3] & 0x7f) + 4;
1004 if (m_buffer.size() < peekLength)
1006 m_buffer.peek(tmp, peekLength);
1009 int LengthBytes=eDVBCISession::parseLengthField(tmp+3, size);
1010 int messageLength = 3+LengthBytes+size;
1011 if ( m_buffer.size() >= messageLength )
1013 unsigned char dest[messageLength];
1014 m_buffer.read(dest, messageLength);
1015 #ifdef CA_REPLY_DEBUG
1016 eDebug("dump ca reply:");
1017 for (int i=0; i < messageLength; ++i)
1018 eDebugNoNewLine("%02x ", dest[i]);
1019 eDebug("\n--------");
1021 // /*emit*/ mmi_progress(0, dest, (const void*)(dest+3+LengthBytes), messageLength-3-LengthBytes);
1026 if (what & eSocketNotifier::Hungup) {
1027 /*eDebug("[eDVBCAService] connection closed")*/;
1031 if (what & eSocketNotifier::Error)
1032 eDebug("[eDVBCAService] connection error");
1035 void eDVBCAService::Connect()
1038 memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
1039 m_servaddr.sun_family = AF_UNIX;
1040 strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
1041 m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
1042 m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
1045 if (!connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen))
1048 fcntl(m_sock, F_SETFL, O_NONBLOCK);
1049 setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
1050 m_sn = eSocketNotifier::create(eApp, m_sock,
1051 eSocketNotifier::Read|eSocketNotifier::Priority|eSocketNotifier::Error|eSocketNotifier::Hungup);
1052 CONNECT(m_sn->activated, eDVBCAService::socketCB);
1056 // eDebug("[eDVBCAService] connect failed %m");
1059 eDebug("[eDVBCAService] create socket failed %m");
1062 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
1067 eDVBTableSpec table_spec;
1068 ptr->getSpec(table_spec);
1070 int pmtpid = table_spec.pid,
1071 pmt_version = table_spec.version;
1073 uint8_t demux_mask = 0;
1074 int data_demux = -1;
1076 int iter=0, max_demux_slots = sizeof(m_used_demux);
1077 while ( iter < max_demux_slots )
1079 if ( m_used_demux[iter] != 0xFF )
1081 if ( m_used_demux[iter] > data_demux )
1082 data_demux = m_used_demux[iter];
1083 demux_mask |= (1 << m_used_demux[iter]);
1088 if ( data_demux == -1 )
1090 eDebug("[eDVBCAService] no data demux found for service %s", m_service.toString().c_str() );
1094 eDebug("demux %d mask %02x prevhash %08x", data_demux, demux_mask, m_prev_build_hash);
1096 unsigned int build_hash = ( pmtpid << 16);
1097 build_hash |= (demux_mask << 8);
1098 build_hash |= (pmt_version&0xFF);
1100 if ( build_hash == m_prev_build_hash )
1102 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
1106 std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
1107 if ( i != ptr->getSections().end() )
1109 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
1111 while( i != ptr->getSections().end() )
1113 // eDebug("append");
1117 // add our private descriptors to capmt
1120 tmp[0]=0x84; // pmt pid
1124 capmt.injectDescriptor(tmp, false);
1126 tmp[0] = 0x82; // demux
1128 tmp[2] = demux_mask; // descramble bitmask
1129 tmp[3] = data_demux&0xFF; // read section data from demux number
1130 capmt.injectDescriptor(tmp, false);
1132 tmp[0] = 0x81; // dvbnamespace
1134 tmp[2] = m_service.getDVBNamespace().get()>>24;
1135 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
1136 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
1137 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
1138 tmp[6]=m_service.getTransportStreamID().get()>>8;
1139 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
1140 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
1141 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
1142 capmt.injectDescriptor(tmp, false);
1144 capmt.writeToBuffer(m_capmt);
1147 m_prev_build_hash = build_hash;
1149 if ( m_sendstate != 0xFFFFFFFF )
1154 void eDVBCAService::sendCAPMT()
1156 if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
1163 if ( m_capmt[3] & 0x80 )
1166 int lenbytes = m_capmt[3] & ~0x80;
1168 wp = (wp << 8) | m_capmt[4 + i++];
1178 if ( write(m_sock, m_capmt, wp) == wp )
1180 m_sendstate=0xFFFFFFFF;
1181 eDebug("[eDVBCAService] send %d bytes",wp);
1183 m_service.getChannelID(chid);
1184 channel_data *data = getChannelData(chid);
1187 int lenbytes = m_capmt[3] & 0x80 ? m_capmt[3] & ~0x80 : 0;
1188 data->m_dataDemux = m_capmt[24+lenbytes];
1191 for(int i=0;i<wp;i++)
1192 eDebugNoNewLine("%02x ", m_capmt[i]);
1202 m_retryTimer->start(0,true);
1203 // eDebug("[eDVBCAService] send failed .. immediate retry");
1206 m_retryTimer->start(5000,true);
1207 // eDebug("[eDVBCAService] send failed .. retry in 5 sec");
1214 static PyObject *createTuple(int pid, const char *type)
1216 PyObject *r = PyTuple_New(2);
1217 PyTuple_SET_ITEM(r, 0, PyInt_FromLong(pid));
1218 PyTuple_SET_ITEM(r, 1, PyString_FromString(type));
1222 static inline void PyList_AppendSteal(PyObject *list, PyObject *item)
1224 PyList_Append(list, item);
1228 extern void PutToDict(ePyObject &dict, const char*key, ePyObject item); // defined in dvb/frontend.cpp
1230 PyObject *eDVBServicePMTHandler::program::createPythonObject()
1232 ePyObject r = PyDict_New();
1233 ePyObject l = PyList_New(0);
1235 PyList_AppendSteal(l, createTuple(0, "pat"));
1238 PyList_AppendSteal(l, createTuple(pmtPid, "pmt"));
1240 for (std::vector<eDVBServicePMTHandler::videoStream>::const_iterator
1241 i(videoStreams.begin());
1242 i != videoStreams.end(); ++i)
1243 PyList_AppendSteal(l, createTuple(i->pid, "video"));
1245 for (std::vector<eDVBServicePMTHandler::audioStream>::const_iterator
1246 i(audioStreams.begin());
1247 i != audioStreams.end(); ++i)
1248 PyList_AppendSteal(l, createTuple(i->pid, "audio"));
1250 for (std::vector<eDVBServicePMTHandler::subtitleStream>::const_iterator
1251 i(subtitleStreams.begin());
1252 i != subtitleStreams.end(); ++i)
1253 PyList_AppendSteal(l, createTuple(i->pid, "subtitle"));
1255 PyList_AppendSteal(l, createTuple(pcrPid, "pcr"));
1258 PyList_AppendSteal(l, createTuple(textPid, "text"));
1260 PutToDict(r, "pids", l);