]> git.vomp.tv Git - vompclient.git/blob - demuxer.cc
Compile fixes for stretch
[vompclient.git] / demuxer.cc
1 /*
2     Copyright 2005-2008 Mark Calderbank
3     Copyright 2007 Marten Richter (AC3 support)
4
5     This file is part of VOMP.
6
7     VOMP is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     VOMP is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License
18     along with VOMP; if not, write to the Free Software Foundation, Inc.,
19     51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 */
21
22 #include "demuxer.h"
23
24 #include "callback.h"
25 #include "dvbsubtitles.h"
26 #include "log.h"
27
28 #include <cstdlib>
29
30 #include <math.h>
31
32 #define DEMUXER_SEQ_HEAD 0x000001B3
33 #define DEMUXER_PIC_HEAD 0x00000101
34 #define DEMUXER_SEQ_EXT_HEAD 0x000001B5
35
36 #define DEMUXER_H264_ACCESS_UNIT 0x00000109
37 #define DEMUXER_H264_SEQ_PARAMETER_SET 0x00000107
38 #define DEMUXER_H264_SUB_ENHANCEMENT_INF 0x00000106
39 #define DEMUXER_H264_CODED_SLICE_IDR 0x00000105
40 #define DEMUXER_H264_CODED_SLICE_NON_IDR 0x00000101
41
42 #define SEEK_THRESHOLD 150000 // About 1.5 seconds
43
44 // Statics
45 const int Demuxer::FrameRates[9] = { 0, 23, 24, 25, 29, 30, 50, 59, 60 };
46 Demuxer* Demuxer::instance = NULL;
47
48 class NALUUnit {
49 public:
50     NALUUnit(const UCHAR* buf,UINT length_buf);
51     ~NALUUnit();
52
53 inline    UINT getBits(UINT num_bits);
54     UINT getUe();
55     int getSe();
56     bool isEonalu() {return eonalu;};
57     int getPos(){return pos;};
58
59 protected:
60     UCHAR* nalu_buf;
61     UINT nalu_length;
62     UINT pos;
63     UCHAR bit_pos;
64     UCHAR working_byte;
65     UINT last_bytes;
66     bool eonalu;
67 };
68
69 NALUUnit::NALUUnit(const UCHAR *buf, UINT length_buf)
70 {
71     nalu_length=0;
72     nalu_buf=NULL;
73     pos=0;
74     bit_pos=0;
75     working_byte=0;
76     last_bytes=0;
77     eonalu=false;
78
79     UINT nalu_start=0;
80     UINT nalu_end=0;
81     UINT pattern =(((UINT)buf[ 0] << 16) |
82                    ((UINT)buf[1] <<  8) |
83                     (UINT)buf[2]  );
84     nalu_start=3;
85     while (pattern != 0x000001)
86     {
87         if (++nalu_start >= length_buf) return;
88         pattern = ((pattern << 8) | buf[nalu_start])&0x00FFFFFF;
89     }
90     nalu_end=nalu_start+1;
91     if (nalu_end >= length_buf) return; // input buffer too small. corrupt data? ignore.
92     pattern = ((pattern << 8) | buf[nalu_end])&0x00FFFFFF;
93
94     while (pattern != 0x000001 && pattern != 0x000000)
95     {
96         if (++nalu_end >= length_buf) { nalu_end+=3;break;};
97         pattern = ((pattern << 8) | buf[nalu_end])&0x00FFFFFF;
98     }
99     nalu_end-=3;
100     nalu_end=min(length_buf-1,nalu_end);
101     if (nalu_end <= nalu_start) return; // input buffer too small. corrupt data? ignore.
102     nalu_length=nalu_end-nalu_start;
103     nalu_buf=(UCHAR*)malloc(nalu_length);
104     memcpy(nalu_buf,buf+nalu_start,nalu_length);
105     pos=1;
106 }
107
108 NALUUnit::~NALUUnit()
109 {
110     if (nalu_buf) free(nalu_buf);
111 }
112
113 inline UINT NALUUnit::getBits(UINT num_bits)
114 {
115     if (num_bits==0) return 0; //???
116     UINT remain_bits=num_bits;
117     UINT work=0;
118     //May be slow, but should work!
119     while (remain_bits>0) {
120         if (bit_pos==0) {
121             if (pos<nalu_length)
122             {
123                 last_bytes=(last_bytes<<8) & nalu_buf[pos];
124                 if ((last_bytes & 0x00FFFFFF) == 0x000003) pos++; //emulation prevention byte
125                  if (pos<nalu_length)
126                  {
127                      working_byte=nalu_buf[pos];
128                      pos++;
129                  } 
130                  else
131                  {
132                      working_byte=0;
133                      eonalu=true;
134                  }
135             } 
136             else
137             {
138                 working_byte=0;
139                 eonalu=true;
140             }
141
142         }
143         UINT fetch_bits=min(remain_bits,8-bit_pos);
144         work=work <<fetch_bits;
145         //work|=((working_byte>>bit_pos) & (0xFF>>(8-fetch_bits)));
146         work|=(working_byte &(0xFF>>(bit_pos)))>>(8-fetch_bits-bit_pos);
147         remain_bits-=fetch_bits;
148         bit_pos=(bit_pos+fetch_bits)%8;
149     }
150     return work;
151 }
152
153 UINT NALUUnit::getUe()
154 {
155     int leadbits=-1;
156     bool bit;
157     for( bit = 0; !bit && !eonalu; leadbits++ )
158         bit = getBits(1);
159     if (eonalu) return 0;
160     return ((1 << leadbits)-1)+getBits(leadbits);
161 }
162
163 int NALUUnit::getSe()
164 {
165     UINT input=getUe();
166     if (input==0) return 0;
167     int output=((input+1)>>1);
168     if (input & 0x1) output*=-1;
169     return output;
170 }
171
172
173
174 static const int PESPacket_initial_size = 2000;
175
176 // PESPacket methods
177 PESPacket::PESPacket()
178 {
179   data_size = PESPacket_initial_size;
180   data = (UCHAR*)malloc(data_size);
181   data[0] = 0x00;
182   data[1] = 0x00;
183   data[2] = 0x01;
184   init(0);
185 }
186
187 PESPacket::PESPacket(const PESPacket& packet)
188 {
189   copyFrom(packet);
190 }
191
192 PESPacket& PESPacket::operator=(const PESPacket& packet)
193 {
194   if (this != &packet)
195   {
196     if (data) free(data);
197     copyFrom(packet);
198   }
199   return *this;
200 }
201
202 PESPacket::~PESPacket()
203 {
204   if (data) free(data);
205 }
206
207 void PESPacket::copyFrom(const PESPacket& packet)
208 {
209   length = packet.length;
210   size = packet.size;
211   packetType = packet.packetType;
212   substream = packet.substream;
213   seq_header = packet.seq_header;
214   data_size = size;
215   data = (UCHAR*)malloc(data_size);
216   memcpy(data, packet.data, data_size);
217 }
218
219 void PESPacket::init(UCHAR type, UCHAR sub)
220 {
221   length = 0; 
222   size = 6;
223   data[4] = data[5] = 0;
224   data[3] = type;
225   packetType = type;
226   substream = sub;
227   seq_header = 1; // Unknown seq_header status
228
229 }
230
231 void PESPacket::truncate()
232 {
233   init(packetType,substream);
234 }
235
236
237
238 int PESPacket::write(const UCHAR *buf, int len)
239 {
240
241
242   if (size + len > 0x10000) return 0;
243   if (size + len > data_size)
244   { // Reallocate
245     UINT new_data_size = max(data_size + data_size / 2, data_size + len);
246     if (new_data_size > 0x10000) new_data_size = 0x10000;
247     data_size = new_data_size;
248     data = (UCHAR*)realloc(data, data_size);
249   }
250   memcpy(data + size, buf, len);
251   length += len;
252   size += len;
253   data[4] = (length >> 8);
254   data[5] = (length & 0xFF);
255   // We have added data - reset seq_header indicator if necessary
256   if (seq_header == 0) seq_header = 1; // Reset to 'unknown'
257   return 1;
258 }
259
260 ULLONG PESPacket::getPTS() const
261 {
262   if ( ( (packetType >= Demuxer::PESTYPE_AUD0 &&
263           packetType <= Demuxer::PESTYPE_AUDMAX)
264          ||
265          (packetType >= Demuxer::PESTYPE_VID0 &&
266           packetType <= Demuxer::PESTYPE_VIDMAX)
267    ||
268           packetType == Demuxer::PESTYPE_PRIVATE_1
269        )
270        && size >= 14 && data[7] & 0x80)
271   {
272     return ( (ULLONG)(data[ 9] & 0x0E) << 29) |
273            ( (ULLONG)(data[10])        << 22 ) |
274            ( (ULLONG)(data[11] & 0xFE) << 14 ) |
275            ( (ULLONG)(data[12])        <<  7 ) |
276            ( (ULLONG)(data[13] & 0xFE) >>  1 );
277   }
278   else return PTS_INVALID;
279 }
280
281 UCHAR PESPacket::operator[] (UINT index) const
282 {
283   if (index >= size)
284     return 0;
285   else
286     return data[index];
287 }
288
289 UINT PESPacket::findPictureHeader(bool h264) const
290 {
291   if (size < 12) return 0;
292   UINT pattern = ( ((UINT)data[ 8] << 24) |
293                    ((UINT)data[ 9] << 16) |
294                    ((UINT)data[10] <<  8) |
295                     (UINT)data[11]  );
296   UINT pos = 11;
297   if (h264) {
298           
299           while (pattern != DEMUXER_H264_ACCESS_UNIT)
300           {
301                   if (++pos >= size) return 0;
302                   pattern = (pattern << 8) | data[pos];
303           }
304           return pos-3;
305   } else {
306           while (pattern != DEMUXER_PIC_HEAD)
307           {
308                   if (++pos >= size) return 0;
309                   pattern = (pattern << 8) | data[pos];
310           }
311           return pos-3;
312   }
313 }
314
315 UINT PESPacket::countPictureHeaders(bool h264, struct PictCountInfo& pinfo) const
316 {
317   if (size < 12) return 0;
318   UINT pattern = ( ((UINT)data[ 8] << 24) |
319                    ((UINT)data[ 9] << 16) |
320                    ((UINT)data[10] <<  8) |
321                     (UINT)data[11]  );
322   UINT pos = 11;
323   UINT count=0;
324   if (h264) {
325           //inspired by vdr algorithm for frame couting by Klaus Schmidinger
326           while (pos<size)
327           {
328           pos++;
329                   pattern = (pattern << 8) | data[pos];
330                   if ((pattern &0xFFFFFF00)==0x00000100) {
331                           UINT testpattern=(pattern& 0xFFFFFF1f);
332                           if (testpattern==DEMUXER_H264_ACCESS_UNIT) pinfo.hasaccessunit=true;
333                           else if (testpattern==DEMUXER_H264_SEQ_PARAMETER_SET ) {
334                                   pinfo.hassps=true;
335                                   NALUUnit nalu(data+pos-3,getSize()-pos+3);
336                                   int profile=nalu.getBits(8);
337                                   nalu.getBits(8); //constraints
338                                   nalu.getBits(8); //level_idc
339                                   nalu.getUe(); //seq_parameter_set_id
340                                   int chroma=1;
341                               pinfo.separate_color_plane_flag=0;
342                                   if (profile==100 || profile==110 || profile==122 || profile==144)
343                                   {
344                                       chroma=nalu.getUe();
345                                       if (chroma==3)
346                                       {
347                                           pinfo.separate_color_plane_flag=nalu.getBits(1);
348                                       }
349                                       nalu.getUe(); //bit depth lume
350                                       nalu.getUe(); //bit depth chrome
351                                       nalu.getBits(1);
352                                       if (nalu.getBits(1))
353                                       {
354                                           for (int i=0;i<8;i++){
355                                                   if (nalu.getBits(1))
356                                                   {
357                                                           if (i<6)
358                                                           {
359                                                                   UINT lastscale=8;
360                                                                   UINT nextscale=8;
361                                                                   for (int j=0;j<16;j++) {
362                                                                           if (nextscale!=0) {
363                                                                                   UINT delta=nalu.getSe();
364                                                                                   nextscale=(lastscale+delta+256)%256;
365                                                                           }
366                                                                           lastscale=(nextscale==0)?lastscale:nextscale;
367                                                                   }
368                                                           }
369                                                           else
370                                                           {
371                                                                   UINT lastscale=8;
372                                                                   UINT nextscale=8;
373                                                                   for (int j=0;j<64;j++) {
374                                                                           if (nextscale!=0) {
375                                                                                   UINT delta=nalu.getSe();
376                                                                                   nextscale=(lastscale+delta+256)%256;
377                                                                           }
378                                                                           lastscale=(nextscale==0)?lastscale:nextscale;
379                                                                   }
380                                                           }
381                                                   }
382                                           }
383                                       }
384                                   }
385
386                                   UINT checkMaxFrameNum = nalu.getUe() + 4;  //log2framenum
387
388                                   if (checkMaxFrameNum < 13) {
389                                         pinfo.log2_max_frame_num = checkMaxFrameNum;
390                                   }
391                                   else {
392                                         pattern=0xFFFFFF;
393                                         pos+=nalu.getPos();
394                                         continue;
395                                   }
396
397                                   UINT temp=nalu.getUe();
398                                   if (temp==0) //pict order
399                                           nalu.getUe();
400                                   else if (temp==1) {
401                                           nalu.getBits(1);
402                                           nalu.getSe();
403                                           nalu.getSe();
404                                           UINT temp2=nalu.getUe();
405                                           for (UINT i=0;i<temp2;i++)
406                                                   nalu.getSe();
407                                   }
408                                   nalu.getUe(); //Num refframes
409                                   nalu.getBits(1);
410                                   nalu.getUe();
411                                   nalu.getUe();
412                                   pinfo.frame_mbs_only_flag=nalu.getBits(1);
413                                   pattern=0xFFFFFF;
414                                   pos+=nalu.getPos();
415
416                           } if (testpattern==DEMUXER_H264_CODED_SLICE_IDR || testpattern==DEMUXER_H264_CODED_SLICE_NON_IDR ) {
417                                 /*  Log::getInstance()->log("Demuxer", Log::ERR,
418                                                                 "Has slice %d %d %d %d %d",pinfo.hasaccessunit, pinfo.hassps,pinfo.frame_mbs_only_flag,pinfo.separate_color_plane_flag,
419                                                                 pinfo.log2_max_frame_num);*/
420                                   if (pinfo.hasaccessunit && pinfo.hassps) {
421
422                                           NALUUnit nalu(data+pos-3,getSize()-pos+3);
423                                           nalu.getUe();// first_mb_in_slice
424                                           nalu.getUe();//sliectype
425                                           if (!pinfo.frame_mbs_only_flag) {
426                                                   nalu.getUe(); //pic_paramter_set_id
427                                                   if (pinfo.separate_color_plane_flag) nalu.getBits(2);
428                                                   nalu.getBits(pinfo.log2_max_frame_num);
429                                                   //if (!frame_mbs_only_flag)
430                                                   if (nalu.getBits(1)) { //field_picture
431                                                           if (!nalu.getBits(1)) { //bottom_field
432                                                                   count++;
433                                                           }
434                                                   } else count++;
435
436                                           } else count++;
437                                           pattern=0xFFFFFF;
438                                           pos+=nalu.getPos();
439                                           pinfo.hasaccessunit=false;
440                                   }
441                           }
442                   }
443           }
444           return count;
445   } else {
446       while (pos<size)
447           {
448           pos++;
449                   pattern = (pattern << 8) | data[pos];
450           if (pattern==DEMUXER_PIC_HEAD) count++;
451           }
452           return count;
453   }
454 }
455
456 UINT PESPacket::findSeqHeader(bool h264) const
457 {
458   if (seq_header != 1) return seq_header;
459   if (size < 12) return 0;
460   UINT pattern = ( ((UINT)data[ 8] << 24) |
461                    ((UINT)data[ 9] << 16) |
462                    ((UINT)data[10] <<  8) |
463                     (UINT)data[11]  );
464   UINT pos = 11;
465   if (h264) {
466       while ((pattern & 0xFFFFFF1F) != DEMUXER_H264_SEQ_PARAMETER_SET)
467           {
468                   if (++pos >= size)
469                   {
470                           seq_header = 0;
471                           return 0;
472                   }
473                   pattern = (pattern << 8) | data[pos];
474           }
475           seq_header = pos - 3;
476   } 
477   else 
478   {
479           while (pattern != DEMUXER_SEQ_HEAD)
480           {
481                   if (++pos >= size)
482                   {
483                           seq_header = 0;
484                           return 0;
485                   }
486                   pattern = (pattern << 8) | data[pos];
487           }
488           seq_header = pos - 3;
489   }
490   return seq_header;
491 }
492
493 UINT PESPacket::findSeqExtHeader(bool h264) const
494 {
495   if (seq_header != 1) return seq_header;
496   if (size < 12) return 0;
497   UINT pattern = ( ((UINT)data[ 8] << 24) |
498                    ((UINT)data[ 9] << 16) |
499                    ((UINT)data[10] <<  8) |
500                     (UINT)data[11]  );
501   UINT pos = 11;
502   if (h264) {
503       while ((pattern & 0xFFFFFF1F) != DEMUXER_H264_SUB_ENHANCEMENT_INF)
504           {
505                   if (++pos >= size)
506                   {
507                           seq_header = 0;
508                           return 0;
509                   }
510                   pattern = (pattern << 8) | data[pos];
511           }
512           seq_header = pos - 3;
513   }
514   else
515   {
516           while (pattern != DEMUXER_SEQ_EXT_HEAD && (data[pos+1]&0xf0)!=0x10)
517           {
518                   if (++pos >= (size-1))
519                   {
520                           seq_header = 0;
521                           return 0;
522                   }
523                   pattern = (pattern << 8) | data[pos];
524           }
525           seq_header = pos - 3;
526   }
527   return seq_header;
528 }
529
530 // Demuxer methods
531 Demuxer::Demuxer()
532 {
533   if (instance) return;
534   instance = this;
535   initted = false;
536   callback = NULL;
537   arcnt = 0;
538   vid_seeking = aud_seeking = false;
539   video_pts = audio_pts = 0;
540   ispre_1_3_19 = false;
541   packetnum=0;
542   h264 = false;
543   fps = 25.0;
544   astreamtype=4;
545   livetv=false;
546 }
547
548 Demuxer::~Demuxer()
549 {
550   shutdown();
551   instance = NULL;
552 }
553
554 Demuxer* Demuxer::getInstance()
555 {
556   return instance;
557 }
558
559 int Demuxer::init(Callback* tcallback, DrainTarget* audio, DrainTarget* video, DrainTarget* teletext,
560                   ULONG demuxMemoryV, ULONG demuxMemoryA, ULONG demuxMemoryT,double infps, DVBSubtitles* tsubtitles)
561 {
562   if (!initted)
563   {
564     if ( !videostream.init(video, demuxMemoryV) ||
565          !audiostream.init(audio, demuxMemoryA) ||
566          !teletextstream.init(teletext, demuxMemoryT))
567     {
568       Log::getInstance()->log("Demuxer", Log::CRIT,
569                               "Failed to initialize demuxer");
570       shutdown();
571       return 0;
572     }
573   }
574   if (teletext) {
575       isteletextdecoded = true;
576   } else {
577       isteletextdecoded = false;
578   }
579   fps=infps;
580   reset();
581   initted = true;
582   subtitles = tsubtitles;
583   callback = tcallback;
584   return 1;
585 }
586
587 void Demuxer::reset()
588 {
589   Log::getInstance()->log("Demuxer", Log::DEBUG, "Reset called");
590   flush();
591   video_current = audio_current = teletext_current = subtitle_current = -1;
592   horizontal_size = vertical_size = 0;
593   interlaced=true; // default is true
594   aspect_ratio = (enum AspectRatio) 0;
595   parx=1;
596   pary=1;
597   frame_rate = bit_rate = 0;
598   ispre_1_3_19 = false;
599   h264 = false;
600   packetnum=0;
601   astreamtype=4;
602   livetv=false;
603
604   for (int i = 0; i <= (PESTYPE_AUDMAX - PESTYPE_AUD0); i++)
605   {
606     avail_mpaudchan[i] = false;
607   }
608   for (int i = 0; i <= (PESTYPE_SUBSTREAM_AC3MAX - PESTYPE_SUBSTREAM_AC30); i++)
609   {
610     avail_ac3audchan[i] = false;
611   }
612   for (int i = 0; i <= (PESTYPE_SUBSTREAM_DVBSUBTITLEMAX - PESTYPE_SUBSTREAM_DVBSUBTITLE0); i++)
613   {
614     avail_dvbsubtitlechan[i] = false;
615   }
616 }
617
618 int Demuxer::shutdown()
619 {
620   videostream.shutdown();
621   audiostream.shutdown();
622   teletextstream.shutdown();
623   initted = false;
624   return 1;
625 }
626
627 void Demuxer::flush()
628 {
629   Log::getInstance()->log("Demuxer", Log::DEBUG, "Flush called");
630
631   videostream.flush();
632   audiostream.flush();
633   teletextstream.flush();
634 }
635
636 void Demuxer::flushAudio()
637 {
638   audiostream.flush();
639 }
640
641 void Demuxer::seek()
642 {
643   vid_seeking = aud_seeking = true;
644   video_pts = audio_pts = teletext_pts = 0;
645 }
646
647 void Demuxer::setAudioStream(int id)
648 {
649   audio_current = id;
650 }
651
652 void Demuxer::setVideoStream(int id)
653 {
654   video_current = id;
655 }
656
657 void Demuxer::setTeletextStream(int id)
658 {
659   teletext_current = id;
660 }
661
662 void Demuxer::setDVBSubtitleStream(int id)
663 {
664   subtitle_current = id;
665 }
666
667 void Demuxer::setAspectRatio(enum AspectRatio ar, int taspectx, int taspecty)
668 {
669   if ((aspect_ratio != ar) || (parx !=  taspectx) || (pary != taspecty) )
670   {
671     Log::getInstance()->log("Demux", Log::DEBUG,
672                             "Aspect ratio difference signalled");
673     if (++arcnt > 3) // avoid changing aspect ratio if glitch in signal
674     {
675       arcnt = 0;
676       aspect_ratio = ar;
677       parx=taspectx;
678       pary=taspecty;
679       if (callback) callback->call(this);
680     }
681   }
682   else
683     arcnt = 0;
684 }
685
686 bool Demuxer::writeAudio(bool * dataavail)
687 {
688   return audiostream.drain(dataavail);
689 }
690
691 bool Demuxer::writeVideo(bool * dataavail)
692 {
693   return videostream.drain(dataavail);
694 }
695
696 bool Demuxer::writeTeletext(bool * dataavail)
697 {
698    return teletextstream.drain(dataavail);
699 }
700
701 bool Demuxer::submitPacket(PESPacket& packet)
702 {
703   UINT sent = 0;
704   UCHAR packet_type = packet.getPacketType();
705   const UCHAR* packetdata = packet.getData();
706   if (packet_type >= PESTYPE_VID0 && packet_type <= PESTYPE_VIDMAX)
707   {
708     if (video_current == -1) video_current = packet_type;
709     if (video_current == packet_type && !vid_seeking)
710         {
711         sent = videostream.put(&packetdata[0], packet.getSize(), h264?MPTYPE_VIDEO_H264:MPTYPE_VIDEO_MPEG2,packetnum);
712         if (sent) packetnum++;
713         }
714         else
715       sent = packet.getSize();
716   }
717   else if (packet_type >= PESTYPE_AUD0 && packet_type <= PESTYPE_AUDMAX)
718   {
719
720     if (audio_current == -1) audio_current = packet_type;
721     avail_mpaudchan[packet_type - PESTYPE_AUD0] = true;
722     if (audio_current == packet_type && !aud_seeking)
723         {
724       UCHAR type=MPTYPE_MPEG_AUDIO;
725       switch (astreamtype)
726       {
727       case 3:
728       case 4:
729           type=MPTYPE_MPEG_AUDIO; break;
730       case 0x11:
731           type=MPTYPE_AAC_LATM; break;
732       };
733       sent = audiostream.put(&packetdata[0], packet.getSize(), type,packetnum);
734           if (sent)  packetnum++;
735         }
736         else
737       sent = packet.getSize();
738   }
739   else if (packet_type == PESTYPE_PRIVATE_1 &&
740            packet.getSubstream() >= PESTYPE_SUBSTREAM_AC30 &&
741            packet.getSubstream() <= PESTYPE_SUBSTREAM_AC3MAX)
742   {
743     avail_ac3audchan[packet.getSubstream() - PESTYPE_SUBSTREAM_AC30] = true;
744     if (packet.getSubstream() == audio_current)
745     {
746       sent = audiostream.put(&packetdata[0], packet.getSize(), (ispre_1_3_19 || livetv)? MPTYPE_AC3_PRE13 : MPTYPE_AC3,packetnum);
747           if (sent) packetnum++;
748     }
749     else
750     {
751       sent = packet.getSize();
752     }
753   }
754   else if (packet_type == PESTYPE_PRIVATE_1 &&
755            packet.getSubstream() >= PESTYPE_SUBSTREAM_DVBSUBTITLE0 &&
756            packet.getSubstream() <= PESTYPE_SUBSTREAM_DVBSUBTITLEMAX)
757   {
758     avail_dvbsubtitlechan[packet.getSubstream()-PESTYPE_SUBSTREAM_DVBSUBTITLE0]=true;
759     if (subtitle_current == -1) subtitle_current = packet.getSubstream();
760     if (subtitles && packet.getSubstream()==subtitle_current)
761     {
762          subtitles->put(packet);
763     }
764     sent = packet.getSize();
765   }
766   else if (isteletextdecoded  && packet_type == PESTYPE_PRIVATE_1 &&
767            packet.getSubstream() >= PESTYPE_SUBSTREAM_TELETEXT0 &&
768            packet.getSubstream() <= PESTYPE_SUBSTREAM_TELETEXTMAX)
769   {
770
771     if (teletext_current == -1) teletext_current = packet.getSubstream();
772     if (teletext_current == packet.getSubstream())
773     {
774         sent = teletextstream.put(&packetdata[0], packet.getSize(), MPTYPE_TELETEXT,packetnum);
775     }
776     else 
777     {
778         sent = packet.getSize();
779     }
780   }
781   else
782   {
783     sent = packet.getSize();
784   }
785
786   if (sent < packet.getSize()) // Stream is full.
787     return false;
788   else
789     return true;
790 }
791
792 void Demuxer::parsePacketDetails(PESPacket& packet)
793 {
794     if (packet.getPacketType() >= PESTYPE_AUD0 &&
795         packet.getPacketType() <= PESTYPE_AUDMAX)
796     {
797         // Extract audio PTS if it exists
798         if (packet.hasPTS())
799         {
800             audio_pts = packet.getPTS();
801             // We continue to seek on the audio if the video PTS that we
802             // are trying to match is ahead of the audio PTS by at most
803             // SEEK_THRESHOLD. We consider the possibility of PTS wrap.
804             if (aud_seeking && !vid_seeking &&
805                 !( (video_pts_seek > audio_pts &&
806                 video_pts_seek - audio_pts < SEEK_THRESHOLD)
807                 ||
808                 (video_pts_seek < audio_pts &&
809                 video_pts_seek + (1LL<<33) - audio_pts < SEEK_THRESHOLD) ))
810             {
811                 aud_seeking = 0;
812                 Log::getInstance()->log("Demuxer", Log::DEBUG,
813                     "Leaving  audio sync: Audio PTS = %llu", audio_pts);
814             }
815         }
816     }
817     else if (packet.getPacketType() == PESTYPE_PRIVATE_1) // Private stream
818     {
819         if (!livetv) {
820                 //Inspired by vdr's device.c
821                 int payload_begin = packet[8]+9;
822                 unsigned char substream_id = packet[payload_begin];
823                 unsigned char substream_type = substream_id & 0xF0;
824                 unsigned char substream_index = substream_id & 0x1F;
825                 pre_1_3_19_Recording: //This is for old recordings stuff and live TV
826                 if (ispre_1_3_19)
827                 {
828                         int old_substream=packet.getSubstream();
829                         if (old_substream){ //someone else already set it, this is live tv
830                                 substream_id = old_substream;
831                                 substream_type = substream_id & 0xF0;
832                                 substream_index = substream_id & 0x1F;
833                         } else {
834                                 substream_id = PESTYPE_PRIVATE_1;
835                                 substream_type = 0x80;
836                                 substream_index = 0;
837                         }
838
839                 }
840                 switch (substream_type)
841                 {
842                 case 0x20://SPU
843                 case 0x30://SPU
844                         packet.setSubstream(substream_id);
845                         break;
846                 case 0xA0: //LPCM //not supported yet, is there any LPCM transmissio out there?
847                         break;
848                 case 0x80: //ac3, currently only one ac3 track per recording supported
849                         packet.setSubstream(substream_type+substream_index);
850
851                         // Extract audio PTS if it exists
852                         if (packet.hasPTS())
853                         {
854                                 audio_pts = packet.getPTS();
855                                 // We continue to seek on the audio if the video PTS that we
856                                 // are trying to match is ahead of the audio PTS by at most
857                                 // SEEK_THRESHOLD. We consider the possibility of PTS wrap.
858                                 if (aud_seeking && !vid_seeking &&
859                                                 !( (video_pts_seek > audio_pts &&
860                                                                 video_pts_seek - audio_pts < SEEK_THRESHOLD)
861                                                                 ||
862                                                                 (video_pts_seek < audio_pts &&
863                                                                                 video_pts_seek + (1LL<<33) - audio_pts < SEEK_THRESHOLD) ))
864                                 {
865                                         aud_seeking = 0;
866                                         Log::getInstance()->log("Demuxer", Log::DEBUG, "Leaving  audio sync: Audio PTS = %llu", audio_pts);
867                                 }
868                         }
869                         break;
870                 case 0x10: //Teletext Is this correct?
871                         packet.setSubstream(substream_id);
872                         // Extract teletxt PTS if it exists
873                         if (packet.hasPTS())
874                         {
875                                 teletext_pts = packet.getPTS();
876                         }
877                         break;
878                 default:
879                         if (!ispre_1_3_19)
880                         {
881                                 ispre_1_3_19=true; //switching to compat mode and live tv mode
882                                 goto pre_1_3_19_Recording;
883                         }
884                         else
885                         {
886                                 packet.setSubstream(0);
887                         }
888                         break;
889                 }
890         }
891     }
892     else if (packet.getPacketType() >= PESTYPE_VID0 &&
893         packet.getPacketType() <= PESTYPE_VIDMAX)
894     {
895         // Extract video PTS if it exists
896         if (packet.hasPTS()) video_pts = packet.getPTS();
897
898         // If there is a sequence header, extract information
899         UINT pos = packet.findSeqHeader(h264);
900         if (pos > 1)
901         {
902             if (!h264) {
903                 pos += 4;
904                 if (pos+6 >= packet.getSize()) return;
905                 horizontal_size = ((int)packet[pos] << 4) | ((int)packet[pos+1] >> 4);
906                 
907                 vertical_size = (((int)packet[pos+1] & 0xf) << 8) | (int)packet[pos+2];
908
909                 enum AspectRatio aspect=(enum AspectRatio)(packet[pos+3] >> 4);
910                 int aspectx=1;
911                 int aspecty=1;
912                 const int aspectDAR[]={0,1,1,1,4,3,16,9,221,100};
913                 int aspectDARx=aspectDAR[aspect*2];
914                 int aspectDARy=aspectDAR[aspect*2+1];
915
916                 aspectx=aspectDARx*vertical_size;
917                 aspecty=aspectDARy*horizontal_size;
918
919                 int commona;
920                 int commonb;
921                // Log::getInstance()->log("Demuxer", Log::DEBUG, "PAR test1 %d %d %d %d ", aspectx,aspecty,commona,commonb);
922                 commona=aspectx;
923                 commonb=aspecty;
924
925                 while (commonb) {
926                         int temp=commonb;
927                         commonb=commona%commonb;
928                         commona=temp;
929                 }
930                 aspectx=aspectx/commona;
931                 aspecty=aspecty/commona;
932                 //Log::getInstance()->log("Demuxer", Log::DEBUG, "PAR test2 %d %d %d %d %d %d %d", aspectx,aspecty,aspectDARx,aspectDARy,horizontal_size,vertical_size,commona);
933
934                 setAspectRatio(aspect,aspectx,aspecty);
935                 frame_rate = packet[pos+3] & 0x0f;
936                 if (frame_rate >= 1 && frame_rate <= 8)
937                     frame_rate = FrameRates[frame_rate];
938                 else
939                     frame_rate = 0;
940                 bit_rate = ((int)packet[pos+4] << 10) |
941                     ((int)packet[pos+5] << 2) |
942                     ((int)packet[pos+6] >> 6);
943             } 
944             else
945             {
946                 /* Chris and Mark I know this is ugly, should we move this to a method  of PESPacket or to NALUUnit what would be better?
947                 This looks so ugly since the header includes variable length parts and I have to parse through the whole header to get the wanted information*/
948                 NALUUnit nalu(packet.getData()+pos,packet.getSize()-pos);
949                 profile=nalu.getBits(8);
950                 nalu.getBits(8); //constraints
951                 nalu.getBits(8); //level_idc
952                 nalu.getUe(); //seq_parameter_set_id
953                 int chroma=1;
954                 if (profile==100 || profile==110 || profile==122 || profile==144)
955                 {
956                     chroma=nalu.getUe();
957                     if (chroma==3)
958                     {
959                         nalu.getBits(1);
960                     }
961                     nalu.getUe(); //bit depth lume
962                     nalu.getUe(); //bit depth chrome
963                     nalu.getBits(1);
964                     if (nalu.getBits(1))
965                     {
966                         for (int i=0;i<8;i++){
967                             if (nalu.getBits(1))
968                             {
969                                 if (i<6)
970                                 {
971                                     UINT lastscale=8;
972                                     UINT nextscale=8;
973                                     for (int j=0;j<16;j++) {
974                                         if (nextscale!=0) {
975                                             UINT delta=nalu.getSe();
976                                             nextscale=(lastscale+delta+256)%256;
977                                         }
978                                         lastscale=(nextscale==0)?lastscale:nextscale;
979                                     }
980                                 }
981                                 else
982                                 {
983                                     UINT lastscale=8;
984                                     UINT nextscale=8;
985                                     for (int j=0;j<64;j++) {
986                                         if (nextscale!=0) {
987                                             UINT delta=nalu.getSe();
988                                             nextscale=(lastscale+delta+256)%256;
989                                         }
990                                         lastscale=(nextscale==0)?lastscale:nextscale;
991                                     }
992                                 }
993                             }
994                         }
995                     }
996                 }
997                 int chromunitx=1;
998                 int chromunity=1;
999                 switch (chroma) {
1000                 case 0:
1001                     chromunitx=chromunity=1; break;
1002                 case 1:
1003                     chromunitx=chromunity=2; break;
1004                 case 2:
1005                     chromunitx=2;chromunity=1; break;
1006                 case 3:
1007                     chromunitx=chromunity=1; break;
1008                 };
1009
1010                 nalu.getUe(); //log2framenum
1011                 UINT temp=nalu.getUe();
1012                 if (temp==0) //pict order
1013                     nalu.getUe();
1014                 else if (temp==1) {
1015                     nalu.getBits(1);
1016                     nalu.getSe();
1017                     nalu.getSe();
1018                     UINT temp2=nalu.getUe();
1019                     for (UINT i=0;i<temp2;i++)
1020                         nalu.getSe();
1021                 }
1022                 nalu.getUe(); //Num refframes
1023                 nalu.getBits(1);
1024                 horizontal_size=(nalu.getUe()+1)*16;
1025                 
1026                 vertical_size=(nalu.getUe()+1)*16;
1027                 int tinterlaced=nalu.getBits(1);
1028                 vertical_size*=(2-tinterlaced);
1029                 interlaced=!tinterlaced;
1030                 
1031                 if (!tinterlaced) nalu.getBits(1);
1032                 nalu.getBits(1);
1033                 if (nalu.getBits(1))
1034                 {
1035                     horizontal_size-=nalu.getUe()*chromunitx;
1036                     horizontal_size-=nalu.getUe()*chromunitx;
1037                     vertical_size-=nalu.getUe()*(2-tinterlaced)*chromunity;
1038                     vertical_size-=nalu.getUe()*(2-tinterlaced)*chromunity;
1039                 }
1040                 if (nalu.getBits(1))
1041                 {
1042                     if (nalu.getBits(1))
1043                     {
1044                         UINT aspectratioidc=nalu.getBits(8);
1045                         bool hasaspect=false;
1046                         int aspectx,aspecty;
1047                         const float aspects[]={1., 1./1.,12./11.,10./11.,16./11.,40./33.,
1048                             24./11.,20./11.,32./11.,80./33.,18./11.,15./11.,64./33.,160./99.,4./3.,3./2.,2./1.};
1049                         const int aspectsx[]={1, 1,12,10,16,40,
1050                                                     24,20,32,80,18,15,64,160,4,3,2};
1051                         const int aspectsy[]={1, 1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1};
1052                       
1053                         float aspectratio=((float) horizontal_size)/((float) vertical_size);
1054                         if (aspectratioidc<=16) 
1055                         {
1056                             hasaspect=true;
1057                             aspectratio*=aspects[aspectratioidc];
1058                             aspectx=aspectsx[aspectratioidc];
1059                             aspecty=aspectsy[aspectratioidc];
1060                            
1061                         }
1062                         else if (aspectratioidc==255)
1063                         {
1064                             int t_sar_width=nalu.getBits(16);
1065                             int t_sar_height=nalu.getBits(16);
1066                             if (t_sar_width!=0 && t_sar_height!=0)
1067                             {
1068                                 hasaspect=true;
1069                                 aspectratio*=((float)t_sar_width)/((float)t_sar_height);
1070                                 aspectx=t_sar_width;
1071                                 aspecty=t_sar_height;
1072                             }
1073                         }
1074                         if (hasaspect)
1075                         {
1076                             if (fabs(aspectratio-16./9.)<0.1) setAspectRatio(ASPECT_16_9,aspectx,aspecty);
1077                             else if (fabs(aspectratio-4./3.)<0.1) setAspectRatio(ASPECT_4_3,aspectx,aspecty);
1078                             else  setAspectRatio(ASPECT_1_1,aspectx,aspecty);
1079                         }
1080                     }
1081
1082                 }
1083
1084             }
1085             UINT posext = packet.findSeqExtHeader(h264);
1086             if (posext>1) {
1087                 if (!h264) {
1088                         interlaced=!(packet[pos+1] & 0x08); //really simple
1089                         // if more than full hd is coming we need to add additional parsers here
1090                 } else {
1091                 /*      NALUUnit nalu(packet.getData()+posext,packet.getSize()-posext);
1092                         while (!nalu.isEonalu()) {
1093                                 unsigned int payloadtype=0;
1094                                 unsigned int payloadadd=0xFF;
1095                                 while (payloadadd==0xFF && !nalu.isEonalu()) {
1096                                         payloadadd=nalu.getBits(8);
1097                                         payloadtype+=payloadadd;
1098                                 }
1099                                 unsigned int payloadsize=0;
1100                                 payloadadd=0xff;
1101                                 while (payloadadd==0xFF && !nalu.isEonalu()) {
1102                                        payloadadd=nalu.getBits(8);
1103                                        payloadsize+=payloadadd;
1104                             }
1105                                 switch (payloadtype) {
1106                                 case 1: { // picture timing SEI
1107
1108                                 } break;
1109                                 default: {
1110                                         while (payloadsize) { // not handled skip
1111                                                 nalu.getBits(8);
1112                                                 payloadsize--;
1113                                         }
1114                                 } break;
1115                                 }
1116
1117
1118
1119                         }*/
1120
1121
1122                 }
1123             }
1124            
1125             if (vid_seeking)
1126             {
1127                 vid_seeking = 0;
1128                 video_pts_seek = video_pts;
1129                 Log::getInstance()->log("Demuxer", Log::DEBUG,
1130                     "Entering audio sync: Video PTS = %llu", video_pts);
1131                 Log::getInstance()->log("Demuxer", Log::DEBUG,
1132                     "Entering audio sync: Audio PTS = %llu", audio_pts);
1133             }
1134             return;
1135         } 
1136     }
1137 }
1138
1139 UINT Demuxer::stripAudio(UCHAR* buf, UINT len)
1140 {
1141   UINT read_pos = 0, write_pos = 0;
1142   UINT pattern, packet_length;
1143   if (len < 4) return 0;
1144   pattern = (buf[0] << 16) | (buf[1] << 8) | (buf[2]);
1145   while (read_pos + 7 <= len)
1146   {
1147     pattern = ((pattern & 0xFFFFFF) << 8) | buf[read_pos+3];
1148     if (pattern < (0x100|PESTYPE_VID0) || pattern > (0x100|PESTYPE_VIDMAX))
1149       read_pos++;
1150     else
1151     {
1152       packet_length = ((buf[read_pos+4] << 8) | (buf[read_pos+5])) + 6;
1153       if (read_pos + packet_length > len)
1154         read_pos = len;
1155       else
1156       {
1157         if (read_pos != write_pos)
1158           memmove(buf+write_pos, buf+read_pos, packet_length);
1159         read_pos += packet_length;
1160         write_pos += packet_length;
1161         pattern = (buf[read_pos] << 16) | (buf[read_pos+1] << 8)
1162                                         | (buf[read_pos+2]);
1163       }
1164     }
1165   }
1166   return write_pos;
1167 }
1168
1169 void Demuxer::changeTimes(UCHAR* buf, UINT len,UINT playtime)
1170 {
1171         UINT pattern, packet_length;
1172         UINT read_pos = 0;
1173         if (len < 4) return;
1174         pattern = (buf[0] << 16) | (buf[1] << 8) | (buf[2]);
1175         while (read_pos + 7 <= len)
1176         {
1177            pattern = ((pattern & 0xFFFFFF) << 8) | buf[read_pos+3];
1178            if (pattern < (0x100|PESTYPE_VID0) || pattern > (0x100|PESTYPE_VIDMAX))
1179               read_pos++;
1180            else
1181            {
1182               packet_length = ((buf[read_pos+4] << 8) | (buf[read_pos+5])) + 6;
1183               // ok we have a packet figure out if pts and dts are present and replace them
1184               if (read_pos + 19 > len) return;
1185               ULLONG new_ts=playtime*90; //play time is on ms so multiply it by 90
1186               if (buf[read_pos+7] & 0x80) { // pts is here, replace it
1187                   buf[read_pos+9]=0x21 | (( new_ts>>29)& 0xde );
1188                   buf[read_pos+10]=0x00 |(( new_ts>>22)& 0xff );
1189                   buf[read_pos+11]=0x01 | (( new_ts>>14)& 0xfe );
1190                   buf[read_pos+12]=0x00 | (( new_ts>>7)& 0xff );
1191                   buf[read_pos+13]=0x01 | (( new_ts<<1)& 0xfe );
1192               }
1193
1194               if (buf[read_pos+7] & 0x40) { // pts is here, replace it
1195                    buf[read_pos+14]=0x21 | (( new_ts>>29)& 0xde );
1196                    buf[read_pos+15]=0x00 | (( new_ts>>22)& 0xff );
1197                    buf[read_pos+16]=0x01 | (( new_ts>>14)& 0xfe );
1198                    buf[read_pos+17]=0x00 | (( new_ts>>7)& 0xff );
1199                    buf[read_pos+18]=0x01 | (( new_ts<<1)& 0xfe );
1200               }
1201               read_pos += packet_length;
1202               pattern = (buf[read_pos] << 16) | (buf[read_pos+1] << 8)
1203                                                 | (buf[read_pos+2]);
1204               }
1205           }
1206
1207 }
1208
1209 bool Demuxer::scanForVideo(UCHAR* buf, UINT len, bool &ish264)
1210 {
1211   UINT pos = 3;
1212   UINT pattern;
1213   ish264=false;
1214   if (len < 4) return false;
1215   pattern = (buf[0] << 16) | (buf[1] << 8) | (buf[2]);
1216   while (pos < len)
1217   {
1218     pattern = ((pattern & 0xFFFFFF) << 8) | buf[pos++];
1219     if (pattern >= (0x100|PESTYPE_VID0) && pattern <= (0x100|PESTYPE_VIDMAX))
1220       return true;
1221   }
1222   return false;
1223 }
1224
1225 bool* Demuxer::getmpAudioChannels()
1226 {
1227   return avail_mpaudchan;
1228 }
1229
1230 bool* Demuxer::getac3AudioChannels()
1231 {
1232   return avail_ac3audchan;
1233 }
1234
1235 bool* Demuxer::getSubtitleChannels()
1236 {
1237   return avail_dvbsubtitlechan;
1238 }
1239
1240 int Demuxer::getselSubtitleChannel()
1241 {
1242   return subtitle_current;
1243 }
1244
1245 int Demuxer::getselAudioChannel()
1246 {
1247   return audio_current;
1248 }
1249
1250