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