ceddf0ad5cf6f1ef16929ace44860a01d273fe8e
[openblackhole/openblackhole-enigma2.git] / lib / dvb / pmt.cpp
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/cahandler.h>
5 #include <lib/dvb/specs.h>
6 #include <lib/dvb/dvb.h>
7 #include <lib/dvb/metaparser.h>
8 #include <lib/dvb_ci/dvbci.h>
9 #include <lib/dvb/epgcache.h>
10 #include <lib/dvb/scan.h>
11 #include <lib/dvb_ci/dvbci_session.h>
12 #include <dvbsi++/ca_descriptor.h>
13 #include <dvbsi++/ca_program_map_section.h>
14 #include <dvbsi++/teletext_descriptor.h>
15 #include <dvbsi++/descriptor_tag.h>
16 #include <dvbsi++/iso639_language_descriptor.h>
17 #include <dvbsi++/stream_identifier_descriptor.h>
18 #include <dvbsi++/subtitling_descriptor.h>
19 #include <dvbsi++/teletext_descriptor.h>
20 #include <dvbsi++/video_stream_descriptor.h>
21 #include <dvbsi++/registration_descriptor.h>
22 #include <dvbsi++/simple_application_location_descriptor.h>
23 #include <dvbsi++/simple_application_boundary_descriptor.h>
24 #include <dvbsi++/transport_protocol_descriptor.h>
25 #include <dvbsi++/application_name_descriptor.h>
26
27 eDVBServicePMTHandler::eDVBServicePMTHandler()
28         :m_ca_servicePtr(0), m_dvb_scan(0), m_decode_demux_num(0xFF), m_no_pat_entry_delay(eTimer::create())
29 {
30         m_use_decode_demux = 0;
31         m_pmt_pid = -1;
32         m_dsmcc_pid = -1;
33         m_service_type = livetv;
34         eDVBResourceManager::getInstance(m_resourceManager);
35         CONNECT(m_PAT.tableReady, eDVBServicePMTHandler::PATready);
36         CONNECT(m_AIT.tableReady, eDVBServicePMTHandler::AITready);
37         CONNECT(m_OC.tableReady, eDVBServicePMTHandler::OCready);
38         CONNECT(m_no_pat_entry_delay->timeout, eDVBServicePMTHandler::sendEventNoPatEntry);
39 }
40
41 eDVBServicePMTHandler::~eDVBServicePMTHandler()
42 {
43         free();
44 }
45
46 void eDVBServicePMTHandler::channelStateChanged(iDVBChannel *channel)
47 {
48         int state;
49         channel->getState(state);
50
51         if ((m_last_channel_state != iDVBChannel::state_ok)
52                 && (state == iDVBChannel::state_ok))
53         {
54                 if (!m_demux && m_channel)
55                 {
56                         if (m_pvr_demux_tmp)
57                         {
58                                 m_demux = m_pvr_demux_tmp;
59                                 m_pvr_demux_tmp = NULL;
60                         }
61                         else if (m_channel->getDemux(m_demux, (!m_use_decode_demux) ? 0 : iDVBChannel::capDecode))
62                                 eDebug("[eDVBServicePMTHandler] Allocating %s-decoding a demux for now tuned-in channel failed.", m_use_decode_demux ? "" : "non-");
63                 }
64
65                 if (m_demux)
66                 {
67                         eDebug("[eDVBServicePMTHandler] ok ... now we start!!");
68                         m_have_cached_program = false;
69
70                         if (m_service && !m_service->cacheEmpty())
71                         {
72                                 serviceEvent(eventNewProgramInfo);
73                                 if (doDescramble)
74                                 {
75                                         if (!m_ca_servicePtr)
76                                         {
77                                                 registerCAService();
78                                         }
79                                 }
80                         }
81
82                         if (!m_service || m_service->usePMT())
83                         {
84                                 if (m_pmt_pid == -1)
85                                         m_PAT.begin(eApp, eDVBPATSpec(), m_demux);
86                                 else
87                                         m_PMT.begin(eApp, eDVBPMTSpec(m_pmt_pid, m_reference.getServiceID().get()), m_demux);
88                         }
89
90                         serviceEvent(eventTuned);
91                 }
92         } else if ((m_last_channel_state != iDVBChannel::state_failed) &&
93                         (state == iDVBChannel::state_failed))
94         {
95                 eDebug("[eDVBServicePMTHandler] tune failed.");
96                 serviceEvent(eventTuneFailed);
97         }
98 }
99
100 void eDVBServicePMTHandler::channelEvent(iDVBChannel *channel, int event)
101 {
102         switch (event)
103         {
104         case iDVBChannel::evtPreStart:
105                 serviceEvent(eventPreStart);
106                 break;
107         case iDVBChannel::evtEOF:
108                 serviceEvent(eventEOF);
109                 break;
110         case iDVBChannel::evtSOF:
111                 serviceEvent(eventSOF);
112                 break;
113         case iDVBChannel::evtStopped:
114                 serviceEvent(eventStopped);
115                 break;
116         default:
117                 break;
118         }
119 }
120
121 void eDVBServicePMTHandler::registerCAService()
122 {
123         int demuxes[2] = {0, 0};
124         uint8_t demuxid;
125         uint8_t adapterid;
126         m_demux->getCADemuxID(demuxid);
127         m_demux->getCAAdapterID(adapterid);
128         demuxes[0] = demuxid;
129         if (m_decode_demux_num != 0xFF)
130                 demuxes[1] = m_decode_demux_num;
131         else
132                 demuxes[1] = demuxes[0];
133         eDVBCAHandler::getInstance()->registerService(m_reference, adapterid, demuxes, (int)m_service_type, m_ca_servicePtr);
134 }
135
136 void eDVBServicePMTHandler::PMTready(int error)
137 {
138         if (error)
139                 serviceEvent(eventNoPMT);
140         else
141         {
142                 m_have_cached_program = false;
143                 serviceEvent(eventNewProgramInfo);
144                 switch (m_service_type)
145                 {
146                 case livetv:
147                 case recording:
148                 case scrambled_recording:
149                 case timeshift_recording:
150                 case scrambled_timeshift_recording:
151                 case streamserver:
152                 case scrambled_streamserver:
153                 case streamclient:
154                         eEPGCache::getInstance()->PMTready(this);
155                         break;
156                 default:
157                         /* do not start epg caching for other types of services */
158                         break;
159                 }
160                 if (doDescramble)
161                 {
162                         if (!m_ca_servicePtr)
163                         {
164                                 registerCAService();
165                         }
166                         eDVBCIInterfaces::getInstance()->recheckPMTHandlers();
167                         eDVBCIInterfaces::getInstance()->gotPMT(this);
168                 }
169                 if (m_ca_servicePtr)
170                 {
171                         ePtr<eTable<ProgramMapSection> > ptr;
172                         if (!m_PMT.getCurrent(ptr))
173                                 eDVBCAHandler::getInstance()->handlePMT(m_reference, ptr);
174                         else
175                                 eDebug("[eDVBServicePMTHandler] cannot call buildCAPMT");
176                 }
177         }
178 }
179
180 void eDVBServicePMTHandler::sendEventNoPatEntry()
181 {
182         serviceEvent(eventNoPATEntry);
183 }
184
185 void eDVBServicePMTHandler::PATready(int)
186 {
187         eDebug("[eDVBServicePMTHandler] PATready");
188         ePtr<eTable<ProgramAssociationSection> > ptr;
189         if (!m_PAT.getCurrent(ptr))
190         {
191                 int service_id_single = -1;
192                 int pmtpid_single = -1;
193                 int pmtpid = -1;
194                 int cnt=0;
195                 std::vector<ProgramAssociationSection*>::const_iterator i;
196                 for (i = ptr->getSections().begin(); pmtpid == -1 && i != ptr->getSections().end(); ++i)
197                 {
198                         const ProgramAssociationSection &pat = **i;
199                         ProgramAssociationConstIterator program;
200                         for (program = pat.getPrograms()->begin(); pmtpid == -1 && program != pat.getPrograms()->end(); ++program)
201                         {
202                                 if (eServiceID((*program)->getProgramNumber()) == m_reference.getServiceID())
203                                         pmtpid = (*program)->getProgramMapPid();
204                                 if (++cnt == 1 && pmtpid_single == -1 && pmtpid == -1)
205                                 {
206                                         pmtpid_single = (*program)->getProgramMapPid();
207                                         service_id_single = (*program)->getProgramNumber();
208                                 }
209                                 else
210                                         pmtpid_single = service_id_single = -1;
211                         }
212                 }
213                 if (pmtpid_single != -1) // only one PAT entry .. and not valid pmtpid found
214                 {
215                         eDebug("[eDVBServicePMTHandler] use single pat entry!");
216                         m_reference.setServiceID(eServiceID(service_id_single));
217                         pmtpid = pmtpid_single;
218                 }
219                 if (pmtpid == -1) {
220                         eDebug("[eDVBServicePMTHandler] no PAT entry found.. start delay");
221                         m_no_pat_entry_delay->start(1000, true);
222                 }
223                 else {
224                         eDebug("[eDVBServicePMTHandler] use pmtpid %04x for service_id %04x", pmtpid, m_reference.getServiceID().get());
225                         m_no_pat_entry_delay->stop();
226                         m_PMT.begin(eApp, eDVBPMTSpec(pmtpid, m_reference.getServiceID().get()), m_demux);
227                 }
228         } else
229                 serviceEvent(eventNoPAT);
230 }
231
232 void eDVBServicePMTHandler::AITready(int error)
233 {
234         eDebug("[eDVBServicePMTHandler] AITready");
235         ePtr<eTable<ApplicationInformationSection> > ptr;
236         m_aitInfoList.clear();
237         if (!m_AIT.getCurrent(ptr))
238         {
239                 m_HBBTVUrl = "";
240                 for (std::vector<ApplicationInformationSection*>::const_iterator it = ptr->getSections().begin(); it != ptr->getSections().end(); ++it)
241                 {
242                         for (std::list<ApplicationInformation *>::const_iterator i = (*it)->getApplicationInformation()->begin(); i != (*it)->getApplicationInformation()->end(); ++i)
243                         {
244                                 struct aitInfo aitinfo;
245                                 aitinfo.id = ((ApplicationIdentifier*)(*i)->getApplicationIdentifier())->getApplicationId();
246                                 for (DescriptorConstIterator desc = (*i)->getDescriptors()->begin(); desc != (*i)->getDescriptors()->end(); ++desc)
247                                 {
248                                         switch ((*desc)->getTag())
249                                         {
250                                         case APPLICATION_DESCRIPTOR:
251                                                 break;
252                                         case APPLICATION_NAME_DESCRIPTOR:
253                                         {
254                                                 ApplicationNameDescriptor *appname = (ApplicationNameDescriptor*)(*desc);
255                                                 for (ApplicationNameConstIterator appnamesit = appname->getApplicationNames()->begin(); appnamesit != appname->getApplicationNames()->end(); ++appnamesit)
256                                                 {
257                                                         aitinfo.name = (*appnamesit)->getApplicationName();
258                                                         eDebug("[eDVBServicePMTHandler] AIT: %s", aitinfo.name.c_str());
259                                                 }
260                                                 break;
261                                         }
262                                         case TRANSPORT_PROTOCOL_DESCRIPTOR:
263                                         {
264                                                 TransportProtocolDescriptor *transport = (TransportProtocolDescriptor*)(*desc);
265                                                 switch (transport->getProtocolId())
266                                                 {
267                                                 case 1: /* object carousel */
268                                                         if (m_dsmcc_pid >= 0)
269                                                         {
270                                                                 m_OC.begin(eApp, eDVBDSMCCDLDataSpec(m_dsmcc_pid), m_demux);
271                                                         }
272                                                         break;
273                                                 case 2: /* ip */
274                                                         break;
275                                                 case 3: /* interaction */
276                                                         for (InterActionTransportConstIterator interactionit = transport->getInteractionTransports()->begin(); interactionit != transport->getInteractionTransports()->end(); ++interactionit)
277                                                         {
278                                                                 if ((*i)->getApplicationControlCode() == 0x01) /* AUTOSTART */
279                                                                 {
280                                                                         m_HBBTVUrl = (*interactionit)->getUrlBase()->getUrl();
281                                                                 }
282                                                                 aitinfo.url = (*interactionit)->getUrlBase()->getUrl();
283                                                                 break;
284                                                         }
285                                                         break;
286                                                 }
287                                                 break;
288                                         }
289                                         case GRAPHICS_CONSTRAINTS_DESCRIPTOR:
290                                                 break;
291                                         case SIMPLE_APPLICATION_LOCATION_DESCRIPTOR:
292                                         {
293                                                 SimpleApplicationLocationDescriptor *applicationlocation = (SimpleApplicationLocationDescriptor*)(*desc);
294                                                 if ((*i)->getApplicationControlCode() == 0x01) /* AUTOSTART */
295                                                 {
296                                                         m_HBBTVUrl += applicationlocation->getInitialPath();
297                                                 }
298                                                 aitinfo.url += applicationlocation->getInitialPath();
299                                                 m_aitInfoList.push_back(aitinfo);
300                                                 break;
301                                         }
302                                         case APPLICATION_USAGE_DESCRIPTOR:
303                                                 break;
304                                         case SIMPLE_APPLICATION_BOUNDARY_DESCRIPTOR:
305                                                 break;
306                                         }
307                                 }
308                         }
309                 }
310                 if (!m_HBBTVUrl.empty())
311                 {
312                         serviceEvent(eventHBBTVInfo);
313                 }
314         }
315         /* for now, do not keep listening for table updates */
316         m_AIT.stop();
317 }
318
319 void eDVBServicePMTHandler::OCready(int error)
320 {
321         eDebug("[eDVBServicePMTHandler] OCready");
322         ePtr<eTable<OCSection> > ptr;
323         if (!m_OC.getCurrent(ptr))
324         {
325                 std::string data;
326                 for (std::vector<OCSection*>::const_iterator it = ptr->getSections().begin(); it != ptr->getSections().end(); ++it)
327                 {
328                 }
329         }
330         /* for now, do not keep listening for table updates */
331         m_OC.stop();
332 }
333
334 void eDVBServicePMTHandler::getAITApplications(std::map<int, std::string> &aitlist)
335 {
336         for (std::vector<struct aitInfo>::iterator it = m_aitInfoList.begin(); it != m_aitInfoList.end(); ++it)
337         {
338                 aitlist[it->id] = it->url;
339         }
340 }
341
342 void eDVBServicePMTHandler::getCaIds(std::vector<int> &caids, std::vector<int> &ecmpids)
343 {
344         program prog;
345
346         if (!getProgramInfo(prog))
347         {
348                 for (std::list<program::capid_pair>::iterator it = prog.caids.begin(); it != prog.caids.end(); ++it)
349                 {
350                         caids.push_back(it->caid);
351                         ecmpids.push_back(it->capid);
352                 }
353         }
354 }
355
356 int eDVBServicePMTHandler::getProgramInfo(program &program)
357 {
358         ePtr<eTable<ProgramMapSection> > ptr;
359         int cached_apid_ac3 = -1;
360         int cached_apid_ddp = -1;
361         int cached_apid_mpeg = -1;
362         int cached_apid_aache = -1;
363         int cached_vpid = -1;
364         int cached_tpid = -1;
365         int ret = -1;
366         uint8_t adapter, demux;
367
368         if (m_have_cached_program)
369         {
370                 program = m_cached_program;
371                 return 0;
372         }
373
374         eDVBPMTParser::clearProgramInfo(program);
375
376         if ( m_service && !m_service->cacheEmpty() )
377         {
378                 cached_vpid = m_service->getCacheEntry(eDVBService::cVPID);
379                 cached_apid_mpeg = m_service->getCacheEntry(eDVBService::cMPEGAPID);
380                 cached_apid_ac3 = m_service->getCacheEntry(eDVBService::cAC3PID);
381                 cached_apid_ddp = m_service->getCacheEntry(eDVBService::cDDPPID);
382                 cached_apid_aache = m_service->getCacheEntry(eDVBService::cAACHEAPID);
383                 cached_tpid = m_service->getCacheEntry(eDVBService::cTPID);
384         }
385
386         if ( ((m_service && m_service->usePMT()) || !m_service) && eDVBPMTParser::getProgramInfo(program) >= 0)
387         {
388                 unsigned int i;
389                 int first_non_mpeg = -1;
390                 int audio_cached = -1;
391                 int autoaudio_mpeg = -1;
392                 int autoaudio_ac3 = -1;
393                 int autoaudio_ddp = -1;
394                 int autoaudio_aache = -1;
395                 int autoaudio_level = 4;
396
397                 std::string configvalue;
398                 std::vector<std::string> autoaudio_languages;
399                 configvalue = eConfigManager::getConfigValue("config.autolanguage.audio_autoselect1");
400                 if (configvalue != "" && configvalue != "None")
401                         autoaudio_languages.push_back(configvalue);
402                 configvalue = eConfigManager::getConfigValue("config.autolanguage.audio_autoselect2");
403                 if (configvalue != "" && configvalue != "None")
404                         autoaudio_languages.push_back(configvalue);
405                 configvalue = eConfigManager::getConfigValue("config.autolanguage.audio_autoselect3");
406                 if (configvalue != "" && configvalue != "None")
407                         autoaudio_languages.push_back(configvalue);
408                 configvalue = eConfigManager::getConfigValue("config.autolanguage.audio_autoselect4");
409                 if (configvalue != "" && configvalue != "None")
410                         autoaudio_languages.push_back(configvalue);
411
412                 int autosub_txt_normal = -1;
413                 int autosub_txt_hearing = -1;
414                 int autosub_dvb_normal = -1;
415                 int autosub_dvb_hearing = -1;
416                 int autosub_level =4;
417
418                 std::vector<std::string> autosub_languages;
419                 configvalue = eConfigManager::getConfigValue("config.autolanguage.subtitle_autoselect1");
420                 if (configvalue != "" && configvalue != "None")
421                         autosub_languages.push_back(configvalue);
422                 configvalue = eConfigManager::getConfigValue("config.autolanguage.subtitle_autoselect2");
423                 if (configvalue != "" && configvalue != "None")
424                         autosub_languages.push_back(configvalue);
425                 configvalue = eConfigManager::getConfigValue("config.autolanguage.subtitle_autoselect3");
426                 if (configvalue != "" && configvalue != "None")
427                         autosub_languages.push_back(configvalue);
428                 configvalue = eConfigManager::getConfigValue("config.autolanguage.subtitle_autoselect4");
429                 if (configvalue != "" && configvalue != "None")
430                         autosub_languages.push_back(configvalue);
431
432                 m_dsmcc_pid = program.dsmccPid;
433                 if (program.aitPid >= 0)
434                 {
435                         m_AIT.begin(eApp, eDVBAITSpec(program.aitPid), m_demux);
436                 }
437
438                 for (i = 0; i < program.videoStreams.size(); i++)
439                 {
440                         if (program.videoStreams[i].pid == cached_vpid)
441                         {
442                                 /* put cached vpid at the front of the videoStreams vector */
443                                 if (i > 0)
444                                 {
445                                         videoStream tmp = program.videoStreams[i];
446                                         program.videoStreams[i] = program.videoStreams[0];
447                                         program.videoStreams[0] = tmp;
448                                 }
449                                 break;
450                         }
451                 }
452                 for (i = 0; i < program.audioStreams.size(); i++)
453                 {
454                         if (program.audioStreams[i].pid == cached_apid_ac3
455                          || program.audioStreams[i].pid == cached_apid_ddp
456                          || program.audioStreams[i].pid == cached_apid_mpeg
457                          || program.audioStreams[i].pid == cached_apid_aache)
458                         {
459                                 /* if we find the cached pids, this will be our default stream */
460                                 audio_cached = i;
461                         }
462                         /* also, we need to know the first non-mpeg (i.e. "ac3"/dts/...) stream */
463                         if ((program.audioStreams[i].type != audioStream::atMPEG) && ((first_non_mpeg == -1)
464                                 || (program.audioStreams[i].pid == cached_apid_ac3)
465                                 || (program.audioStreams[i].pid == cached_apid_ddp)
466                                 || (program.audioStreams[i].pid == cached_apid_aache)))
467                         {
468                                 first_non_mpeg = i;
469                         }
470                         if (!program.audioStreams[i].language_code.empty())
471                         {
472                                 int x = 1;
473                                 for (std::vector<std::string>::iterator it = autoaudio_languages.begin();x <= autoaudio_level && it != autoaudio_languages.end();x++,it++)
474                                 {
475                                         if ((*it).find(program.audioStreams[i].language_code) != std::string::npos)
476                                         {
477                                                 if (program.audioStreams[i].type == audioStream::atMPEG && (autoaudio_level > x || autoaudio_mpeg == -1))
478                                                         autoaudio_mpeg = i;
479                                                 else if (program.audioStreams[i].type == audioStream::atAC3 && (autoaudio_level > x || autoaudio_ac3 == -1))
480                                                         autoaudio_ac3 = i;
481                                                 else if (program.audioStreams[i].type == audioStream::atDDP && (autoaudio_level > x || autoaudio_ddp == -1))
482                                                         autoaudio_ddp = i;
483                                                 else if (program.audioStreams[i].type == audioStream::atAACHE && (autoaudio_level > x || autoaudio_aache == -1))
484                                                         autoaudio_aache = i;
485                                                 autoaudio_level = x;
486                                                 break;
487                                         }
488                                 }
489                         }
490                 }
491                 for (i = 0; i < program.subtitleStreams.size(); i++)
492                 {
493                         if (!program.subtitleStreams[i].language_code.empty())
494                         {
495                                 int x = 1;
496                                 for (std::vector<std::string>::iterator it2 = autosub_languages.begin();x <= autosub_level && it2 != autosub_languages.end();x++,it2++)
497                                 {
498                                         if ((*it2).find(program.subtitleStreams[i].language_code) != std::string::npos)
499                                         {
500                                                 autosub_level = x;
501                                                 if (program.subtitleStreams[i].subtitling_type >= 0x10)
502                                                 {
503                                                         /* DVB subs */
504                                                         if (program.subtitleStreams[i].subtitling_type >= 0x20)
505                                                                 autosub_dvb_hearing = i;
506                                                         else
507                                                                 autosub_dvb_normal = i;
508                                                 }
509                                                 else
510                                                 {
511                                                         /* TXT subs */
512                                                         if (program.subtitleStreams[i].subtitling_type == 0x05)
513                                                                 autosub_txt_hearing = i;
514                                                         else
515                                                                 autosub_txt_normal = i;
516                                                 }
517                                                 break;
518                                         }
519                                 }
520                         }
521                 }
522
523                 bool defaultac3 = eConfigManager::getConfigBoolValue("config.autolanguage.audio_defaultac3");
524                 bool defaultddp = eConfigManager::getConfigBoolValue("config.autolanguage.audio_defaultddp");
525                 bool useaudio_cache = eConfigManager::getConfigBoolValue("config.autolanguage.audio_usecache");
526
527                 if (useaudio_cache && audio_cached != -1)
528                         program.defaultAudioStream = audio_cached;
529                 else if (defaultac3 && autoaudio_ac3 != -1)
530                         program.defaultAudioStream = autoaudio_ac3;
531                 else if (defaultddp && autoaudio_ddp != -1)
532                         program.defaultAudioStream = autoaudio_ddp;
533                 else
534                 {
535                         if (autoaudio_mpeg != -1)
536                                 program.defaultAudioStream = autoaudio_mpeg;
537                         else if (autoaudio_ac3 != -1)
538                                 program.defaultAudioStream = autoaudio_ac3;
539                         else if (autoaudio_ddp != -1)
540                                 program.defaultAudioStream = autoaudio_ddp;
541                         else if (autoaudio_aache != -1)
542                                 program.defaultAudioStream = autoaudio_aache;
543                         else if (first_non_mpeg != -1)
544                                 program.defaultAudioStream = first_non_mpeg;
545                 }
546
547                 bool allow_hearingimpaired = eConfigManager::getConfigBoolValue("config.autolanguage.subtitle_hearingimpaired");
548                 bool default_hearingimpaired = eConfigManager::getConfigBoolValue("config.autolanguage.subtitle_defaultimpaired");
549                 bool defaultdvb = eConfigManager::getConfigBoolValue("config.autolanguage.subtitle_defaultdvb");
550                 int equallanguagemask = eConfigManager::getConfigIntValue("config.autolanguage.equal_languages");
551
552                 if (defaultdvb)
553                 {
554                         if (allow_hearingimpaired && default_hearingimpaired && autosub_dvb_hearing != -1)
555                                 program.defaultSubtitleStream = autosub_dvb_hearing;
556                         else if (autosub_dvb_normal != -1)
557                                 program.defaultSubtitleStream = autosub_dvb_normal;
558                         else if (allow_hearingimpaired && autosub_dvb_hearing != -1)
559                                 program.defaultSubtitleStream = autosub_dvb_hearing;
560                         else if (allow_hearingimpaired && default_hearingimpaired && autosub_txt_hearing != -1)
561                                 program.defaultSubtitleStream = autosub_txt_hearing;
562                         else if (autosub_txt_normal != -1)
563                                 program.defaultSubtitleStream = autosub_txt_normal;
564                         else if (allow_hearingimpaired && autosub_txt_hearing != -1)
565                                 program.defaultSubtitleStream = autosub_txt_hearing;
566                 }
567                 else
568                 {
569                         if (allow_hearingimpaired && default_hearingimpaired && autosub_txt_hearing != -1)
570                                 program.defaultSubtitleStream = autosub_txt_hearing;
571                         else if (autosub_txt_normal != -1)
572                                 program.defaultSubtitleStream = autosub_txt_normal;
573                         else if (allow_hearingimpaired && autosub_txt_hearing != -1)
574                                 program.defaultSubtitleStream = autosub_txt_hearing;
575                         else if (allow_hearingimpaired && default_hearingimpaired && autosub_dvb_hearing != -1)
576                                 program.defaultSubtitleStream = autosub_dvb_hearing;
577                         else if (autosub_dvb_normal != -1)
578                                 program.defaultSubtitleStream = autosub_dvb_normal;
579                         else if (allow_hearingimpaired && autosub_dvb_hearing != -1)
580                                 program.defaultSubtitleStream = autosub_dvb_hearing;
581                 }
582                 if (program.defaultSubtitleStream != -1 && (equallanguagemask & (1<<(autosub_level-1))) == 0 && program.subtitleStreams[program.defaultSubtitleStream].language_code.compare(program.audioStreams[program.defaultAudioStream].language_code) == 0 )
583                         program.defaultSubtitleStream = -1;
584
585                 ret = 0;
586         }
587         else if ( m_service && !m_service->cacheEmpty() )
588         {
589                 int cached_pcrpid = m_service->getCacheEntry(eDVBService::cPCRPID),
590                         vpidtype = m_service->getCacheEntry(eDVBService::cVTYPE),
591                         cnt=0;
592                 if ( vpidtype == -1 )
593                         vpidtype = videoStream::vtMPEG2;
594                 if ( cached_vpid != -1 )
595                 {
596                         videoStream s;
597                         s.pid = cached_vpid;
598                         s.type = vpidtype;
599                         program.videoStreams.push_back(s);
600                         ++cnt;
601                 }
602                 if ( cached_apid_ac3 != -1 )
603                 {
604                         audioStream s;
605                         s.type = audioStream::atAC3;
606                         s.pid = cached_apid_ac3;
607                         s.rdsPid = -1;
608                         program.audioStreams.push_back(s);
609                         ++cnt;
610                 }
611                 if ( cached_apid_ddp != -1 )
612                 {
613                         audioStream s;
614                         s.type = audioStream::atDDP;
615                         s.pid = cached_apid_ddp;
616                         s.rdsPid = -1;
617                         program.audioStreams.push_back(s);
618                         ++cnt;
619                 }
620                 if ( cached_apid_aache != -1 )
621                 {
622                         audioStream s;
623                         s.type = audioStream::atAACHE;
624                         s.pid = cached_apid_aache;
625                         s.rdsPid = -1;
626                         program.audioStreams.push_back(s);
627                         ++cnt;
628                 }
629                 if ( cached_apid_mpeg != -1 )
630                 {
631                         audioStream s;
632                         s.type = audioStream::atMPEG;
633                         s.pid = cached_apid_mpeg;
634                         s.rdsPid = -1;
635                         program.audioStreams.push_back(s);
636                         ++cnt;
637                 }
638                 if ( cached_pcrpid != -1 )
639                 {
640                         ++cnt;
641                         program.pcrPid = cached_pcrpid;
642                 }
643                 if ( cached_tpid != -1 )
644                 {
645                         ++cnt;
646                         program.textPid = cached_tpid;
647                 }
648                 CAID_LIST &caids = m_service->m_ca;
649                 for (CAID_LIST::iterator it(caids.begin()); it != caids.end(); ++it) {
650                         program::capid_pair pair;
651                         pair.caid = *it;
652                         pair.capid = -1; // not known yet
653                         program.caids.push_back(pair);
654                 }
655                 if ( cnt )
656                         ret = 0;
657         }
658
659         if (m_demux)
660         {
661                 m_demux->getCAAdapterID(adapter);
662                 program.adapterId = adapter;
663                 m_demux->getCADemuxID(demux);
664                 program.demuxId = demux;
665         }
666
667         m_cached_program = program;
668         m_have_cached_program = true;
669         return ret;
670 }
671
672 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
673 {
674         channel = m_channel;
675         if (channel)
676                 return 0;
677         else
678                 return -1;
679 }
680
681 int eDVBServicePMTHandler::getDataDemux(ePtr<iDVBDemux> &demux)
682 {
683         demux = m_demux;
684         if (demux)
685                 return 0;
686         else
687                 return -1;
688 }
689
690 int eDVBServicePMTHandler::getDecodeDemux(ePtr<iDVBDemux> &demux)
691 {
692         int ret=0;
693                 /* if we're using the decoding demux as data source
694                    (for example in pvr playbacks), return that one. */
695         if (m_use_decode_demux)
696         {
697                 demux = m_demux;
698                 return ret;
699         }
700
701         ASSERT(m_channel); /* calling without a previous ::tune is certainly bad. */
702
703         ret = m_channel->getDemux(demux, iDVBChannel::capDecode);
704         if (!ret)
705                 demux->getCADemuxID(m_decode_demux_num);
706
707         return ret;
708 }
709
710 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
711 {
712         pvr_channel = m_pvr_channel;
713         if (pvr_channel)
714                 return 0;
715         else
716                 return -1;
717 }
718
719 void eDVBServicePMTHandler::SDTScanEvent(int event)
720 {
721         switch (event)
722         {
723                 case eDVBScan::evtFinish:
724                 {
725                         ePtr<iDVBChannelList> db;
726                         if (m_resourceManager->getChannelList(db) != 0)
727                                 eDebug("[eDVBServicePMTHandler] no channel list");
728                         else
729                         {
730                                 eDVBChannelID chid;
731                                 m_reference.getChannelID(chid);
732                                 if (chid == m_dvb_scan->getCurrentChannelID())
733                                 {
734                                         m_dvb_scan->insertInto(db, true);
735                                         eDebug("[eDVBServicePMTHandler] sdt update done!");
736                                 }
737                                 else
738                                         eDebug("[eDVBServicePMTHandler] ignore sdt update data.... incorrect transponder tuned!!!");
739                         }
740                         break;
741                 }
742
743                 default:
744                         break;
745         }
746 }
747
748 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref, int use_decode_demux, eCueSheet *cue, bool simulate, eDVBService *service, serviceType type, bool descramble)
749 {
750         ePtr<iTsSource> s;
751         return tuneExt(ref, use_decode_demux, s, NULL, cue, simulate, service, type, descramble);
752 }
753
754 int eDVBServicePMTHandler::tuneExt(eServiceReferenceDVB &ref, int use_decode_demux, ePtr<iTsSource> &source, const char *streaminfo_file, eCueSheet *cue, bool simulate, eDVBService *service, serviceType type, bool descramble)
755 {
756         RESULT res=0;
757         m_reference = ref;
758         m_use_decode_demux = use_decode_demux;
759         m_no_pat_entry_delay->stop();
760         m_service_type = type;
761
762         doDescramble = descramble;
763
764                 /* 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 */
765         m_service = service;
766
767                 /* is this a normal (non PVR) channel? */
768         if (ref.path.empty())
769         {
770                 eDVBChannelID chid;
771                 ref.getChannelID(chid);
772                 res = m_resourceManager->allocateChannel(chid, m_channel, simulate);
773                 if (!simulate)
774                         eDebug("[eDVBServicePMTHandler] allocate Channel: res %d", res);
775
776                 ePtr<iDVBChannelList> db;
777                 if (!m_resourceManager->getChannelList(db))
778                         db->getService((eServiceReferenceDVB&)m_reference, m_service);
779
780                 if (!res && !simulate)
781                         eDVBCIInterfaces::getInstance()->addPMTHandler(this);
782         } else if (!simulate) // no simulation of playback services
783         {
784                 if (!ref.getServiceID().get() /* incorrect sid in meta file or recordings.epl*/ )
785                 {
786                         eDVBTSTools tstools;
787                         bool b = source || !tstools.openFile(ref.path.c_str(), 1);
788                         eWarning("[eDVBServicePMTHandler] no .meta file found, trying to find PMT pid");
789                         if (source)
790                                 tstools.setSource(source, NULL);
791                         if (b)
792                         {
793                                 eDVBPMTParser::program program;
794                                 if (!tstools.findPMT(program))
795                                 {
796                                         m_pmt_pid = program.pmtPid;
797                                         eDebug("[eDVBServicePMTHandler] PMT pid %04x, service id %d", m_pmt_pid, program.serviceId);
798                                         m_reference.setServiceID(program.serviceId);
799                                 }
800                         }
801                         else
802                                 eWarning("[eDVBServicePMTHandler] no valid source to find PMT pid!");
803                 }
804                 eDebug("[eDVBServicePMTHandler] alloc PVR");
805                         /* allocate PVR */
806                 eDVBChannelID chid;
807                 if (m_service_type == streamclient) ref.getChannelID(chid);
808                 res = m_resourceManager->allocatePVRChannel(chid, m_pvr_channel);
809                 if (res)
810                         eDebug("[eDVBServicePMTHandler] allocatePVRChannel failed!\n");
811                 m_channel = m_pvr_channel;
812         }
813
814         if (!simulate)
815         {
816                 if (m_channel)
817                 {
818                         m_channel->connectStateChange(
819                                 slot(*this, &eDVBServicePMTHandler::channelStateChanged),
820                                 m_channelStateChanged_connection);
821                         m_last_channel_state = -1;
822                         channelStateChanged(m_channel);
823
824                         m_channel->connectEvent(
825                                 slot(*this, &eDVBServicePMTHandler::channelEvent),
826                                 m_channelEvent_connection);
827
828                         if (ref.path.empty())
829                         {
830                                 m_dvb_scan = new eDVBScan(m_channel, true, false);
831                                 if (!eConfigManager::getConfigBoolValue("config.misc.disable_background_scan"))
832                                 {
833                                         /*
834                                          * not starting a dvb scan triggers what appears to be a
835                                          * refcount bug (channel?/demux?), so we always start a scan,
836                                          * but ignore the results when background scanning is disabled
837                                          */
838                                         m_dvb_scan->connectEvent(slot(*this, &eDVBServicePMTHandler::SDTScanEvent), m_scan_event_connection);
839                                 }
840                         }
841                 } else
842                 {
843                         if (res == eDVBResourceManager::errAllSourcesBusy)
844                                 serviceEvent(eventNoResources);
845                         else /* errChidNotFound, errNoChannelList, errChannelNotInList, errNoSourceFound */
846                                 serviceEvent(eventMisconfiguration);
847                         return res;
848                 }
849
850                 if (m_pvr_channel)
851                 {
852                         m_pvr_channel->setCueSheet(cue);
853
854                         if (m_pvr_channel->getDemux(m_pvr_demux_tmp, (!m_use_decode_demux) ? 0 : iDVBChannel::capDecode))
855                                 eDebug("[eDVBServicePMTHandler] Allocating %s-decoding a demux for PVR channel failed.", m_use_decode_demux ? "" : "non-");
856                         else if (source)
857                                 m_pvr_channel->playSource(source, streaminfo_file);
858                         else
859                                 m_pvr_channel->playFile(ref.path.c_str());
860
861                         if (m_service_type == offline)
862                         {
863                                 m_pvr_channel->setOfflineDecodeMode(eConfigManager::getConfigIntValue("config.recording.offline_decode_delay"));
864                         }
865                 }
866         }
867
868         return res;
869 }
870
871 void eDVBServicePMTHandler::free()
872 {
873         m_dvb_scan = 0;
874
875         if (m_ca_servicePtr)
876         {
877                 int demuxes[2] = {0,0};
878                 uint8_t demuxid;
879                 uint8_t adapterid;
880                 m_demux->getCADemuxID(demuxid);
881                 m_demux->getCAAdapterID(adapterid);
882                 demuxes[0]=demuxid;
883                 if (m_decode_demux_num != 0xFF)
884                         demuxes[1]=m_decode_demux_num;
885                 else
886                         demuxes[1]=demuxes[0];
887                 ePtr<eTable<ProgramMapSection> > ptr;
888                 m_PMT.getCurrent(ptr);
889                 eDVBCAHandler::getInstance()->unregisterService(m_reference, adapterid, demuxes, ptr);
890                 m_ca_servicePtr = 0;
891         }
892
893         if (m_channel)
894                 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
895
896         if (m_pvr_channel)
897         {
898                 m_pvr_channel->stop();
899                 m_pvr_channel->setCueSheet(0);
900         }
901
902         m_OC.stop();
903         m_AIT.stop();
904         m_PMT.stop();
905         m_PAT.stop();
906         m_service = 0;
907         m_channel = 0;
908         m_pvr_channel = 0;
909         m_demux = 0;
910 }