Merge branch 'master' of /home/tmbinc/enigma2-git
[enigma2.git] / lib / dvb_ci / dvbci.cpp
1 #include <fcntl.h>
2 #include <sys/ioctl.h>
3
4 #include <lib/base/init.h>
5 #include <lib/base/init_num.h>
6 #include <lib/base/ebase.h>
7
8 #include <lib/base/eerror.h>
9 #include <lib/base/nconfig.h> // access to python config
10 #include <lib/dvb/db.h>
11 #include <lib/dvb/pmt.h>
12 #include <lib/dvb_ci/dvbci.h>
13 #include <lib/dvb_ci/dvbci_session.h>
14 #include <lib/dvb_ci/dvbci_camgr.h>
15 #include <lib/dvb_ci/dvbci_ui.h>
16 #include <lib/dvb_ci/dvbci_appmgr.h>
17 #include <lib/dvb_ci/dvbci_mmi.h>
18
19 #include <dvbsi++/ca_program_map_section.h>
20
21 //#define CIDEBUG 1
22
23 #ifdef CIDEBUG
24         #define eDebugCI(x...) eDebug(x)
25 #else
26         #define eDebugCI(x...)
27 #endif
28
29 eDVBCIInterfaces *eDVBCIInterfaces::instance = 0;
30
31 eDVBCIInterfaces::eDVBCIInterfaces()
32 {
33         int num_ci = 0;
34         
35         instance = this;
36         
37         eDebug("scanning for common interfaces..");
38
39         while (1)
40         {
41                 struct stat s;
42                 char filename[128];
43                 sprintf(filename, "/dev/ci%d", num_ci);
44
45                 if (stat(filename, &s))
46                         break;
47
48                 ePtr<eDVBCISlot> cislot;
49
50                 cislot = new eDVBCISlot(eApp, num_ci);
51                 m_slots.push_back(cislot);
52
53                 ++num_ci;
54         }
55
56         for (eSmartPtrList<eDVBCISlot>::iterator it(m_slots.begin()); it != m_slots.end(); ++it)
57                 it->setSource(TUNER_A);
58
59         if (num_ci > 1) // // FIXME .. we force DM8000 when more than one CI Slot is avail
60         {
61                 setInputSource(0, TUNER_A);
62                 setInputSource(1, TUNER_B);
63                 setInputSource(2, TUNER_C);
64                 setInputSource(3, TUNER_D);
65         }
66         else
67         {
68                 setInputSource(0, TUNER_A);
69                 setInputSource(1, TUNER_B);
70         }
71
72         eDebug("done, found %d common interface slots", num_ci);
73 }
74
75 eDVBCIInterfaces::~eDVBCIInterfaces()
76 {
77 }
78
79 eDVBCIInterfaces *eDVBCIInterfaces::getInstance()
80 {
81         return instance;
82 }
83
84 eDVBCISlot *eDVBCIInterfaces::getSlot(int slotid)
85 {
86         for(eSmartPtrList<eDVBCISlot>::iterator i(m_slots.begin()); i != m_slots.end(); ++i)
87                 if(i->getSlotID() == slotid)
88                         return i;
89
90         eDebug("FIXME: request for unknown slot");
91                         
92         return 0;
93 }
94
95 int eDVBCIInterfaces::getSlotState(int slotid)
96 {
97         eDVBCISlot *slot;
98
99         if( (slot = getSlot(slotid)) == 0 )
100                 return eDVBCISlot::stateInvalid;
101
102         return slot->getState();
103 }
104
105 int eDVBCIInterfaces::reset(int slotid)
106 {
107         eDVBCISlot *slot;
108
109         if( (slot = getSlot(slotid)) == 0 )
110                 return -1;
111
112         return slot->reset();
113 }
114
115 int eDVBCIInterfaces::initialize(int slotid)
116 {
117         eDVBCISlot *slot;
118
119         if( (slot = getSlot(slotid)) == 0 )
120                 return -1;
121
122         slot->removeService();
123
124         return sendCAPMT(slotid);
125 }
126
127 int eDVBCIInterfaces::sendCAPMT(int slotid)
128 {
129         eDVBCISlot *slot;
130
131         if( (slot = getSlot(slotid)) == 0 )
132                 return -1;
133
134         PMTHandlerList::iterator it = m_pmt_handlers.begin();
135         while (it != m_pmt_handlers.end())
136         {
137                 eDVBCISlot *tmp = it->cislot;
138                 while (tmp && tmp != slot)
139                         tmp = tmp->linked_next;
140                 if (tmp)
141                 {
142                         tmp->sendCAPMT(it->pmthandler);  // send capmt
143                         break;
144                 }
145                 ++it;
146         }
147
148         return 0;
149 }
150
151 int eDVBCIInterfaces::startMMI(int slotid)
152 {
153         eDVBCISlot *slot;
154
155         if( (slot = getSlot(slotid)) == 0 )
156                 return -1;
157         
158         return slot->startMMI();
159 }
160
161 int eDVBCIInterfaces::stopMMI(int slotid)
162 {
163         eDVBCISlot *slot;
164
165         if( (slot = getSlot(slotid)) == 0 )
166                 return -1;
167         
168         return slot->stopMMI();
169 }
170
171 int eDVBCIInterfaces::answerText(int slotid, int answer)
172 {
173         eDVBCISlot *slot;
174
175         if( (slot = getSlot(slotid)) == 0 )
176                 return -1;
177         
178         return slot->answerText(answer);
179 }
180
181 int eDVBCIInterfaces::answerEnq(int slotid, char *value)
182 {
183         eDVBCISlot *slot;
184
185         if( (slot = getSlot(slotid)) == 0 )
186                 return -1;
187         
188         return slot->answerEnq(value);
189 }
190
191 int eDVBCIInterfaces::cancelEnq(int slotid)
192 {
193         eDVBCISlot *slot;
194
195         if( (slot = getSlot(slotid)) == 0 )
196                 return -1;
197         
198         return slot->cancelEnq();
199 }
200
201 void eDVBCIInterfaces::ciRemoved(eDVBCISlot *slot)
202 {
203         eDebug("CI Slot %d: removed... usecount %d", slot->getSlotID(), slot->use_count);
204         for (PMTHandlerList::iterator it(m_pmt_handlers.begin());
205                 it != m_pmt_handlers.end(); ++it)
206         {
207                 eServiceReferenceDVB ref;
208                 it->pmthandler->getServiceReference(ref);
209                 eDebugCI("check %s cislot %p %d\n", ref.toString().c_str(), it->cislot, it->cislot?it->cislot->getSlotID() : -1);
210                 slot->removeService(ref.getServiceID().get());
211                 if (slot->use_count && !--slot->use_count)
212                 {
213                         if (slot->linked_next)
214                                 slot->linked_next->setSource(slot->current_source);
215                         else // last CI in chain
216                                 setInputSource(slot->current_tuner, slot->current_source);
217
218                         if (it->cislot == slot) // remove the base slot
219                         {
220                                 it->cislot = slot->linked_next;
221                                 eDebugCI("base removed.. so slot is now %p", it->cislot);
222                         }
223                         else
224                         {
225                                 eDebugCI("not base removed.. %d", it->cislot->getSlotID());
226                                 eDVBCISlot *tmp = it->cislot;
227                                 while(tmp->linked_next != slot)
228                                         tmp = tmp->linked_next;
229                                 ASSERT(tmp);
230                                 if (slot->linked_next)
231                                         tmp->linked_next = slot->linked_next;
232                                 else
233                                         tmp->linked_next = 0;
234                         }
235                         slot->linked_next=0;
236                         slot->user_mapped=false;
237                 }
238         }
239         recheckPMTHandlers();
240 }
241
242 static bool canDescrambleMultipleServices(int slotid)
243 {
244         char configStr[255];
245         snprintf(configStr, 255, "config.ci.%d.canDescrambleMultipleServices", slotid);
246         std::string str;
247         ePythonConfigQuery::getConfigValue(configStr, str);
248         if ( str == "auto" )
249         {
250                 std::string appname = eDVBCI_UI::getInstance()->getAppName(slotid);
251                 if (appname.find("AlphaCrypt") != std::string::npos)
252                         return true;
253         }
254         else if (str == "yes")
255                 return true;
256         return false;
257 }
258
259 void eDVBCIInterfaces::recheckPMTHandlers()
260 {
261         eDebugCI("recheckPMTHAndlers()");
262         for (PMTHandlerList::iterator it(m_pmt_handlers.begin());
263                 it != m_pmt_handlers.end(); ++it)
264         {
265                 CAID_LIST caids;
266                 ePtr<eDVBService> service;
267                 eServiceReferenceDVB ref;
268                 eDVBCISlot *tmp = it->cislot;
269                 eDVBServicePMTHandler *pmthandler = it->pmthandler;
270                 eDVBServicePMTHandler::program p;
271                 bool first_plugged_cis_exist = false;
272
273                 pmthandler->getServiceReference(ref);
274                 pmthandler->getService(service);
275
276                 eDebugCI("recheck %p %s", pmthandler, ref.toString().c_str());
277                 for (eSmartPtrList<eDVBCISlot>::iterator ci_it(m_slots.begin()); ci_it != m_slots.end(); ++ci_it)
278                         if (ci_it->first_plugged && ci_it->getCAManager())
279                         {
280                                 eDebug("Slot %d first plugged", ci_it->getSlotID());
281                                 ci_it->first_plugged = false;
282                                 first_plugged_cis_exist = true;
283                         }
284
285                 // check if this pmt handler has already assigned CI(s) .. and this CI(s) are already running
286                 if (!first_plugged_cis_exist)
287                 {
288                         while(tmp)
289                         {
290                                 if (!tmp->running_services.empty())
291                                         break;
292                                 tmp=tmp->linked_next;
293                         }
294                         if (tmp) // we dont like to change tsmux for running services
295                         {
296                                 eDebugCI("already assigned and running CI!\n");
297                                 continue;
298                         }
299                 }
300
301                 if (!pmthandler->getProgramInfo(p))
302                 {
303                         int cnt=0;
304                         for (caidSet::reverse_iterator x(p.caids.rbegin()); x != p.caids.rend(); ++x, ++cnt)
305                                 caids.push_front(*x);
306                         if (service && cnt)
307                                 service->m_ca = caids;
308                 }
309
310                 if (service)
311                         caids = service->m_ca;
312
313                 if (caids.empty())
314                         continue; // unscrambled service
315
316                 for (eSmartPtrList<eDVBCISlot>::iterator ci_it(m_slots.begin()); ci_it != m_slots.end(); ++ci_it)
317                 {
318                         eDebugCI("check Slot %d", ci_it->getSlotID());
319                         bool useThis=false;
320                         bool user_mapped=true;
321                         eDVBCICAManagerSession *ca_manager = ci_it->getCAManager();
322
323                         if (ca_manager)
324                         {
325                                 int mask=0;
326                                 if (!ci_it->possible_services.empty())
327                                 {
328                                         mask |= 1;
329                                         serviceSet::iterator it = ci_it->possible_services.find(ref);
330                                         if (it != ci_it->possible_services.end())
331                                         {
332                                                 eDebug("'%s' is in service list of slot %d... so use it", ref.toString().c_str(), ci_it->getSlotID());
333                                                 useThis = true;
334                                         }
335                                 }
336                                 if (!useThis && !ci_it->possible_providers.empty())
337                                 {
338                                         eDVBNamespace ns = ref.getDVBNamespace();
339                                         mask |= 2;
340                                         if (!service) // subservice?
341                                         {
342                                                 eServiceReferenceDVB parent_ref = ref.getParentServiceReference();
343                                                 eDVBDB::getInstance()->getService(parent_ref, service);
344                                         }
345                                         if (service)
346                                         {
347                                                 providerSet::iterator it = ci_it->possible_providers.find(providerPair(service->m_provider_name, ns.get()));
348                                                 if (it != ci_it->possible_providers.end())
349                                                 {
350                                                         eDebug("'%s/%08x' is in provider list of slot %d... so use it", service->m_provider_name.c_str(), ns.get(), ci_it->getSlotID());
351                                                         useThis = true;
352                                                 }
353                                         }
354                                 }
355                                 if (!useThis && !ci_it->possible_caids.empty())
356                                 {
357                                         for (CAID_LIST::iterator ca(caids.begin()); ca != caids.end(); ++ca)
358                                         {
359                                                 caidSet::iterator it = ci_it->possible_caids.find(*ca);
360                                                 if (it != ci_it->possible_caids.end())
361                                                 {
362                                                         eDebug("caid '%04x' is in caid list of slot %d... so use it", *ca, ci_it->getSlotID());
363                                                         useThis = true;
364                                                         break;
365                                                 }
366                                         }
367                                 }
368                                 if (!useThis && !mask)
369                                 {
370                                         const std::vector<uint16_t> &ci_caids = ca_manager->getCAIDs();
371                                         for (CAID_LIST::iterator ca(caids.begin()); ca != caids.end(); ++ca)
372                                         {
373                                                 std::vector<uint16_t>::const_iterator z =
374                                                         std::lower_bound(ci_caids.begin(), ci_caids.end(), *ca);
375                                                 if ( z != ci_caids.end() && *z == *ca )
376                                                 {
377                                                         eDebug("The CI in Slot %d has said it can handle caid %04x... so use it", ci_it->getSlotID(), *z);
378                                                         useThis = true;
379                                                         user_mapped = false;
380                                                         break;
381                                                 }
382                                         }
383                                 }
384                         }
385
386                         if (useThis)
387                         {
388                                 // check if this CI is already assigned to this pmthandler
389                                 eDVBCISlot *tmp = it->cislot;
390                                 while(tmp)
391                                 {
392                                         if (tmp == ci_it)
393                                                 break;
394                                         tmp=tmp->linked_next;
395                                 }
396                                 if (tmp) // ignore already assigned cislots...
397                                 {
398                                         eDebugCI("already assigned!");
399                                         continue;
400                                 }
401                                 eDebugCI("current slot %d usecount %d", ci_it->getSlotID(), ci_it->use_count);
402                                 if (ci_it->use_count)  // check if this CI can descramble more than one service
403                                 {
404                                         bool found = false;
405                                         useThis = false;
406                                         PMTHandlerList::iterator tmp = m_pmt_handlers.begin();
407                                         while (!found && tmp != m_pmt_handlers.end())
408                                         {
409                                                 eDebugCI(".");
410                                                 eDVBCISlot *tmp_cislot = tmp->cislot;
411                                                 while (!found && tmp_cislot)
412                                                 {
413                                                         eDebugCI("..");
414                                                         eServiceReferenceDVB ref2;
415                                                         tmp->pmthandler->getServiceReference(ref2);
416                                                         if ( tmp_cislot == ci_it && it->pmthandler != tmp->pmthandler )
417                                                         {
418                                                                 eDebugCI("check pmthandler %s for same service/tp", ref2.toString().c_str());
419                                                                 eDVBChannelID s1, s2;
420                                                                 if (ref != ref2)
421                                                                 {
422                                                                         eDebugCI("different services!");
423                                                                         ref.getChannelID(s1);
424                                                                         ref2.getChannelID(s2);
425                                                                 }
426                                                                 if (ref == ref2 || (s1 == s2 && canDescrambleMultipleServices(tmp_cislot->getSlotID())))
427                                                                 {
428                                                                         found = true;
429                                                                         eDebugCI("found!");
430                                                                         eDVBCISlot *tmpci = it->cislot = tmp->cislot;
431                                                                         while(tmpci)
432                                                                         {
433                                                                                 ++tmpci->use_count;
434                                                                                 eDebug("(2)CISlot %d, usecount now %d", tmpci->getSlotID(), tmpci->use_count);
435                                                                                 tmpci=tmpci->linked_next;
436                                                                         }
437                                                                 }
438                                                         }
439                                                         tmp_cislot=tmp_cislot->linked_next;
440                                                 }
441                                                 eDebugCI("...");
442                                                 ++tmp;
443                                         }
444                                 }
445
446                                 if (useThis)
447                                 {
448                                         if (ci_it->user_mapped)  // we dont like to link user mapped CIs
449                                         {
450                                                 eDebugCI("user mapped CI already in use... dont link!");
451                                                 continue;
452                                         }
453
454                                         ++ci_it->use_count;
455                                         eDebug("(1)CISlot %d, usecount now %d", ci_it->getSlotID(), ci_it->use_count);
456
457                                         data_source ci_source=CI_A;
458                                         switch(ci_it->getSlotID())
459                                         {
460                                                 case 0: ci_source = CI_A; break;
461                                                 case 1: ci_source = CI_B; break;
462                                                 case 2: ci_source = CI_C; break;
463                                                 case 3: ci_source = CI_D; break;
464                                                 default:
465                                                         eDebug("try to get source for CI %d!!\n", ci_it->getSlotID());
466                                                         break;
467                                         }
468
469                                         if (!it->cislot)
470                                         {
471                                                 int tunernum = -1;
472                                                 eUsePtr<iDVBChannel> channel;
473                                                 if (!pmthandler->getChannel(channel))
474                                                 {
475                                                         ePtr<iDVBFrontend> frontend;
476                                                         if (!channel->getFrontend(frontend))
477                                                         {
478                                                                 eDVBFrontend *fe = (eDVBFrontend*) &(*frontend);
479                                                                 tunernum = fe->getSlotID();
480                                                         }
481                                                 }
482                                                 ASSERT(tunernum != -1);
483                                                 data_source tuner_source = TUNER_A;
484                                                 switch (tunernum)
485                                                 {
486                                                         case 0: tuner_source = TUNER_A; break;
487                                                         case 1: tuner_source = TUNER_B; break;
488                                                         case 2: tuner_source = TUNER_C; break;
489                                                         case 3: tuner_source = TUNER_D; break;
490                                                         default:
491                                                                 eDebug("try to get source for tuner %d!!\n", tunernum);
492                                                                 break;
493                                                 }
494                                                 ci_it->current_tuner = tunernum;
495                                                 setInputSource(tunernum, ci_source);
496                                                 ci_it->setSource(tuner_source);
497                                         }
498                                         else
499                                         {
500                                                 ci_it->current_tuner = it->cislot->current_tuner;
501                                                 ci_it->linked_next = it->cislot;
502                                                 ci_it->setSource(ci_it->linked_next->current_source);
503                                                 ci_it->linked_next->setSource(ci_source);
504                                         }
505                                         it->cislot = ci_it;
506                                         eDebugCI("assigned!");
507                                         gotPMT(pmthandler);
508                                 }
509
510                                 if (it->cislot && user_mapped) // CI assigned to this pmthandler in this run.. and user mapped? then we break here.. we dont like to link other CIs to user mapped CIs
511                                 {
512                                         eDebugCI("user mapped CI assigned... dont link CIs!");
513                                         break;
514                                 }
515                         }
516                 }
517         }
518 }
519
520 void eDVBCIInterfaces::addPMTHandler(eDVBServicePMTHandler *pmthandler)
521 {
522         // check if this pmthandler is already registered
523         PMTHandlerList::iterator it = m_pmt_handlers.begin();
524         while (it != m_pmt_handlers.end())
525         {
526                 if ( *it++ == pmthandler )
527                         return;
528         }
529
530         eServiceReferenceDVB ref;
531         pmthandler->getServiceReference(ref);
532         eDebug("[eDVBCIInterfaces] addPMTHandler %s", ref.toString().c_str());
533
534         m_pmt_handlers.push_back(CIPmtHandler(pmthandler));
535         recheckPMTHandlers();
536 }
537
538 void eDVBCIInterfaces::removePMTHandler(eDVBServicePMTHandler *pmthandler)
539 {
540         PMTHandlerList::iterator it=std::find(m_pmt_handlers.begin(),m_pmt_handlers.end(),pmthandler);
541         if (it != m_pmt_handlers.end())
542         {
543                 eDVBCISlot *slot = it->cislot;
544                 eDVBServicePMTHandler *pmthandler = it->pmthandler;
545                 m_pmt_handlers.erase(it);
546
547                 eServiceReferenceDVB service_to_remove;
548                 pmthandler->getServiceReference(service_to_remove);
549
550                 bool sameServiceExist=false;
551                 for (PMTHandlerList::iterator i=m_pmt_handlers.begin(); i != m_pmt_handlers.end(); ++i)
552                 {
553                         if (i->cislot)
554                         {
555                                 eServiceReferenceDVB ref;
556                                 i->pmthandler->getServiceReference(ref);
557                                 if ( ref == service_to_remove )
558                                 {
559                                         sameServiceExist=true;
560                                         break;
561                                 }
562                         }
563                 }
564
565                 while(slot)
566                 {
567                         if (!sameServiceExist)
568                         {
569                                 if (slot->getNumOfServices() > 1)
570                                 {
571                                         eDebug("[eDVBCIInterfaces] remove last pmt handler for service %s send empty capmt",
572                                                 service_to_remove.toString().c_str());
573                                                 std::vector<uint16_t> caids;
574                                         caids.push_back(0xFFFF);
575                                         slot->sendCAPMT(pmthandler, caids);  // send a capmt without caids to remove a running service
576                                 }
577                                 slot->removeService(service_to_remove.getServiceID().get());
578                         }
579
580                         eDVBCISlot *next = slot->linked_next;
581                         if (!--slot->use_count)
582                         {
583                                 if (slot->linked_next)
584                                         slot->linked_next->setSource(slot->current_source);
585                                 else
586                                         setInputSource(slot->current_tuner, slot->current_source);
587
588                                 if (it->cislot == slot) // remove the base slot
589                                         it->cislot = slot->linked_next;
590                                 else
591                                 {
592                                         eDVBCISlot *tmp = it->cislot;
593                                         while(tmp->linked_next != slot)
594                                                 tmp = tmp->linked_next;
595                                         ASSERT(tmp);
596                                         if (slot->linked_next)
597                                                 tmp->linked_next = slot->linked_next;
598                                         else
599                                                 tmp->linked_next = 0;
600                                 }
601                                 slot->linked_next = 0;
602                                 slot->user_mapped = false;
603                         }
604                         eDebug("(3) slot %d usecount is now %d", slot->getSlotID(), slot->use_count);
605                         slot = next;
606                 }
607                 // check if another service is waiting for the CI
608                 recheckPMTHandlers();
609         }
610 }
611
612 void eDVBCIInterfaces::gotPMT(eDVBServicePMTHandler *pmthandler)
613 {
614         eDebug("[eDVBCIInterfaces] gotPMT");
615         PMTHandlerList::iterator it=std::find(m_pmt_handlers.begin(), m_pmt_handlers.end(), pmthandler);
616         if (it != m_pmt_handlers.end() && it->cislot)
617         {
618                 eDVBCISlot *tmp = it->cislot;
619                 while(tmp)
620                 {
621                         eDebugCI("check slot %d %d %d", tmp->getSlotID(), tmp->running_services.empty(), canDescrambleMultipleServices(tmp->getSlotID()));
622                         if (tmp->running_services.empty() || canDescrambleMultipleServices(tmp->getSlotID()))
623                                 tmp->sendCAPMT(pmthandler);
624                         tmp = tmp->linked_next;
625                 }
626         }
627 }
628
629 int eDVBCIInterfaces::getMMIState(int slotid)
630 {
631         eDVBCISlot *slot;
632
633         if( (slot = getSlot(slotid)) == 0 )
634                 return -1;
635
636         return slot->getMMIState();
637 }
638
639 int eDVBCIInterfaces::setInputSource(int tuner_no, data_source source)
640 {
641 //      eDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
642 //      eDebug("eDVBCIInterfaces::setInputSource(%d %d)", tuner_no, (int)source);
643         if (getNumOfSlots() > 1) // FIXME .. we force DM8000 when more than one CI Slot is avail
644         {
645                 char buf[64];
646                 snprintf(buf, 64, "/proc/stb/tsmux/input%d", tuner_no);
647
648                 FILE *input=0;
649                 if((input = fopen(buf, "wb")) == NULL) {
650                         eDebug("cannot open %s", buf);
651                         return 0;
652                 }
653
654                 if (tuner_no > 3)
655                         eDebug("setInputSource(%d, %d) failed... dm8000 just have four inputs", tuner_no, (int)source);
656
657                 switch(source)
658                 {
659                         case CI_A:
660                                 fprintf(input, "CI0");
661                                 break;
662                         case CI_B:
663                                 fprintf(input, "CI1");
664                                 break;
665                         case CI_C:
666                                 fprintf(input, "CI2");
667                         break;
668                         case CI_D:
669                                 fprintf(input, "CI3");
670                                 break;
671                         case TUNER_A:
672                                 fprintf(input, "A");
673                                 break;
674                         case TUNER_B:
675                                 fprintf(input, "B");
676                                 break;
677                         case TUNER_C:
678                                 fprintf(input, "C");
679                                 break;
680                         case TUNER_D:
681                                 fprintf(input, "D");
682                                 break;
683                         default:
684                                 eDebug("setInputSource for input %d failed!!!\n", (int)source);
685                                 break;
686                 }
687
688                 fclose(input);
689         }
690         else  // DM7025
691         {
692                 char buf[64];
693                 snprintf(buf, 64, "/proc/stb/tsmux/input%d", tuner_no);
694
695                 if (tuner_no > 1)
696                         eDebug("setInputSource(%d, %d) failed... dm7025 just have two inputs", tuner_no, (int)source);
697
698                 FILE *input=0;
699                 if((input = fopen(buf, "wb")) == NULL) {
700                         eDebug("cannot open %s", buf);
701                         return 0;
702                 }
703
704                 switch(source)
705                 {
706                         case CI_A:
707                                 fprintf(input, "CI");
708                                 break;
709                         case TUNER_A:
710                                 fprintf(input, "A");
711                                 break;
712                         case TUNER_B:
713                                 fprintf(input, "B");
714                                 break;
715                         default:
716                                 eDebug("setInputSource for input %d failed!!!\n", (int)source);
717                                 break;
718                 }
719
720                 fclose(input);
721         }
722         eDebug("eDVBCIInterfaces->setInputSource(%d, %d)", tuner_no, (int)source);
723         return 0;
724 }
725
726 PyObject *eDVBCIInterfaces::getDescrambleRules(int slotid)
727 {
728         eDVBCISlot *slot = getSlot(slotid);
729         if (!slot)
730         {
731                 char tmp[255];
732                 snprintf(tmp, 255, "eDVBCIInterfaces::getDescrambleRules try to get rules for CI Slot %d... but just %d slots are available", slotid, m_slots.size());
733                 PyErr_SetString(PyExc_StandardError, tmp);
734                 return 0;
735         }
736         ePyObject tuple = PyTuple_New(3);
737         int caids = slot->possible_caids.size();
738         int services = slot->possible_services.size();
739         int providers = slot->possible_providers.size();
740         ePyObject caid_list = PyList_New(caids);
741         ePyObject service_list = PyList_New(services);
742         ePyObject provider_list = PyList_New(providers);
743         caidSet::iterator caid_it(slot->possible_caids.begin());
744         while(caids)
745         {
746                 --caids;
747                 PyList_SET_ITEM(caid_list, caids, PyLong_FromLong(*caid_it));
748                 ++caid_it;
749         }
750         serviceSet::iterator ref_it(slot->possible_services.begin());
751         while(services)
752         {
753                 --services;
754                 PyList_SET_ITEM(service_list, services, PyString_FromString(ref_it->toString().c_str()));
755                 ++ref_it;
756         }
757         providerSet::iterator provider_it(slot->possible_providers.begin());
758         while(providers)
759         {
760                 ePyObject tuple = PyTuple_New(2);
761                 PyTuple_SET_ITEM(tuple, 0, PyString_FromString(provider_it->first.c_str()));
762                 PyTuple_SET_ITEM(tuple, 1, PyLong_FromUnsignedLong(provider_it->second));
763                 --providers;
764                 PyList_SET_ITEM(provider_list, providers, tuple);
765                 ++provider_it;
766         }
767         PyTuple_SET_ITEM(tuple, 0, service_list);
768         PyTuple_SET_ITEM(tuple, 1, provider_list);
769         PyTuple_SET_ITEM(tuple, 2, caid_list);
770         return tuple;
771 }
772
773 const char *PyObject_TypeStr(PyObject *o)
774 {
775         return o->ob_type && o->ob_type->tp_name ? o->ob_type->tp_name : "unknown object type";
776 }
777
778 RESULT eDVBCIInterfaces::setDescrambleRules(int slotid, SWIG_PYOBJECT(ePyObject) obj )
779 {
780         eDVBCISlot *slot = getSlot(slotid);
781         if (!slot)
782         {
783                 char tmp[255];
784                 snprintf(tmp, 255, "eDVBCIInterfaces::setDescrambleRules try to set rules for CI Slot %d... but just %d slots are available", slotid, m_slots.size());
785                 PyErr_SetString(PyExc_StandardError, tmp);
786                 return -1;
787         }
788         if (!PyTuple_Check(obj))
789         {
790                 char tmp[255];
791                 snprintf(tmp, 255, "2nd argument of setDescrambleRules is not a tuple.. it is a '%s'!!", PyObject_TypeStr(obj));
792                 PyErr_SetString(PyExc_StandardError, tmp);
793                 return -1;
794         }
795         if (PyTuple_Size(obj) != 3)
796         {
797                 const char *errstr = "eDVBCIInterfaces::setDescrambleRules not enough entrys in argument tuple!!\n"
798                         "first argument should be a pythonlist with possible services\n"
799                         "second argument should be a pythonlist with possible providers/dvbnamespace tuples\n"
800                         "third argument should be a pythonlist with possible caids";
801                 PyErr_SetString(PyExc_StandardError, errstr);
802                 return -1;
803         }
804         ePyObject service_list = PyTuple_GET_ITEM(obj, 0);
805         ePyObject provider_list = PyTuple_GET_ITEM(obj, 1);
806         ePyObject caid_list = PyTuple_GET_ITEM(obj, 2);
807         if (!PyList_Check(service_list) || !PyList_Check(provider_list) || !PyList_Check(caid_list))
808         {
809                 char errstr[512];
810                 snprintf(errstr, 512, "eDVBCIInterfaces::setDescrambleRules incorrect data types in argument tuple!!\n"
811                         "first argument(%s) should be a pythonlist with possible services (reference strings)\n"
812                         "second argument(%s) should be a pythonlist with possible providers (providername strings)\n"
813                         "third argument(%s) should be a pythonlist with possible caids (ints)",
814                         PyObject_TypeStr(service_list), PyObject_TypeStr(provider_list), PyObject_TypeStr(caid_list));
815                 PyErr_SetString(PyExc_StandardError, errstr);
816                 return -1;
817         }
818         slot->possible_caids.clear();
819         slot->possible_services.clear();
820         slot->possible_providers.clear();
821         int size = PyList_Size(service_list);
822         while(size)
823         {
824                 --size;
825                 ePyObject refstr = PyList_GET_ITEM(service_list, size);
826                 if (!PyString_Check(refstr))
827                 {
828                         char buf[255];
829                         snprintf(buf, 255, "eDVBCIInterfaces::setDescrambleRules entry in service list is not a string.. it is '%s'!!", PyObject_TypeStr(refstr));
830                         PyErr_SetString(PyExc_StandardError, buf);
831                         return -1;
832                 }
833                 char *tmpstr = PyString_AS_STRING(refstr);
834                 eServiceReference ref(tmpstr);
835                 if (ref.valid())
836                         slot->possible_services.insert(ref);
837                 else
838                         eDebug("eDVBCIInterfaces::setDescrambleRules '%s' is not a valid service reference... ignore!!", tmpstr);
839         };
840         size = PyList_Size(provider_list);
841         while(size)
842         {
843                 --size;
844                 ePyObject tuple = PyList_GET_ITEM(provider_list, size);
845                 if (!PyTuple_Check(tuple))
846                 {
847                         char buf[255];
848                         snprintf(buf, 255, "eDVBCIInterfaces::setDescrambleRules entry in provider list is not a tuple it is '%s'!!", PyObject_TypeStr(tuple));
849                         PyErr_SetString(PyExc_StandardError, buf);
850                         return -1;
851                 }
852                 if (PyTuple_Size(tuple) != 2)
853                 {
854                         char buf[255];
855                         snprintf(buf, 255, "eDVBCIInterfaces::setDescrambleRules provider tuple has %d instead of 2 entries!!", PyTuple_Size(tuple));
856                         PyErr_SetString(PyExc_StandardError, buf);
857                         return -1;
858                 }
859                 if (!PyString_Check(PyTuple_GET_ITEM(tuple, 0)))
860                 {
861                         char buf[255];
862                         snprintf(buf, 255, "eDVBCIInterfaces::setDescrambleRules 1st entry in provider tuple is not a string it is '%s'", PyObject_TypeStr(PyTuple_GET_ITEM(tuple, 0)));
863                         PyErr_SetString(PyExc_StandardError, buf);
864                         return -1;
865                 }
866                 if (!PyLong_Check(PyTuple_GET_ITEM(tuple, 1)))
867                 {
868                         char buf[255];
869                         snprintf(buf, 255, "eDVBCIInterfaces::setDescrambleRules 2nd entry in provider tuple is not a long it is '%s'", PyObject_TypeStr(PyTuple_GET_ITEM(tuple, 1)));
870                         PyErr_SetString(PyExc_StandardError, buf);
871                         return -1;
872                 }
873                 char *tmpstr = PyString_AS_STRING(PyTuple_GET_ITEM(tuple, 0));
874                 uint32_t orbpos = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(tuple, 1));
875                 if (strlen(tmpstr))
876                         slot->possible_providers.insert(std::pair<std::string, uint32_t>(tmpstr, orbpos));
877                 else
878                         eDebug("eDVBCIInterfaces::setDescrambleRules ignore invalid entry in provider tuple (string is empty)!!");
879         };
880         size = PyList_Size(caid_list);
881         while(size)
882         {
883                 --size;
884                 ePyObject caid = PyList_GET_ITEM(caid_list, size);
885                 if (!PyInt_Check(caid))
886                 {
887                         char buf[255];
888                         snprintf(buf, 255, "eDVBCIInterfaces::setDescrambleRules entry in caid list is not a long it is '%s'!!", PyObject_TypeStr(caid));
889                         PyErr_SetString(PyExc_StandardError, buf);
890                         return -1;
891                 }
892                 int tmpcaid = PyInt_AsLong(caid);
893                 if (tmpcaid > 0 && tmpcaid < 0x10000)
894                         slot->possible_caids.insert(tmpcaid);
895                 else
896                         eDebug("eDVBCIInterfaces::setDescrambleRules %d is not a valid caid... ignore!!", tmpcaid);
897         };
898         return 0;
899 }
900
901 PyObject *eDVBCIInterfaces::readCICaIds(int slotid)
902 {
903         eDVBCISlot *slot = getSlot(slotid);
904         if (!slot)
905         {
906                 char tmp[255];
907                 snprintf(tmp, 255, "eDVBCIInterfaces::readCICaIds try to get CAIds for CI Slot %d... but just %d slots are available", slotid, m_slots.size());
908                 PyErr_SetString(PyExc_StandardError, tmp);
909                 return 0;
910         }
911         int idx=0;
912         ePyObject list = PyList_New(slot->possible_caids.size());
913         for (caidSet::iterator it = slot->possible_caids.begin(); it != slot->possible_caids.end(); ++it)
914                 PyList_SET_ITEM(list, idx++, PyLong_FromLong(*it));
915         return list;
916 }
917
918 int eDVBCISlot::send(const unsigned char *data, size_t len)
919 {
920         int res=0;
921         //int i;
922         //eDebugNoNewLine("< ");
923         //for(i=0;i<len;i++)
924         //      eDebugNoNewLine("%02x ",data[i]);
925         //eDebug("");
926
927         if (sendqueue.empty())
928                 res = ::write(fd, data, len);
929
930         if (res < 0 || (unsigned int)res != len)
931         {
932                 unsigned char *d = new unsigned char[len];
933                 memcpy(d, data, len);
934                 sendqueue.push( queueData(d, len) );
935                 notifier->setRequested(eSocketNotifier::Read | eSocketNotifier::Priority | eSocketNotifier::Write);
936         }
937
938         return res;
939 }
940
941 void eDVBCISlot::data(int what)
942 {
943         eDebugCI("CISlot %d what %d\n", getSlotID(), what);
944         if(what == eSocketNotifier::Priority) {
945                 if(state != stateRemoved) {
946                         state = stateRemoved;
947                         while(sendqueue.size())
948                         {
949                                 delete [] sendqueue.top().data;
950                                 sendqueue.pop();
951                         }
952                         eDVBCISession::deleteSessions(this);
953                         eDVBCIInterfaces::getInstance()->ciRemoved(this);
954                         notifier->setRequested(eSocketNotifier::Read);
955                         eDVBCI_UI::getInstance()->setState(getSlotID(),0);
956                 }
957                 return;
958         }
959
960         if (state == stateInvalid)
961                 reset();
962
963         if(state != stateInserted) {
964                 eDebug("ci inserted in slot %d", getSlotID());
965                 state = stateInserted;
966                 eDVBCI_UI::getInstance()->setState(getSlotID(),1);
967                 notifier->setRequested(eSocketNotifier::Read|eSocketNotifier::Priority);
968                 /* enable PRI to detect removal or errors */
969         }
970
971         if (what & eSocketNotifier::Read) {
972                 __u8 data[4096];
973                 int r;
974                 r = ::read(fd, data, 4096);
975                 if(r > 0) {
976 //                      int i;
977 //                      eDebugNoNewLine("> ");
978 //                      for(i=0;i<r;i++)
979 //                              eDebugNoNewLine("%02x ",data[i]);
980 //                      eDebug("");
981                         eDVBCISession::receiveData(this, data, r);
982                         eDVBCISession::pollAll();
983                         return;
984                 }
985         }
986         else if (what & eSocketNotifier::Write) {
987                 if (!sendqueue.empty()) {
988                         const queueData &qe = sendqueue.top();
989                         int res = ::write(fd, qe.data, qe.len);
990                         if (res >= 0 && (unsigned int)res == qe.len)
991                         {
992                                 delete [] qe.data;
993                                 sendqueue.pop();
994                         }
995                 }
996                 else
997                         notifier->setRequested(eSocketNotifier::Read|eSocketNotifier::Priority);
998         }
999 }
1000
1001 DEFINE_REF(eDVBCISlot);
1002
1003 eDVBCISlot::eDVBCISlot(eMainloop *context, int nr)
1004 {
1005         char filename[128];
1006
1007         application_manager = 0;
1008         mmi_session = 0;
1009         ca_manager = 0;
1010         use_count = 0;
1011         linked_next = 0;
1012         user_mapped = false;
1013         first_plugged = true;
1014         
1015         slotid = nr;
1016
1017         sprintf(filename, "/dev/ci%d", nr);
1018
1019 //      possible_caids.insert(0x1702);
1020 //      possible_providers.insert(providerPair("PREMIERE", 0xC00000));
1021 //      possible_services.insert(eServiceReference("1:0:1:2A:4:85:C00000:0:0:0:"));
1022
1023         fd = ::open(filename, O_RDWR | O_NONBLOCK);
1024
1025         eDebugCI("CI Slot %d has fd %d", getSlotID(), fd);
1026         state = stateInvalid;
1027
1028         if (fd >= 0)
1029         {
1030                 notifier = eSocketNotifier::create(context, fd, eSocketNotifier::Read | eSocketNotifier::Priority | eSocketNotifier::Write);
1031                 CONNECT(notifier->activated, eDVBCISlot::data);
1032         } else
1033         {
1034                 perror(filename);
1035         }
1036 }
1037
1038 eDVBCISlot::~eDVBCISlot()
1039 {
1040         eDVBCISession::deleteSessions(this);
1041 }
1042
1043 void eDVBCISlot::setAppManager( eDVBCIApplicationManagerSession *session )
1044 {
1045         application_manager=session;
1046 }
1047
1048 void eDVBCISlot::setMMIManager( eDVBCIMMISession *session )
1049 {
1050         mmi_session = session;
1051 }
1052
1053 void eDVBCISlot::setCAManager( eDVBCICAManagerSession *session )
1054 {
1055         ca_manager = session;
1056 }
1057
1058 int eDVBCISlot::getSlotID()
1059 {
1060         return slotid;
1061 }
1062
1063 int eDVBCISlot::reset()
1064 {
1065         eDebug("CI Slot %d: reset requested", getSlotID());
1066
1067         if (state == stateInvalid)
1068         {
1069                 unsigned char buf[256];
1070                 eDebug("ci flush");
1071                 while(::read(fd, buf, 256)>0);
1072                 state = stateResetted;
1073         }
1074
1075         while(sendqueue.size())
1076         {
1077                 delete [] sendqueue.top().data;
1078                 sendqueue.pop();
1079         }
1080
1081         ioctl(fd, 0);
1082
1083         return 0;
1084 }
1085
1086 int eDVBCISlot::startMMI()
1087 {
1088         eDebug("CI Slot %d: startMMI()", getSlotID());
1089         
1090         if(application_manager)
1091                 application_manager->startMMI();
1092         
1093         return 0;
1094 }
1095
1096 int eDVBCISlot::stopMMI()
1097 {
1098         eDebug("CI Slot %d: stopMMI()", getSlotID());
1099
1100         if(mmi_session)
1101                 mmi_session->stopMMI();
1102         
1103         return 0;
1104 }
1105
1106 int eDVBCISlot::answerText(int answer)
1107 {
1108         eDebug("CI Slot %d: answerText(%d)", getSlotID(), answer);
1109
1110         if(mmi_session)
1111                 mmi_session->answerText(answer);
1112
1113         return 0;
1114 }
1115
1116 int eDVBCISlot::getMMIState()
1117 {
1118         if(mmi_session)
1119                 return 1;
1120
1121         return 0;
1122 }
1123
1124 int eDVBCISlot::answerEnq(char *value)
1125 {
1126         eDebug("CI Slot %d: answerENQ(%s)", getSlotID(), value);
1127
1128         if(mmi_session)
1129                 mmi_session->answerEnq(value);
1130
1131         return 0;
1132 }
1133
1134 int eDVBCISlot::cancelEnq()
1135 {
1136         eDebug("CI Slot %d: cancelENQ", getSlotID());
1137
1138         if(mmi_session)
1139                 mmi_session->cancelEnq();
1140
1141         return 0;
1142 }
1143
1144 int eDVBCISlot::sendCAPMT(eDVBServicePMTHandler *pmthandler, const std::vector<uint16_t> &ids)
1145 {
1146         if (!ca_manager)
1147         {
1148                 eDebug("no ca_manager (no CI plugged?)");
1149                 return -1;
1150         }
1151         const std::vector<uint16_t> &caids = ids.empty() ? ca_manager->getCAIDs() : ids;
1152         ePtr<eTable<ProgramMapSection> > ptr;
1153         if (pmthandler->getPMT(ptr))
1154                 return -1;
1155         else
1156         {
1157                 eDVBTableSpec table_spec;
1158                 ptr->getSpec(table_spec);
1159                 int pmt_version = table_spec.version & 0x1F; // just 5 bits
1160
1161                 eServiceReferenceDVB ref;
1162                 pmthandler->getServiceReference(ref);
1163                 uint16_t program_number = ref.getServiceID().get();
1164                 std::map<uint16_t, uint8_t>::iterator it =
1165                         running_services.find(program_number);
1166
1167                 if ( it != running_services.end() &&
1168                         (pmt_version == it->second) &&
1169                         !(caids.size() == 1 && caids[0] == 0xFFFF) )
1170                 {
1171                         eDebug("[eDVBCISlot] dont send self capmt version twice");
1172                         return -1;
1173                 }
1174
1175                 std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
1176                 if ( i == ptr->getSections().end() )
1177                         return -1;
1178                 else
1179                 {
1180                         unsigned char raw_data[2048];
1181
1182 //                      eDebug("send %s capmt for service %04x to slot %d",
1183 //                              it != running_services.end() ? "UPDATE" : running_services.empty() ? "ONLY" : "ADD",
1184 //                              program_number, slotid);
1185
1186                         CaProgramMapSection capmt(*i++,
1187                                 it != running_services.end() ? 0x05 /*update*/ : running_services.empty() ? 0x03 /*only*/ : 0x04 /*add*/, 0x01, caids );
1188                         while( i != ptr->getSections().end() )
1189                         {
1190                 //                      eDebug("append");
1191                                 capmt.append(*i++);
1192                         }
1193                         capmt.writeToBuffer(raw_data);
1194 #if 1
1195 // begin calc capmt length
1196                         int wp=0;
1197                         int hlen;
1198                         if ( raw_data[3] & 0x80 )
1199                         {
1200                                 int i=0;
1201                                 int lenbytes = raw_data[3] & ~0x80;
1202                                 while(i < lenbytes)
1203                                         wp = (wp << 8) | raw_data[4 + i++];
1204                                 wp+=4;
1205                                 wp+=lenbytes;
1206                                 hlen = 4 + lenbytes;
1207                         }
1208                         else
1209                         {
1210                                 wp = raw_data[3];
1211                                 wp+=4;
1212                                 hlen = 4;
1213                         }
1214 // end calc capmt length
1215 //                      eDebug("ca_manager %p dump capmt:", ca_manager);
1216 //                      for(int i=0;i<wp;i++)
1217 //                              eDebugNoNewLine("%02x ", raw_data[i]);
1218 //                      eDebug("");
1219 #endif
1220                         if (caids.size() == 1 && caids[0] == 0xFFFF)
1221                         {
1222 //                              eDebugNoNewLine("SEND EMPTY CAPMT.. old version is %02x", raw_data[hlen+3]);
1223                                 raw_data[hlen+3] &= ~0x3E;
1224                                 raw_data[hlen+3] |= ((pmt_version+1) & 0x1F) << 1;
1225 //                              eDebug(" new version is %02x", raw_data[hlen+3]);
1226                         }
1227
1228                         //dont need tag and lenfield
1229                         ca_manager->sendCAPMT(raw_data + hlen, wp - hlen);
1230                         running_services[program_number] = pmt_version;
1231                 }
1232         }
1233         return 0;
1234 }
1235
1236 void eDVBCISlot::removeService(uint16_t program_number)
1237 {
1238         if (program_number == 0xFFFF)
1239                 running_services.clear();  // remove all
1240         else
1241                 running_services.erase(program_number);  // remove single service
1242 }
1243
1244 int eDVBCISlot::setSource(data_source source)
1245 {
1246         current_source = source;
1247         if (eDVBCIInterfaces::getInstance()->getNumOfSlots() > 1) // FIXME .. we force DM8000 when more than one CI Slot is avail
1248         {
1249                 char buf[64];
1250                 snprintf(buf, 64, "/proc/stb/tsmux/ci%d_input", slotid);
1251                 FILE *ci = fopen(buf, "wb");
1252                 switch(source)
1253                 {
1254                         case CI_A:
1255                                 fprintf(ci, "CI0");
1256                                 break;
1257                         case CI_B:
1258                                 fprintf(ci, "CI1");
1259                                 break;
1260                         case CI_C:
1261                                 fprintf(ci, "CI2");
1262                                 break;
1263                         case CI_D:
1264                                 fprintf(ci, "CI3");
1265                                 break;
1266                         case TUNER_A:
1267                                 fprintf(ci, "A");
1268                                 break;
1269                         case TUNER_B:
1270                                 fprintf(ci, "B");
1271                                 break;
1272                         case TUNER_C:
1273                                 fprintf(ci, "C");
1274                                 break;
1275                                 case TUNER_D:
1276                                 fprintf(ci, "D");
1277                                 break;
1278                         default:
1279                                 eDebug("CI Slot %d: setSource %d failed!!!\n", getSlotID(), (int)source);
1280                                 break;
1281                 }
1282                 fclose(ci);
1283         }
1284         else // DM7025
1285         {
1286 //              eDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
1287 //              eDebug("eDVBCISlot::enableTS(%d %d)", enable, (int)source);
1288                 FILE *ci = fopen("/proc/stb/tsmux/input2", "wb");
1289                 if(ci == NULL) {
1290                         eDebug("cannot open /proc/stb/tsmux/input2");
1291                         return 0;
1292                 }
1293                 if (source != TUNER_A && source != TUNER_B)
1294                         eDebug("CI Slot %d: setSource %d failed!!!\n", getSlotID(), (int)source);
1295                 else
1296                         fprintf(ci, "%s", source==TUNER_A ? "A" : "B");  // configure CI data source (TunerA, TunerB)
1297                 fclose(ci);
1298         }
1299         eDebug("CI Slot %d setSource(%d)", getSlotID(), (int)source);
1300         return 0;
1301 }
1302
1303 eAutoInitP0<eDVBCIInterfaces> init_eDVBCIInterfaces(eAutoInitNumbers::dvb, "CI Slots");