fix another timer-issue (with a try except-block... explanation is in the code)
[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 <dvbsi++/ca_program_map_section.h>
8
9 eDVBServicePMTHandler::eDVBServicePMTHandler(int record)
10         :m_ca_servicePtr(0)
11 {
12         m_record = record;
13         eDVBResourceManager::getInstance(m_resourceManager);
14         CONNECT(m_PMT.tableReady, eDVBServicePMTHandler::PMTready);
15         CONNECT(m_PAT.tableReady, eDVBServicePMTHandler::PATready);
16         eDebug("new PMT handler record: %d", m_record);
17 }
18
19 eDVBServicePMTHandler::~eDVBServicePMTHandler()
20 {
21         eDebug("delete PMT handler record: %d", m_record);
22         if (m_ca_servicePtr)
23         {
24                 eDebug("unregister caservice");
25                 uint8_t demux_num;
26                 m_demux->getCADemuxID(demux_num);
27                 ePtr<eTable<ProgramMapSection> > ptr;
28                 m_PMT.getCurrent(ptr);
29                 eDVBCAService::unregister_service(m_reference, demux_num, ptr);
30                 eDVBCIInterfaces::getInstance()->removePMTHandler(this);
31         }
32 }
33
34 void eDVBServicePMTHandler::channelStateChanged(iDVBChannel *channel)
35 {
36         int state;
37         channel->getState(state);
38         
39         if ((m_last_channel_state != iDVBChannel::state_ok)
40                 && (state == iDVBChannel::state_ok) && (!m_demux))
41         {
42                 if (m_channel)
43                         if (m_channel->getDemux(m_demux, m_record ? 0 : iDVBChannel::capDecode))
44                                 eDebug("Allocating a demux for now tuned-in channel failed.");
45                 
46                 serviceEvent(eventTuned);
47                 
48                 if (m_demux)
49                 {
50                         eDebug("ok ... now we start!!");
51
52                         /* emit */ m_resourceManager->m_channelRunning(channel);
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                 if (!m_pvr_channel)
75                 {
76                         if(!m_ca_servicePtr)   // don't send campmt to camd.socket for playbacked services
77                         {
78                                 uint8_t demux_num;
79                                 m_demux->getCADemuxID(demux_num);
80                                 eDVBCAService::register_service(m_reference, demux_num, m_ca_servicePtr);
81                                 eDVBCIInterfaces::getInstance()->addPMTHandler(this);
82                         }
83                         eDVBCIInterfaces::getInstance()->gotPMT(this);
84                 }
85                 if (m_ca_servicePtr)
86                 {
87                         ePtr<eTable<ProgramMapSection> > ptr;
88                         if (!m_PMT.getCurrent(ptr))
89                                 m_ca_servicePtr->buildCAPMT(ptr);
90                         else
91                                 eDebug("eDVBServicePMTHandler cannot call buildCAPMT");
92                 }
93         }
94 }
95
96 void eDVBServicePMTHandler::PATready(int)
97 {
98         eDebug("got PAT");
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
128         if (!m_PMT.getCurrent(ptr))
129         {
130                 eDVBTableSpec table_spec;
131                 ptr->getSpec(table_spec);
132                 program.pmtPid = table_spec.pid < 0x1fff ? table_spec.pid : -1;
133                 std::vector<ProgramMapSection*>::const_iterator i;
134                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
135                 {
136                         const ProgramMapSection &pmt = **i;
137                         program.pcrPid = pmt.getPcrPid();
138                         
139                         ElementaryStreamInfoConstIterator es;
140                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
141                         {
142                                 int isaudio = 0, isvideo = 0;
143                                 videoStream video;
144                                 audioStream audio;
145                                 
146                                 video.pid = (*es)->getPid();
147                                 audio.pid = (*es)->getPid();
148                                 
149                                 switch ((*es)->getType())
150                                 {
151                                 case 0x01: // MPEG 1 video
152                                 case 0x02: // MPEG 2 video
153                                         isvideo = 1;
154                                         break;
155                                 case 0x03: // MPEG 1 audio
156                                 case 0x04: // MPEG 2 audio:
157                                         isaudio = 1;
158                                         audio.type = audioStream::atMPEG;
159                                         break;
160                                 }
161                                 if (isaudio)
162                                         program.audioStreams.push_back(audio);
163                                 if (isvideo)
164                                         program.videoStreams.push_back(video);
165                         }
166                 }
167                 return 0;
168         }
169         else if ( m_service && !m_service->cacheEmpty() )
170         {
171                 int vpid = m_service->getCachePID(eDVBService::cVPID),
172                         apid_ac3 = m_service->getCachePID(eDVBService::cAPID),
173                         apid_mpeg = m_service->getCachePID(eDVBService::cAC3PID),
174                         pcrpid = m_service->getCachePID(eDVBService::cPCRPID),
175                         cnt=0;
176                 if ( vpid != -1 )
177                 {
178                         videoStream s;
179                         s.pid = vpid;
180                         program.videoStreams.push_back(s);
181                         ++cnt;
182                 }
183                 if ( apid_ac3 != -1 )
184                 {
185                         audioStream s;
186                         s.type = audioStream::atAC3;
187                         s.pid = apid_ac3;
188                         program.audioStreams.push_back(s);
189                         ++cnt;
190                 }
191                 if ( apid_mpeg != -1 )
192                 {
193                         audioStream s;
194                         s.type = audioStream::atMPEG;
195                         s.pid = apid_mpeg;
196                         program.audioStreams.push_back(s);
197                         ++cnt;
198                 }
199                 if ( pcrpid != -1 )
200                 {
201                         ++cnt;
202                         program.pcrPid = pcrpid;
203                 }
204                 if ( cnt )
205                         return 0;
206         }
207         return -1;
208 }
209
210 int eDVBServicePMTHandler::getChannel(eUsePtr<iDVBChannel> &channel)
211 {
212         channel = m_channel;
213         if (channel)
214                 return 0;
215         else
216                 return -1;
217 }
218
219 int eDVBServicePMTHandler::getDemux(ePtr<iDVBDemux> &demux)
220 {
221         demux = m_demux;
222         if (demux)
223                 return 0;
224         else
225                 return -1;
226 }
227
228 int eDVBServicePMTHandler::getPVRChannel(ePtr<iDVBPVRChannel> &pvr_channel)
229 {
230         pvr_channel = m_pvr_channel;
231         if (pvr_channel)
232                 return 0;
233         else
234                 return -1;
235 }
236
237 int eDVBServicePMTHandler::tune(eServiceReferenceDVB &ref)
238 {
239         RESULT res;
240         m_reference = ref;
241         
242                 /* is this a normal (non PVR) channel? */
243         if (ref.path.empty())
244         {
245                 eDVBChannelID chid;
246                 ref.getChannelID(chid);
247                 res = m_resourceManager->allocateChannel(chid, m_channel);
248                 eDebug("allocate Channel: res %d", res);
249         } else
250         {
251                 eDVBMetaParser parser;
252                 
253                 if (parser.parseFile(ref.path))
254                         eWarning("no .meta file found, trying original service ref.");
255                 else
256                         m_reference = parser.m_ref;
257                 
258                 eDebug("alloc PVR");
259                         /* allocate PVR */
260                 res = m_resourceManager->allocatePVRChannel(m_pvr_channel);
261                 if (res)
262                         eDebug("allocatePVRChannel failed!\n");
263                 m_channel = m_pvr_channel;
264         }
265         
266         if (m_channel)
267         {
268                 m_channel->connectStateChange(
269                         slot(*this, &eDVBServicePMTHandler::channelStateChanged), 
270                         m_channelStateChanged_connection);
271                 m_last_channel_state = -1;
272                 channelStateChanged(m_channel);
273         } else
274         {
275                 serviceEvent(eventTuneFailed);
276                 return res;
277         }
278
279         if (m_pvr_channel)
280                 m_pvr_channel->playFile(ref.path.c_str());
281
282         ePtr<iDVBChannelList> db;
283         if (!m_resourceManager->getChannelList(db))
284                 db->getService((eServiceReferenceDVB&)m_reference, m_service);
285
286         return res;
287 }
288
289 std::map<eServiceReferenceDVB, eDVBCAService*> eDVBCAService::exist;
290
291 eDVBCAService::eDVBCAService()
292         :m_prev_build_hash(0), m_sendstate(0), m_retryTimer(eApp)
293 {
294         memset(m_used_demux, 0xFF, sizeof(m_used_demux));
295         CONNECT(m_retryTimer.timeout, eDVBCAService::sendCAPMT);
296         Connect();
297 }
298
299 eDVBCAService::~eDVBCAService()
300 {
301         eDebug("[eDVBCAService] free service %s", m_service.toString().c_str());
302         ::close(m_sock);
303 }
304
305 RESULT eDVBCAService::register_service( const eServiceReferenceDVB &ref, int demux_num, eDVBCAService *&caservice )
306 {
307         CAServiceMap::iterator it = exist.find(ref);
308         if ( it != exist.end() )
309                 caservice = it->second;
310         else
311         {
312                 caservice = (exist[ref]=new eDVBCAService());
313                 caservice->m_service = ref;
314                 eDebug("[eDVBCAHandler] new service %s", ref.toString().c_str() );
315         }
316 // search free demux entry
317         int iter=0, max_demux_slots = sizeof(caservice->m_used_demux);
318
319         while ( iter < max_demux_slots && caservice->m_used_demux[iter] != 0xFF )
320                 ++iter;
321
322         if ( iter < max_demux_slots )
323         {
324                 caservice->m_used_demux[iter] = demux_num & 0xFF;
325                 eDebug("[eDVBCAHandler] add demux %d to slot %d service %s", demux_num, iter, ref.toString().c_str());
326         }
327         else
328         {
329                 eDebug("[eDVBCAHandler] no more demux slots free for service %s!!", ref.toString().c_str());
330                 return -1;
331         }
332         return 0;
333 }
334
335 RESULT eDVBCAService::unregister_service( const eServiceReferenceDVB &ref, int demux_num, eTable<ProgramMapSection> *ptr )
336 {
337         CAServiceMap::iterator it = exist.find(ref);
338         if ( it == exist.end() )
339         {
340                 eDebug("[eDVBCAHandler] try to unregister non registered %s", ref.toString().c_str());
341                 return -1;
342         }
343         else
344         {
345                 eDVBCAService *caservice = it->second;
346                 bool freed = false;
347                 int iter = 0,
348                         used_demux_slots = 0,
349                         max_demux_slots = sizeof(caservice->m_used_demux)/sizeof(int);
350                 while ( iter < max_demux_slots )
351                 {
352                         if ( caservice->m_used_demux[iter] != 0xFF )
353                         {
354                                 if ( !freed && caservice->m_used_demux[iter] == demux_num )
355                                 {
356                                         eDebug("[eDVBCAService] free slot %d demux %d for service %s", iter, caservice->m_used_demux[iter], caservice->m_service.toString().c_str() );
357                                         caservice->m_used_demux[iter] = 0xFF;
358                                         freed=true;
359                                 }
360                                 else
361                                         ++used_demux_slots;
362                         }
363                         ++iter;
364                 }
365                 if (!freed)
366                 {
367                         eDebug("[eDVBCAService] couldn't free demux slot for demux %d", demux_num);
368                         return -1;
369                 }
370                 if (!used_demux_slots)  // no more used.. so we remove it
371                 {
372                         delete it->second;
373                         exist.erase(it);
374                 }
375                 else
376                 {
377                         if (ptr)
378                                 it->second->buildCAPMT(ptr);
379                         else
380                                 eDebug("[eDVBCAHandler] can not send updated demux info");
381                 }
382         }
383         return 0;
384 }
385
386 void eDVBCAService::Connect()
387 {
388         memset(&m_servaddr, 0, sizeof(struct sockaddr_un));
389         m_servaddr.sun_family = AF_UNIX;
390         strcpy(m_servaddr.sun_path, "/tmp/camd.socket");
391         m_clilen = sizeof(m_servaddr.sun_family) + strlen(m_servaddr.sun_path);
392         m_sock = socket(PF_UNIX, SOCK_STREAM, 0);
393         connect(m_sock, (struct sockaddr *) &m_servaddr, m_clilen);
394         fcntl(m_sock, F_SETFL, O_NONBLOCK);
395         int val=1;
396         setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &val, 4);
397 }
398
399 void eDVBCAService::buildCAPMT(eTable<ProgramMapSection> *ptr)
400 {
401         if (!ptr)
402                 return;
403
404         eDVBTableSpec table_spec;
405         ptr->getSpec(table_spec);
406
407         int pmtpid = table_spec.pid,
408                 pmt_version = table_spec.version;
409
410         uint8_t demux_mask = 0;
411         uint8_t first_demux_num = 0xFF;
412
413 #if 1
414         int iter=0, max_demux_slots = sizeof(m_used_demux);
415         while ( iter < max_demux_slots )
416         {
417                 if ( m_used_demux[iter] != 0xFF )
418                 {
419                         if ( first_demux_num == 0xFF )
420                                 first_demux_num = m_used_demux[iter];
421                         demux_mask |= (1 << m_used_demux[iter]);
422                 }
423                 ++iter;
424         }
425 #else
426         demux_mask = 3;
427         first_demux_num = 0;
428 #endif
429
430         if ( first_demux_num == 0xFF )
431         {
432                 eDebug("[eDVBCAService] no demux found for service %s", m_service.toString().c_str() );
433                 return;
434         }
435
436         eDebug("demux %d mask %02x prevhash %08x", first_demux_num, demux_mask, m_prev_build_hash);
437
438         unsigned int build_hash = (pmtpid << 16);
439         build_hash |= (demux_mask << 8);
440         build_hash |= (pmt_version&0xFF);
441
442         if ( build_hash == m_prev_build_hash )
443         {
444                 eDebug("[eDVBCAService] don't build/send the same CA PMT twice");
445                 return;
446         }
447
448         std::vector<ProgramMapSection*>::const_iterator i=ptr->getSections().begin();
449         if ( i != ptr->getSections().end() )
450         {
451                 CaProgramMapSection capmt(*i++, m_prev_build_hash ? 0x05 /*update*/ : 0x03 /*only*/, 0x01 );
452
453                 while( i != ptr->getSections().end() )
454                 {
455 //                      eDebug("append");
456                         capmt.append(*i++);
457                 }
458
459                 // add our private descriptors to capmt
460                 uint8_t tmp[10];
461
462                 tmp[0]=0x84;  // pmt pid
463                 tmp[1]=0x02;
464                 tmp[2]=pmtpid>>8;
465                 tmp[3]=pmtpid&0xFF;
466                 capmt.injectDescriptor(tmp, false);
467
468                 tmp[0] = 0x82; // demux
469                 tmp[1] = 0x02;
470                 tmp[2] = demux_mask;    // descramble bitmask
471                 tmp[3] = first_demux_num; // read section data from demux number
472                 capmt.injectDescriptor(tmp, false);
473
474                 tmp[0] = 0x81; // dvbnamespace
475                 tmp[1] = 0x08;
476                 tmp[2] = m_service.getDVBNamespace().get()>>24;
477                 tmp[3]=(m_service.getDVBNamespace().get()>>16)&0xFF;
478                 tmp[4]=(m_service.getDVBNamespace().get()>>8)&0xFF;
479                 tmp[5]=m_service.getDVBNamespace().get()&0xFF;
480                 tmp[6]=m_service.getTransportStreamID().get()>>8;
481                 tmp[7]=m_service.getTransportStreamID().get()&0xFF;
482                 tmp[8]=m_service.getOriginalNetworkID().get()>>8;
483                 tmp[9]=m_service.getOriginalNetworkID().get()&0xFF;
484                 capmt.injectDescriptor(tmp, false);
485
486                 capmt.writeToBuffer(m_capmt);
487         }
488
489         m_prev_build_hash = build_hash;
490
491         if ( m_sendstate != 0xFFFFFFFF )
492                 m_sendstate=0;
493         sendCAPMT();
494 }
495
496 void eDVBCAService::sendCAPMT()
497 {
498         if ( m_sendstate && m_sendstate != 0xFFFFFFFF ) // broken pipe retry
499         {
500                 ::close(m_sock);
501                 Connect();
502         }
503
504         int wp=0;
505         if ( m_capmt[3] & 0x80 )
506         {
507                 int i=0;
508                 int lenbytes = m_capmt[3] & ~0x80;
509                 while(i < lenbytes)
510                         wp = (wp << 8) | m_capmt[4 + i++];
511                 wp+=4;
512                 wp+=lenbytes;
513         }
514         else
515         {
516                 wp = m_capmt[3];
517                 wp+=4;
518         }
519
520         if ( write(m_sock, m_capmt, wp) == wp )
521         {
522                 m_sendstate=0xFFFFFFFF;
523                 eDebug("[eDVBCAHandler] send %d bytes",wp);
524 #if 1
525                 for(int i=0;i<wp;i++)
526                         eDebugNoNewLine("%02x ", m_capmt[i]);
527                 eDebug("");
528 #endif
529         }
530         else
531         {
532                 switch(m_sendstate)
533                 {
534                         case 0xFFFFFFFF:
535                                 ++m_sendstate;
536                                 m_retryTimer.start(0,true);
537 //                              eDebug("[eDVBCAHandler] send failed .. immediate retry");
538                                 break;
539                         default:
540                                 m_retryTimer.start(5000,true);
541 //                              eDebug("[eDVBCAHandler] send failed .. retry in 5 sec");
542                                 break;
543                 }
544                 ++m_sendstate;
545         }
546 }