Merge branch 'master' of /home/tmbinc/enigma2-git into tmbinc/FixTimingBugs
[enigma2.git] / lib / dvb / demux.cpp
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <sys/ioctl.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <signal.h>
7
8 #if HAVE_DVB_API_VERSION < 3
9 #include <ost/dmx.h>
10
11 #ifndef DMX_SET_NEGFILTER_MASK
12         #define DMX_SET_NEGFILTER_MASK   _IOW('o',48,uint8_t *)
13 #endif
14
15 #ifndef DMX_GET_STC
16         struct dmx_stc
17         {
18                 unsigned int num;       /* input : which STC? O..N */
19                 unsigned int base;      /* output: divisor for stc to get 90 kHz clock */
20                 unsigned long long stc; /* output: src in 'base'*90 kHz units */
21         };
22         #define DMX_GET_STC             _IOR('o', 50, struct dmx_stc)
23 #endif
24
25 #else
26 #include <linux/dvb/dmx.h>
27
28 #define HAVE_ADD_PID
29
30 #ifdef HAVE_ADD_PID
31 #define DMX_ADD_PID              _IO('o', 51)
32 #define DMX_REMOVE_PID           _IO('o', 52)
33
34 typedef enum {
35         DMX_TAP_TS = 0,
36         DMX_TAP_PES = DMX_PES_OTHER, /* for backward binary compat. */
37 } dmx_tap_type_t;
38
39 #endif
40
41 #endif
42
43 #include "crc32.h"
44
45 #include <lib/base/eerror.h>
46 #include <lib/base/filepush.h>
47 #include <lib/dvb/idvb.h>
48 #include <lib/dvb/demux.h>
49 #include <lib/dvb/esection.h>
50 #include <lib/dvb/decoder.h>
51 #include <lib/dvb/pvrparse.h>
52
53 eDVBDemux::eDVBDemux(int adapter, int demux): adapter(adapter), demux(demux)
54 {
55         m_dvr_busy = 0;
56 }
57
58 eDVBDemux::~eDVBDemux()
59 {
60 }
61
62 int eDVBDemux::openDemux(void)
63 {
64         char filename[128];
65 #if HAVE_DVB_API_VERSION < 3
66         snprintf(filename, 128, "/dev/dvb/card%d/demux%d", adapter, demux);
67 #else
68         snprintf(filename, 128, "/dev/dvb/adapter%d/demux%d", adapter, demux);
69 #endif
70         return ::open(filename, O_RDWR);
71 }
72
73 DEFINE_REF(eDVBDemux)
74
75 RESULT eDVBDemux::setSourceFrontend(int fenum)
76 {
77 #if HAVE_DVB_API_VERSION >= 3
78         int fd = openDemux();
79         int n = DMX_SOURCE_FRONT0 + fenum;
80         int res = ::ioctl(fd, DMX_SET_SOURCE, &n);
81         if (res)
82                 eDebug("DMX_SET_SOURCE failed! - %m");
83         else
84                 source = fenum;
85         ::close(fd);
86         return res;
87 #endif
88         return 0;
89 }
90
91 RESULT eDVBDemux::setSourcePVR(int pvrnum)
92 {
93 #if HAVE_DVB_API_VERSION >= 3
94         int fd = openDemux();
95         int n = DMX_SOURCE_DVR0 + pvrnum;
96         int res = ::ioctl(fd, DMX_SET_SOURCE, &n);
97         source = -1;
98         ::close(fd);
99         return res;
100 #endif
101         return 0;
102 }
103
104 RESULT eDVBDemux::createSectionReader(eMainloop *context, ePtr<iDVBSectionReader> &reader)
105 {
106         RESULT res;
107         reader = new eDVBSectionReader(this, context, res);
108         if (res)
109                 reader = 0;
110         return res;
111 }
112
113 RESULT eDVBDemux::createPESReader(eMainloop *context, ePtr<iDVBPESReader> &reader)
114 {
115         RESULT res;
116         reader = new eDVBPESReader(this, context, res);
117         if (res)
118                 reader = 0;
119         return res;
120 }
121
122 RESULT eDVBDemux::createTSRecorder(ePtr<iDVBTSRecorder> &recorder)
123 {
124         if (m_dvr_busy)
125                 return -EBUSY;
126         recorder = new eDVBTSRecorder(this);
127         return 0;
128 }
129
130 RESULT eDVBDemux::getMPEGDecoder(ePtr<iTSMPEGDecoder> &decoder, int primary)
131 {
132         decoder = new eTSMPEGDecoder(this, primary ? 0 : 1);
133         return 0;
134 }
135
136 RESULT eDVBDemux::getSTC(pts_t &pts, int num)
137 {
138         int fd = openDemux();
139         
140         if (fd < 0)
141                 return -ENODEV;
142
143         struct dmx_stc stc;
144         stc.num = num;
145         stc.base = 1;
146         
147         if (ioctl(fd, DMX_GET_STC, &stc) < 0)
148         {
149                 eDebug("DMX_GET_STC failed!");
150                 ::close(fd);
151                 return -1;
152         }
153         
154         pts = stc.stc;
155         
156         eDebug("DMX_GET_STC - %lld", pts);
157         
158         ::close(fd);
159         return 0;
160 }
161
162 RESULT eDVBDemux::flush()
163 {
164         // FIXME: implement flushing the PVR queue here.
165         
166         m_event(evtFlush);
167         return 0;
168 }
169
170 RESULT eDVBDemux::connectEvent(const Slot1<void,int> &event, ePtr<eConnection> &conn)
171 {
172         conn = new eConnection(this, m_event.connect(event));
173         return 0;
174 }
175
176 void eDVBSectionReader::data(int)
177 {
178         __u8 data[4096]; // max. section size
179         int r;
180         r = ::read(fd, data, 4096);
181         if(r < 0)
182         {
183                 eWarning("ERROR reading section - %m\n");
184                 return;
185         }
186         if (checkcrc)
187         {
188                         // this check should never happen unless the driver is crappy!
189                 unsigned int c;
190                 if ((c = crc32((unsigned)-1, data, r)))
191                 {
192                         eDebug("crc32 failed! is %x\n", c);
193                         return;
194                 }
195         }
196         if (active)
197                 read(data);
198         else
199                 eDebug("data.. but not active");
200 }
201
202 eDVBSectionReader::eDVBSectionReader(eDVBDemux *demux, eMainloop *context, RESULT &res): demux(demux)
203 {
204         char filename[128];
205         fd = demux->openDemux();
206         
207         if (fd >= 0)
208         {
209                 notifier=eSocketNotifier::create(context, fd, eSocketNotifier::Read, false);
210                 CONNECT(notifier->activated, eDVBSectionReader::data);
211                 res = 0;
212         } else
213         {
214                 perror(filename);
215                 res = errno;
216         }
217 }
218
219 DEFINE_REF(eDVBSectionReader)
220
221 eDVBSectionReader::~eDVBSectionReader()
222 {
223         if (fd >= 0)
224                 ::close(fd);
225 }
226
227 RESULT eDVBSectionReader::start(const eDVBSectionFilterMask &mask)
228 {
229         RESULT res;
230         if (fd < 0)
231                 return -ENODEV;
232
233         notifier->start();
234 #if HAVE_DVB_API_VERSION < 3
235         dmxSctFilterParams sct;
236 #else
237         dmx_sct_filter_params sct;
238 #endif
239         sct.pid     = mask.pid;
240         sct.timeout = 0;
241 #if HAVE_DVB_API_VERSION < 3
242         sct.flags   = 0;
243 #else
244         sct.flags   = DMX_IMMEDIATE_START;
245 #endif
246         if (mask.flags & eDVBSectionFilterMask::rfCRC)
247         {
248                 sct.flags |= DMX_CHECK_CRC;
249                 checkcrc = 1;
250         } else
251                 checkcrc = 0;
252         
253         memcpy(sct.filter.filter, mask.data, DMX_FILTER_SIZE);
254         memcpy(sct.filter.mask, mask.mask, DMX_FILTER_SIZE);
255 #if HAVE_DVB_API_VERSION >= 3
256         memcpy(sct.filter.mode, mask.mode, DMX_FILTER_SIZE);
257         if (::ioctl(fd, DMX_SET_BUFFER_SIZE, 8192*8) < 0)
258                 eDebug("DMX_SET_BUFFER_SIZE failed(%m)");
259 #endif
260         
261         res = ::ioctl(fd, DMX_SET_FILTER, &sct);
262         if (!res)
263         {
264 #if HAVE_DVB_API_VERSION < 3
265                 res = ::ioctl(fd, DMX_SET_NEGFILTER_MASK, mask.mode);
266                 if (!res)
267                 {
268                         res = ::ioctl(fd, DMX_START, 0);
269                         if (!res)
270                                 active = 1;
271                 }
272 #else
273                 active = 1;
274 #endif
275         }
276         return res;
277 }
278
279 RESULT eDVBSectionReader::stop()
280 {
281         if (!active)
282                 return -1;
283
284         active=0;
285         ::ioctl(fd, DMX_STOP);
286         notifier->stop();
287
288         return 0;
289 }
290
291 RESULT eDVBSectionReader::connectRead(const Slot1<void,const __u8*> &r, ePtr<eConnection> &conn)
292 {
293         conn = new eConnection(this, read.connect(r));
294         return 0;
295 }
296
297 void eDVBPESReader::data(int)
298 {
299         while (1)
300         {
301                 __u8 buffer[16384];
302                 int r;
303                 r = ::read(m_fd, buffer, 16384);
304                 if (!r)
305                         return;
306                 if(r < 0)
307                 {
308                         if (errno == EAGAIN || errno == EINTR) /* ok */
309                                 return;
310                         eWarning("ERROR reading PES (fd=%d) - %m", m_fd);
311                         return;
312                 }
313
314                 if (m_active)
315                         m_read(buffer, r);
316                 else
317                         eWarning("PES reader not active");
318                 if (r != 16384)
319                         break;
320         }
321 }
322
323 eDVBPESReader::eDVBPESReader(eDVBDemux *demux, eMainloop *context, RESULT &res): m_demux(demux)
324 {
325         char filename[128];
326         m_fd = m_demux->openDemux();
327         
328         if (m_fd >= 0)
329         {
330                 ::ioctl(m_fd, DMX_SET_BUFFER_SIZE, 64*1024);
331                 ::fcntl(m_fd, F_SETFL, O_NONBLOCK);
332                 m_notifier = eSocketNotifier::create(context, m_fd, eSocketNotifier::Read, false);
333                 CONNECT(m_notifier->activated, eDVBPESReader::data);
334                 res = 0;
335         } else
336         {
337                 perror(filename);
338                 res = errno;
339         }
340 }
341
342 DEFINE_REF(eDVBPESReader)
343
344 eDVBPESReader::~eDVBPESReader()
345 {
346         if (m_fd >= 0)
347                 ::close(m_fd);
348 }
349
350 RESULT eDVBPESReader::start(int pid)
351 {
352         RESULT res;
353         if (m_fd < 0)
354                 return -ENODEV;
355
356         m_notifier->start();
357
358 #if HAVE_DVB_API_VERSION < 3
359         dmxPesFilterParams flt;
360         
361         flt.pesType = DMX_PES_OTHER;
362 #else
363         dmx_pes_filter_params flt;
364         
365         flt.pes_type = DMX_PES_OTHER;
366 #endif
367
368         flt.pid     = pid;
369         flt.input   = DMX_IN_FRONTEND;
370         flt.output  = DMX_OUT_TAP;
371         
372         flt.flags   = DMX_IMMEDIATE_START;
373
374         res = ::ioctl(m_fd, DMX_SET_PES_FILTER, &flt);
375         
376         if (res)
377                 eWarning("PES filter: DMX_SET_PES_FILTER - %m");
378         if (!res)
379                 m_active = 1;
380         return res;
381 }
382
383 RESULT eDVBPESReader::stop()
384 {
385         if (!m_active)
386                 return -1;
387
388         m_active=0;
389         ::ioctl(m_fd, DMX_STOP);
390         m_notifier->stop();
391
392         return 0;
393 }
394
395 RESULT eDVBPESReader::connectRead(const Slot2<void,const __u8*,int> &r, ePtr<eConnection> &conn)
396 {
397         conn = new eConnection(this, m_read.connect(r));
398         return 0;
399 }
400
401 class eDVBRecordFileThread: public eFilePushThread
402 {
403 public:
404         eDVBRecordFileThread();
405         void setTimingPID(int pid, int type);
406         
407         void startSaveMetaInformation(const std::string &filename);
408         void stopSaveMetaInformation();
409         int getLastPTS(pts_t &pts);
410 protected:
411         int filterRecordData(const unsigned char *data, int len, size_t &current_span_remaining);
412 private:
413         eMPEGStreamParserTS m_ts_parser;
414         eMPEGStreamInformation m_stream_info;
415         off_t m_current_offset;
416         pts_t m_last_pcr; /* very approximate.. */
417         int m_pid;
418 };
419
420 eDVBRecordFileThread::eDVBRecordFileThread()
421         :eFilePushThread(IOPRIO_CLASS_RT, 7), m_ts_parser(m_stream_info)
422 {
423         m_current_offset = 0;
424 }
425
426 void eDVBRecordFileThread::setTimingPID(int pid, int type)
427 {
428         m_ts_parser.setPid(pid, type);
429 }
430
431 void eDVBRecordFileThread::startSaveMetaInformation(const std::string &filename)
432 {
433         m_stream_info.startSave(filename.c_str());
434 }
435
436 void eDVBRecordFileThread::stopSaveMetaInformation()
437 {
438         m_stream_info.stopSave();
439 }
440
441 int eDVBRecordFileThread::getLastPTS(pts_t &pts)
442 {
443         return m_ts_parser.getLastPTS(pts);
444 }
445
446 int eDVBRecordFileThread::filterRecordData(const unsigned char *data, int len, size_t &current_span_remaining)
447 {
448         m_ts_parser.parseData(m_current_offset, data, len);
449         
450         m_current_offset += len;
451         
452         return len;
453 }
454
455 DEFINE_REF(eDVBTSRecorder);
456
457 eDVBTSRecorder::eDVBTSRecorder(eDVBDemux *demux): m_demux(demux)
458 {
459         m_running = 0;
460         m_target_fd = -1;
461         m_thread = new eDVBRecordFileThread();
462   CONNECT(m_thread->m_event, eDVBTSRecorder::filepushEvent);
463 #ifndef HAVE_ADD_PID
464         m_demux->m_dvr_busy = 1;
465 #endif
466 }
467
468 eDVBTSRecorder::~eDVBTSRecorder()
469 {
470         stop();
471         delete m_thread;
472 #ifndef HAVE_ADD_PID
473         m_demux->m_dvr_busy = 0;
474 #endif
475 }
476
477 RESULT eDVBTSRecorder::start()
478 {
479         if (m_running)
480                 return -1;
481         
482         if (m_target_fd == -1)
483                 return -2;
484
485         char filename[128];
486 #ifndef HAVE_ADD_PID
487 #if HAVE_DVB_API_VERSION < 3
488         snprintf(filename, 128, "/dev/dvb/card%d/dvr%d", m_demux->adapter, m_demux->demux);
489 #else
490         snprintf(filename, 128, "/dev/dvb/adapter%d/dvr%d", m_demux->adapter, m_demux->demux);
491 #endif
492         m_source_fd = ::open(filename, O_RDONLY);
493         
494         if (m_source_fd < 0)
495         {
496                 eDebug("FAILED to open dvr (%s) in ts recoder (%m)", filename);
497                 return -3;
498         }
499 #else
500         snprintf(filename, 128, "/dev/dvb/adapter%d/demux%d", m_demux->adapter, m_demux->demux);
501
502         m_source_fd = ::open(filename, O_RDONLY);
503         
504         if (m_source_fd < 0)
505         {
506                 eDebug("FAILED to open demux (%s) in ts recoder (%m)", filename);
507                 return -3;
508         }
509         
510         ::ioctl(m_source_fd, DMX_SET_BUFFER_SIZE, 1024*1024);
511
512         dmx_pes_filter_params flt;
513         flt.pes_type = (dmx_pes_type_t)DMX_TAP_TS;
514         flt.pid     = (__u16)-1;
515         flt.input   = DMX_IN_FRONTEND;
516         flt.output  = DMX_OUT_TAP;
517         flt.flags   = 0;
518         int res = ::ioctl(m_source_fd, DMX_SET_PES_FILTER, &flt);
519         if (res)
520         {
521                 eDebug("DMX_SET_PES_FILTER: %m");
522                 ::close(m_source_fd);
523                 return -3;
524         }
525         
526         ::ioctl(m_source_fd, DMX_START);
527         
528 #endif
529
530         if (m_target_filename != "")
531                 m_thread->startSaveMetaInformation(m_target_filename);
532         
533         m_thread->start(m_source_fd, m_target_fd);
534         m_running = 1;
535         
536         for (std::map<int,int>::iterator i(m_pids.begin()); i != m_pids.end(); ++i)
537                 startPID(i->first);
538         
539         return 0;
540 }
541
542 RESULT eDVBTSRecorder::addPID(int pid)
543 {
544         if (m_pids.find(pid) != m_pids.end())
545                 return -1;
546         
547         m_pids.insert(std::pair<int,int>(pid, -1));
548         if (m_running)
549                 startPID(pid);
550         return 0;
551 }
552
553 RESULT eDVBTSRecorder::removePID(int pid)
554 {
555         if (m_pids.find(pid) == m_pids.end())
556                 return -1;
557                 
558         if (m_running)
559                 stopPID(pid);
560         
561         m_pids.erase(pid);
562         return 0;
563 }
564
565 RESULT eDVBTSRecorder::setTimingPID(int pid, int type)
566 {
567         if (m_running)
568                 return -1;
569         m_thread->setTimingPID(pid, type);
570         return 0;
571 }
572
573 RESULT eDVBTSRecorder::setTargetFD(int fd)
574 {
575         m_target_fd = fd;
576         return 0;
577 }
578
579 RESULT eDVBTSRecorder::setTargetFilename(const char *filename)
580 {
581         m_target_filename = filename;
582         return 0;
583 }
584
585 RESULT eDVBTSRecorder::setBoundary(off_t max)
586 {
587         return -1; // not yet implemented
588 }
589
590 RESULT eDVBTSRecorder::stop()
591 {
592         for (std::map<int,int>::iterator i(m_pids.begin()); i != m_pids.end(); ++i)
593                 stopPID(i->first);
594
595         if (!m_running)
596                 return -1;
597         m_thread->stop();
598         
599         close(m_source_fd);
600         m_source_fd = -1;
601         
602         m_thread->stopSaveMetaInformation();
603         
604         return 0;
605 }
606
607 RESULT eDVBTSRecorder::getCurrentPCR(pts_t &pcr)
608 {
609         if (!m_running)
610                 return 0;
611         if (!m_thread)
612                 return 0;
613                 /* XXX: we need a lock here */
614
615                         /* we don't filter PCR data, so just use the last received PTS, which is not accurate, but better than nothing */
616         return m_thread->getLastPTS(pcr);
617 }
618
619 RESULT eDVBTSRecorder::connectEvent(const Slot1<void,int> &event, ePtr<eConnection> &conn)
620 {
621         conn = new eConnection(this, m_event.connect(event));
622         return 0;
623 }
624
625 RESULT eDVBTSRecorder::startPID(int pid)
626 {
627 #ifndef HAVE_ADD_PID
628         int fd = m_demux->openDemux();
629         if (fd < 0)
630         {
631                 eDebug("FAILED to open demux in ts recoder (%m)");
632                 return -1;
633         }
634
635 #if HAVE_DVB_API_VERSION < 3
636         dmxPesFilterParams flt;
637         
638         flt.pesType = DMX_PES_OTHER;
639 #else
640         dmx_pes_filter_params flt;
641         
642         flt.pes_type = DMX_PES_OTHER;
643 #endif
644
645         flt.pid     = pid;
646         flt.input   = DMX_IN_FRONTEND;
647         flt.output  = DMX_OUT_TS_TAP;
648         
649         flt.flags   = DMX_IMMEDIATE_START;
650
651         int res = ::ioctl(fd, DMX_SET_PES_FILTER, &flt);
652         if (res < 0)
653         {
654                 eDebug("set pes filter failed!");
655                 ::close(fd);
656                 return -1;
657         }
658         m_pids[pid] = fd;
659 #else
660         while(true) {
661                 if (::ioctl(m_source_fd, DMX_ADD_PID, pid) < 0) {
662                         perror("DMX_ADD_PID");
663                         if (errno == EAGAIN || errno == EINTR) {
664                                 eDebug("retry!");
665                                 continue;
666                         }
667                 } else
668                         m_pids[pid] = 1;
669                 break;
670         }
671 #endif
672         return 0;
673 }
674
675 void eDVBTSRecorder::stopPID(int pid)
676 {
677 #ifndef HAVE_ADD_PID
678         if (m_pids[pid] != -1)
679                 ::close(m_pids[pid]);
680 #else
681         if (m_pids[pid] != -1)
682         {
683                 while(true) {
684                         if (::ioctl(m_source_fd, DMX_REMOVE_PID, pid) < 0) {
685                                 perror("DMX_REMOVE_PID");
686                                 if (errno == EAGAIN || errno == EINTR) {
687                                         eDebug("retry!");
688                                         continue;
689                                 }
690                         }
691                         break;
692                 }
693         }
694 #endif
695         m_pids[pid] = -1;
696 }
697
698 void eDVBTSRecorder::filepushEvent(int event)
699 {
700         switch (event)
701         {
702         case eFilePushThread::evtWriteError:
703                 m_event(eventWriteError);
704                 break;
705         }
706 }