pmt: differentiate between data and decoder demux
[enigma2.git] / lib / dvb / pmt.cpp
1 #include <lib/base/eerror.h>
2 #include <lib/dvb/pmt.h>
3 #include <lib/dvb/specs.h>
4 #include <lib/dvb/dvb.h>
5 #include <lib/dvb/metaparser.h>
6 #include <lib/dvb_ci/dvbci.h>
7 #include <lib/dvb/epgcache.h>
8 #include <dvbsi++/ca_program_map_section.h>
9 #include <dvbsi++/descriptor_tag.h>
10 #include <dvbsi++/iso639_language_descriptor.h>
11 #include <dvbsi++/stream_identifier_descriptor.h>
12
13 eDVBServicePMTHandler::eDVBServicePMTHandler()
14         :m_ca_servicePtr(0)
15 {
16         m_use_decode_demux = 0;
17         eDVBResourceManager::getInstance(m_resourceManager);
18         CONNECT(m_PMT.tableReady, eDVBServicePMTHandler::PMTready);
19         CONNECT(m_PAT.tableReady, eDVBServicePMTHandler::PATready);
20 }
21
22 eDVBServicePMTHandler::~eDVBServicePMTHandler()
23 {
24         if (m_ca_servicePtr)
25         {
26                 eDebug("unregister caservice");
27                 uint8_t demux_num;
28                 m_demux->getCADemuxID(demux_num);
29                 ePtr<eTable<ProgramMapSection> > ptr;
30                 m_PMT.getCurrent(ptr);
31                 eDVBCAService::unregister_service(m_reference, demux_num, ptr);
32                 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
33         }
34 }
35
36 void eDVBServicePMTHandler::channelStateChanged(iDVBChannel *channel)
37 {
38         int state;
39         channel->getState(state);
40         
41         if ((m_last_channel_state != iDVBChannel::state_ok)
42                 && (state == iDVBChannel::state_ok) && (!m_demux))
43         {
44                 if (m_channel)
45                         if (m_channel->getDemux(m_demux, (!m_use_decode_demux) ? 0 : iDVBChannel::capDecode))
46                                 eDebug("Allocating a demux for now tuned-in channel failed.");
47                 
48                 serviceEvent(eventTuned);
49                 
50                 if (m_demux)
51                 {
52                         eDebug("ok ... now we start!!");
53
54                         m_PAT.begin(eApp, eDVBPATSpec(), m_demux);
55
56                         if ( m_service && !m_service->cacheEmpty() )
57                                 serviceEvent(eventNewProgramInfo);
58                 }
59         } else if ((m_last_channel_state != iDVBChannel::state_failed) && 
60                         (state == iDVBChannel::state_failed))
61         {
62                 eDebug("tune failed.");
63                 serviceEvent(eventTuneFailed);
64         }
65 }
66
67 void eDVBServicePMTHandler::PMTready(int error)
68 {
69         if (error)
70                 serviceEvent(eventNoPMT);
71         else
72         {
73                 serviceEvent(eventNewProgramInfo);
74                 eEPGCache::getInstance()->PMTready(this);
75                 if (!m_pvr_channel)
76                 {
77                         if(!m_ca_servicePtr)   // don't send campmt to camd.socket for playbacked services
78                         {
79                                 uint8_t demux_num;
80                                 m_demux->getCADemuxID(demux_num);
81                                 eDVBCAService::register_service(m_reference, demux_num, m_ca_servicePtr);
82                                 eDVBCIInterfaces::getInstance()->addPMTHandler(this);
83                         }
84                         eDVBCIInterfaces::getInstance()->gotPMT(this);
85                 }
86                 if (m_ca_servicePtr)
87                 {
88                         ePtr<eTable<ProgramMapSection> > ptr;
89                         if (!m_PMT.getCurrent(ptr))
90                                 m_ca_servicePtr->buildCAPMT(ptr);
91                         else
92                                 eDebug("eDVBServicePMTHandler cannot call buildCAPMT");
93                 }
94         }
95 }
96
97 void eDVBServicePMTHandler::PATready(int)
98 {
99         ePtr<eTable<ProgramAssociationSection> > ptr;
100         if (!m_PAT.getCurrent(ptr))
101         {
102                 int pmtpid = -1;
103                 std::vector<ProgramAssociationSection*>::const_iterator i;
104                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
105                 {
106                         const ProgramAssociationSection &pat = **i;
107                         ProgramAssociationConstIterator program;
108                         for (program = pat.getPrograms()->begin(); program != pat.getPrograms()->end(); ++program)
109                                 if (eServiceID((*program)->getProgramNumber()) == m_reference.getServiceID())
110                                         pmtpid = (*program)->getProgramMapPid();
111                 }
112                 if (pmtpid == -1)
113                         serviceEvent(eventNoPATEntry);
114                 else
115                         m_PMT.begin(eApp, eDVBPMTSpec(pmtpid, m_reference.getServiceID().get()), m_demux);
116         } else
117                 serviceEvent(eventNoPAT);
118 }
119
120 int eDVBServicePMTHandler::getProgramInfo(struct program &program)
121 {
122         ePtr<eTable<ProgramMapSection> > ptr;
123
124         program.videoStreams.clear();
125         program.audioStreams.clear();
126         program.pcrPid = -1;
127         program.isCrypted = false;
128         program.pmtPid = -1;
129
130         if (!m_PMT.getCurrent(ptr))
131         {
132                 int cached_apid_ac3 = -1;
133                 int cached_apid_mpeg = -1;
134                 int cached_vpid = -1;
135                 if ( m_service && !m_service->cacheEmpty() )
136                 {
137                         cached_vpid = m_service->getCachePID(eDVBService::cVPID);
138                         cached_apid_mpeg = m_service->getCachePID(eDVBService::cAC3PID);
139                         cached_apid_ac3 = m_service->getCachePID(eDVBService::cAPID);
140                 }
141                 eDVBTableSpec table_spec;
142                 ptr->getSpec(table_spec);
143                 program.pmtPid = table_spec.pid < 0x1fff ? table_spec.pid : -1;
144                 std::vector<ProgramMapSection*>::const_iterator i;
145                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
146                 {
147                         const ProgramMapSection &pmt = **i;
148                         program.pcrPid = pmt.getPcrPid();
149                         
150                         ElementaryStreamInfoConstIterator es;
151                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
152                         {
153                                 int isaudio = 0, isvideo = 0, cadescriptors = 0;
154                                 videoStream video;
155                                 audioStream audio;
156                                 audio.component_tag=-1;
157                                 video.component_tag=-1;
158
159                                 video.pid = (*es)->getPid();
160                                 audio.pid = (*es)->getPid();
161
162                                 switch ((*es)->getType())
163                                 {
164                                 case 0x01: // MPEG 1 video
165                                 case 0x02: // MPEG 2 video
166                                         isvideo = 1;
167                                         //break; fall through !!!
168                                 case 0x03: // MPEG 1 audio
169                                 case 0x04: // MPEG 2 audio:
170                                         if (!isvideo)
171                                         {
172                                                 isaudio = 1;
173                                                 audio.type = audioStream::atMPEG;
174                                         }
175                                         //break; fall through !!!
176                                 case 0x06: // PES Private
177                                                 /* PES private can contain AC-3, DTS or lots of other stuff.
178                                                    check descriptors to get the exact type. */
179                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
180                                                         desc != (*es)->getDescriptors()->end(); ++desc)
181                                         {
182                                                 switch ((*desc)->getTag())
183                                                 {
184                                                 case AC3_DESCRIPTOR:
185                                                         if (!isvideo)
186                                                         {
187                                                                 isaudio = 1;
188                                                                 audio.type = audioStream::atAC3;
189                                                         }
190                                                         break;
191                                                 case ISO_639_LANGUAGE_DESCRIPTOR:
192                                                         if (!isvideo)
193                                                         {
194                                                                 const Iso639LanguageList *languages = ((Iso639LanguageDescriptor*)*desc)->getIso639Languages();
195                                                                         /* use last language code */
196                                                                 for (Iso639LanguageConstIterator i(languages->begin()); i != languages->end(); ++i)
197                                                                         audio.language_code = (*i)->getIso639LanguageCode();
198                                                         }
199                                                         break;
200                                                 case STREAM_IDENTIFIER_DESCRIPTOR:
201                                                         audio.component_tag =
202                                                                 video.component_tag =
203                                                                         ((StreamIdentifierDescriptor*)*desc)->getComponentTag();
204                                                         break;
205                                                 case CA_DESCRIPTOR:
206                                                         ++cadescriptors;
207                                                         break;
208                                                 }
209                                         }
210                                         break;
211                                 }
212                                 if (isaudio)
213                                 {
214                                         if ( !program.audioStreams.empty() &&
215                                                 ( audio.pid == cached_apid_ac3 || audio.pid == cached_apid_mpeg) )
216                                         {
217                                                 program.audioStreams.push_back(program.audioStreams[0]);
218                                                 program.audioStreams[0] = audio;
219                                         }
220                                         else
221                                                 program.audioStreams.push_back(audio);
222                                 }
223                                 else if (isvideo)
224                                 {
225                                         if ( !program.videoStreams.empty() && video.pid == cached_vpid )
226                                         {
227                                                 program.videoStreams.push_back(program.videoStreams[0]);
228                                                 program.videoStreams[0] = video;
229                                         }
230                                         else
231                                                 program.videoStreams.push_back(video);
232                                 }
233                                 else
234                                         continue;
235                                 if ( cadescriptors > 0 )
236                                         program.isCrypted=true;
237                         }
238                         if ( !program.isCrypted )
239                         {
240                                 for (DescriptorConstIterator desc = pmt.getDescriptors()->begin();
241                                         desc != pmt.getDescriptors()->end(); ++desc)
242                                 {
243                                         switch ((*desc)->getTag())
244                                         {
245                                         case CA_DESCRIPTOR:
246                                                 program.isCrypted=true;
247                                                 break;
248                                         }
249                                 }
250                                 break;
251                         }
252                 }
253                 return 0;
254         } else if ( m_service && !m_service->cacheEmpty() )
255         {
256                 int vpid = m_service->getCachePID(eDVBService::cVPID),
257                         apid_ac3 = m_service->getCachePID(eDVBService::cAC3PID),
258                         apid_mpeg = m_service->getCachePID(eDVBService::cAPID),
259                         pcrpid = m_service->getCachePID(eDVBService::cPCRPID),
260                         cnt=0;
261                 if ( vpid != -1 )
262                 {
263                         videoStream s;
264                         s.pid = vpid;
265                         program.videoStreams.push_back(s);
266                         ++cnt;
267                 }
268                 if ( apid_ac3 != -1 )
269                 {
270                         audioStream s;
271                         s.type = audioStream::atAC3;
272                         s.pid = apid_ac3;
273                         program.audioStreams.push_back(s);
274                         ++cnt;
275                 }
276                 if ( apid_mpeg != -1 )
277                 {
278                         audioStream s;
279                         s.type = audioStream::atMPEG;
280                         s.pid = apid_mpeg;
281                         program.audioStreams.push_back(s);
282                         ++cnt;
283                 }
284                 if ( pcrpid != -1 )
285                 {
286                         ++cnt;
287                         program.pcrPid = pcrpid;
288                 }
289                 if ( cnt )
290                         return 0;
291         }
292         return -1;
293 }
294
295 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
296 {
297         channel = m_channel;
298         if (channel)
299                 return 0;
300         else
301                 return -1;
302 }
303
304 int eDVBServicePMTHandler::getDataDemux(ePtr<iDVBDemux> &demux)
305 {
306         demux = m_demux;
307         if (demux)
308                 return 0;
309         else
310                 return -1;
311 }
312
313 int eDVBServicePMTHandler::getDecodeDemux(ePtr<iDVBDemux> &demux)
314 {
315                 /* if we're using the decoding demux as data source
316                    (for example in pvr playbacks), return that one. */
317         if (m_use_decode_demux)
318         {
319                 demux = m_demux;
320                 return 0;
321         }
322         
323         return m_channel->getDemux(demux, iDVBChannel::capDecode);
324 }
325
326 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
327 {
328         pvr_channel = m_pvr_channel;
329         if (pvr_channel)
330                 return 0;
331         else
332                 return -1;
333 }
334
335 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref, int use_decode_demux)
336 {
337         RESULT res;
338         m_reference = ref;
339         
340         m_use_decode_demux = use_decode_demux;
341         
342                 /* is this a normal (non PVR) channel? */
343         if (ref.path.empty())
344         {
345                 eDVBChannelID chid;
346                 ref.getChannelID(chid);
347                 res = m_resourceManager->allocateChannel(chid, m_channel);
348                 eDebug("allocate Channel: res %d", res);
349         } else
350         {
351                 eDVBMetaParser parser;
352                 
353                 if (parser.parseFile(ref.path))
354                         eWarning("no .meta file found, trying original service ref.");
355                 else
356                         m_reference = parser.m_ref;
357                 
358                 eDebug("alloc PVR");
359                         /* allocate PVR */
360                 res = m_resourceManager->allocatePVRChannel(m_pvr_channel);
361                 if (res)
362                         eDebug("allocatePVRChannel failed!\n");
363                 m_channel = m_pvr_channel;
364         }
365         
366         if (m_channel)
367         {
368                 m_channel->connectStateChange(
369                         slot(*this, &eDVBServicePMTHandler::channelStateChanged), 
370                         m_channelStateChanged_connection);
371                 m_last_channel_state = -1;
372                 channelStateChanged(m_channel);
373         } else
374         {
375                 serviceEvent(eventTuneFailed);
376                 return res;
377         }
378
379         if (m_pvr_channel)
380                 m_pvr_channel->playFile(ref.path.c_str());
381
382         ePtr<iDVBChannelList> db;
383         if (!m_resourceManager->getChannelList(db))
384                 db->getService((eServiceReferenceDVB&)m_reference, m_service);
385
386         return res;
387 }
388
389 void eDVBServicePMTHandler::free()
390 {
391         m_PMT.stop();
392         m_PAT.stop();
393         m_service = 0;
394         m_channel = 0;
395         m_pvr_channel = 0;
396         m_demux = 0;
397 }
398
399 std::map<eServiceReferenceDVB, eDVBCAService*> eDVBCAService::exist;
400
401 eDVBCAService::eDVBCAService()
402         :m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eApp)
403 {
404         memset(m_used_demux, 0xFF, sizeof(m_used_demux));
405         CONNECT(m_retryTimer.timeout, eDVBCAService::sendCAPMT);
406         Connect();
407 }
408
409 eDVBCAService::~eDVBCAService()
410 {
411         eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
412         ::close(m_sock);
413 }
414
415 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_num, eDVBCAService *&caservice )
416 {
417         CAServiceMap::iterator it = exist.find(ref);
418         if ( it != exist.end() )
419                 caservice = it->second;
420         else
421         {
422                 caservice = (exist[ref]=new eDVBCAService());
423                 caservice->m_service = ref;
424                 eDebug("[eDVBCAService] new service %s", ref.toString().c_str() );
425         }
426 // search free demux entry
427         int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
428
429         while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
430                 ++iter;
431
432         if ( iter < max_demux_slots )
433         {
434                 caservice->m_used_demux[iter] = demux_num & 0xFF;
435                 eDebug("[eDVBCAService] add demux %d to slot %d service %s", demux_num, iter, ref.toString().c_str());
436         }
437         else
438         {
439                 eDebug("[eDVBCAService] no more demux slots free for service %s!!", ref.toString().c_str());
440                 return -1;
441         }
442         return 0;
443 }
444
445 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_num, eTable<ProgramMapSection> *ptr )
446 {
447         CAServiceMap::iterator it = exist.find(ref);
448         if ( it == exist.end() )
449         {
450                 eDebug("[eDVBCAService] try to unregister non registered %s", ref.toString().c_str());
451                 return -1;
452         }
453         else
454         {
455                 eDVBCAService *caservice = it->second;
456                 bool freed = false;
457                 int iter = 0,
458                         used_demux_slots = 0,
459                         max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
460                 while ( iter < max_demux_slots )
461                 {
462                         if ( caservice->m_used_demux[iter] != 0xFF )
463                         {
464                                 if ( !freed && caservice->m_used_demux[iter] == demux_num )
465                                 {
466                                         eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
467                                         caservice->m_used_demux[iter] = 0xFF;
468                                         freed=true;
469                                 }
470                                 else
471                                         ++used_demux_slots;
472                         }
473                         ++iter;
474                 }
475                 if (!freed)
476                 {
477                         eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_num);
478                         return -1;
479                 }
480                 if (!used_demux_slots)  // no more used.. so we remove it
481                 {
482                         delete it->second;
483                         exist.erase(it);
484                 }
485                 else
486                 {
487                         if (ptr)
488                                 it->second->buildCAPMT(ptr);
489                         else
490                                 eDebug("[eDVBCAService] can not send updated demux info");
491                 }
492         }
493         return 0;
494 }
495
496 void eDVBCAService::Connect()
497 {
498         memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
499         m_servaddr.sun_family = AF_UNIX;
500         strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
501         m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
502         m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
503         connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen);
504         fcntl(m_sock, F_SETFL, O_NONBLOCK);
505         int val=1;
506         setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
507 }
508
509 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
510 {
511         if (!ptr)
512                 return;
513
514         eDVBTableSpec table_spec;
515         ptr->getSpec(table_spec);
516
517         int pmtpid = table_spec.pid,
518                 pmt_version = table_spec.version;
519
520         uint8_t demux_mask = 0;
521         uint8_t first_demux_num = 0xFF;
522
523 #if 1
524         int iter=0, max_demux_slots = sizeof(m_used_demux);
525         while ( iter < max_demux_slots )
526         {
527                 if ( m_used_demux[iter] != 0xFF )
528                 {
529                         if ( first_demux_num == 0xFF )
530                                 first_demux_num = m_used_demux[iter];
531                         demux_mask |= (1 << m_used_demux[iter]);
532                 }
533                 ++iter;
534         }
535 #else
536         demux_mask = 3;
537         first_demux_num = 0;
538 #endif
539
540         if ( first_demux_num == 0xFF )
541         {
542                 eDebug("[eDVBCAService] no demux found for service %s", m_service.toString().c_str() );
543                 return;
544         }
545
546         eDebug("demux %d mask %02x prevhash %08x", first_demux_num, demux_mask, m_prev_build_hash);
547
548         unsigned int build_hash = (pmtpid << 16);
549         build_hash |= (demux_mask << 8);
550         build_hash |= (pmt_version&0xFF);
551
552         if ( build_hash == m_prev_build_hash )
553         {
554                 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
555                 return;
556         }
557
558         std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
559         if ( i != ptr->getSections().end() )
560         {
561                 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
562
563                 while( i != ptr->getSections().end() )
564                 {
565 //                      eDebug("append");
566                         capmt.append(*i++);
567                 }
568
569                 // add our private descriptors to capmt
570                 uint8_t tmp[10];
571
572                 tmp[0]=0x84;  // pmt pid
573                 tmp[1]=0x02;
574                 tmp[2]=pmtpid>>8;
575                 tmp[3]=pmtpid&0xFF;
576                 capmt.injectDescriptor(tmp, false);
577
578                 tmp[0] = 0x82; // demux
579                 tmp[1] = 0x02;
580                 tmp[2] = demux_mask;    // descramble bitmask
581                 tmp[3] = first_demux_num; // read section data from demux number
582                 capmt.injectDescriptor(tmp, false);
583
584                 tmp[0] = 0x81; // dvbnamespace
585                 tmp[1] = 0x08;
586                 tmp[2] = m_service.getDVBNamespace().get()>>24;
587                 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
588                 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
589                 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
590                 tmp[6]=m_service.getTransportStreamID().get()>>8;
591                 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
592                 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
593                 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
594                 capmt.injectDescriptor(tmp, false);
595
596                 capmt.writeToBuffer(m_capmt);
597         }
598
599         m_prev_build_hash = build_hash;
600
601         if ( m_sendstate != 0xFFFFFFFF )
602                 m_sendstate=0;
603         sendCAPMT();
604 }
605
606 void eDVBCAService::sendCAPMT()
607 {
608         if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
609         {
610                 ::close(m_sock);
611                 Connect();
612         }
613
614         int wp=0;
615         if ( m_capmt[3] & 0x80 )
616         {
617                 int i=0;
618                 int lenbytes = m_capmt[3] & ~0x80;
619                 while(i < lenbytes)
620                         wp = (wp << 8) | m_capmt[4 + i++];
621                 wp+=4;
622                 wp+=lenbytes;
623         }
624         else
625         {
626                 wp = m_capmt[3];
627                 wp+=4;
628         }
629
630         if ( write(m_sock, m_capmt, wp) == wp )
631         {
632                 m_sendstate=0xFFFFFFFF;
633                 eDebug("[eDVBCAService] send %d bytes",wp);
634 #if 1
635                 for(int i=0;i<wp;i++)
636                         eDebugNoNewLine("%02x ", m_capmt[i]);
637                 eDebug("");
638 #endif
639         }
640         else
641         {
642                 switch(m_sendstate)
643                 {
644                         case 0xFFFFFFFF:
645                                 ++m_sendstate;
646                                 m_retryTimer.start(0,true);
647 //                              eDebug("[eDVBCAService] send failed .. immediate retry");
648                                 break;
649                         default:
650                                 m_retryTimer.start(5000,true);
651 //                              eDebug("[eDVBCAService] send failed .. retry in 5 sec");
652                                 break;
653                 }
654                 ++m_sendstate;
655         }
656 }