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