]> git.vomp.tv Git - vompclient.git/blob - demuxer.cc
Vogel Media Player 2008-11-28
[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 #define DEMUXER_SEQ_HEAD 0x000001B3
31 #define DEMUXER_PIC_HEAD 0x00000101
32 #define SEEK_THRESHOLD 150000 // About 1.5 seconds
33
34 // Statics
35 const int Demuxer::FrameRates[9] = { 0, 23, 24, 25, 29, 30, 50, 59, 60 };
36 Demuxer* Demuxer::instance = NULL;
37
38 static const int PESPacket_initial_size = 2000;
39
40 // PESPacket methods
41 PESPacket::PESPacket()
42 {
43   data_size = PESPacket_initial_size;
44   data = (UCHAR*)malloc(data_size);
45   data[0] = 0x00;
46   data[1] = 0x00;
47   data[2] = 0x01;
48   init(0);
49 }
50
51 PESPacket::PESPacket(const PESPacket& packet)
52 {
53   copyFrom(packet);
54 }
55
56 PESPacket& PESPacket::operator=(const PESPacket& packet)
57 {
58   if (this != &packet)
59   {
60     if (data) free(data);
61     copyFrom(packet);
62   }
63   return *this;
64 }
65
66 PESPacket::~PESPacket()
67 {
68   if (data) free(data);
69 }
70
71 void PESPacket::copyFrom(const PESPacket& packet)
72 {
73   length = packet.length;
74   size = packet.size;
75   packetType = packet.packetType;
76   substream = packet.substream;
77   seq_header = packet.seq_header;
78   data_size = size;
79   data = (UCHAR*)malloc(data_size);
80   memcpy(data, packet.data, data_size);
81 }
82
83 void PESPacket::init(UCHAR type, UCHAR sub)
84 {
85   length = 0; 
86   size = 6;
87   data[4] = data[5] = 0;
88   data[3] = type;
89   packetType = type;
90   substream = sub;
91   seq_header = 1; // Unknown seq_header status
92 }
93
94 void PESPacket::truncate()
95 {
96   init(packetType,substream);
97 }
98
99 int PESPacket::write(const UCHAR *buf, int len)
100 {
101   if (size + len > 0x10000) return 0;
102   if (size + len > data_size)
103   { // Reallocate
104     UINT new_data_size = max(data_size + data_size / 2, data_size + len);
105     if (new_data_size > 0x10000) new_data_size = 0x10000;
106     data_size = new_data_size;
107     data = (UCHAR*)realloc(data, data_size);
108   }
109   memcpy(data + size, buf, len);
110   length += len;
111   size += len;
112   data[4] = (length >> 8);
113   data[5] = (length & 0xFF);
114   // We have added data - reset seq_header indicator if necessary
115   if (seq_header == 0) seq_header = 1; // Reset to 'unknown'
116   return 1;
117 }
118
119 ULLONG PESPacket::getPTS() const
120 {
121   if ( ( (packetType >= Demuxer::PESTYPE_AUD0 &&
122           packetType <= Demuxer::PESTYPE_AUDMAX)
123          ||
124          (packetType >= Demuxer::PESTYPE_VID0 &&
125           packetType <= Demuxer::PESTYPE_VIDMAX)
126    ||
127           packetType == Demuxer::PESTYPE_PRIVATE_1
128        )
129        && size >= 14 && data[7] & 0x80)
130   {
131     return ( (ULLONG)(data[ 9] & 0x0E) << 29) |
132            ( (ULLONG)(data[10])        << 22 ) |
133            ( (ULLONG)(data[11] & 0xFE) << 14 ) |
134            ( (ULLONG)(data[12])        <<  7 ) |
135            ( (ULLONG)(data[13] & 0xFE) >>  1 );
136   }
137   else return PTS_INVALID;
138 }
139
140 UCHAR PESPacket::operator[] (UINT index) const
141 {
142   if (index >= size)
143     return 0;
144   else
145     return data[index];
146 }
147
148 UINT PESPacket::findPictureHeader() const
149 {
150   if (size < 12) return 0;
151   UINT pattern = ( ((UINT)data[ 8] << 24) |
152                    ((UINT)data[ 9] << 16) |
153                    ((UINT)data[10] <<  8) |
154                     (UINT)data[11]  );
155   UINT pos = 11;
156   while (pattern != DEMUXER_PIC_HEAD)
157   {
158     if (++pos >= size) return 0;
159     pattern = (pattern << 8) | data[pos];
160   }
161   return pos-3;
162 }
163
164 UINT PESPacket::findSeqHeader() const
165 {
166   if (seq_header != 1) return seq_header;
167   if (size < 12) return 0;
168   UINT pattern = ( ((UINT)data[ 8] << 24) |
169                    ((UINT)data[ 9] << 16) |
170                    ((UINT)data[10] <<  8) |
171                     (UINT)data[11]  );
172   UINT pos = 11;
173   while (pattern != DEMUXER_SEQ_HEAD)
174   {
175     if (++pos >= size)
176     {
177       seq_header = 0;
178       return 0;
179     }
180     pattern = (pattern << 8) | data[pos];
181   }
182   seq_header = pos - 3;
183   return seq_header;
184 }
185
186 // Demuxer methods
187 Demuxer::Demuxer()
188 {
189   if (instance) return;
190   instance = this;
191   initted = false;
192   callback = NULL;
193   arcnt = 0;
194   vid_seeking = aud_seeking = false;
195   video_pts = audio_pts = 0;
196   ispre_1_3_19 = false;
197 }
198
199 Demuxer::~Demuxer()
200 {
201   shutdown();
202   instance = NULL;
203 }
204
205 Demuxer* Demuxer::getInstance()
206 {
207   return instance;
208 }
209
210 int Demuxer::init(Callback* tcallback, DrainTarget* audio, DrainTarget* video, ULONG demuxMemoryV, ULONG demuxMemoryA, DVBSubtitles* tsubtitles)
211 {
212   if (!initted)
213   {
214     if ( !videostream.init(video, demuxMemoryV) ||
215          !audiostream.init(audio, demuxMemoryA))
216     {
217       Log::getInstance()->log("Demuxer", Log::CRIT,
218                               "Failed to initialize demuxer");
219       shutdown();
220       return 0;
221     }
222   }
223
224   reset();
225   initted = true;
226   subtitles = tsubtitles;
227   callback = tcallback;
228   return 1;
229 }
230
231 void Demuxer::reset()
232 {
233   Log::getInstance()->log("Demuxer", Log::DEBUG, "Reset called");
234   flush();
235   video_current = audio_current = -1;
236   horizontal_size = vertical_size = 0;
237   aspect_ratio = (enum AspectRatio) 0;
238   frame_rate = bit_rate = 0;
239   ispre_1_3_19 = false;
240
241   for (int i = 0; i <= (PESTYPE_AUDMAX - PESTYPE_AUD0); i++)
242   {
243     avail_mpaudchan[i] = false;
244   }
245   for (int i = 0; i <= (PESTYPE_SUBSTREAM_AC3MAX - PESTYPE_SUBSTREAM_AC30); i++)
246   {
247     avail_ac3audchan[i] = false;
248   }
249 }
250
251 int Demuxer::shutdown()
252 {
253   videostream.shutdown();
254   audiostream.shutdown();
255   initted = false;
256   return 1;
257 }
258
259 void Demuxer::flush()
260 {
261   Log::getInstance()->log("Demuxer", Log::DEBUG, "Flush called");
262
263   videostream.flush();
264   audiostream.flush();
265 }
266
267 void Demuxer::flushAudio()
268 {
269   audiostream.flush();
270 }
271
272 void Demuxer::seek()
273 {
274   vid_seeking = aud_seeking = true;
275   video_pts = audio_pts = 0;
276 }
277
278 void Demuxer::setAudioStream(int id)
279 {
280   audio_current = id;
281 }
282
283 void Demuxer::setVideoStream(int id)
284 {
285   video_current = id;
286 }
287
288 void Demuxer::setAspectRatio(enum AspectRatio ar)
289 {
290   if (aspect_ratio != ar)
291   {
292     Log::getInstance()->log("Demux", Log::DEBUG,
293                             "Aspect ratio difference signalled");
294     if (++arcnt > 3) // avoid changing aspect ratio if glitch in signal
295     {
296       arcnt = 0;
297       aspect_ratio = ar;
298       if (callback) callback->call(this);
299     }
300   }
301   else
302     arcnt = 0;
303 }
304
305 bool Demuxer::writeAudio()
306 {
307   return audiostream.drain();
308 }
309
310 bool Demuxer::writeVideo()
311 {
312   return videostream.drain();
313 }
314
315 bool Demuxer::submitPacket(PESPacket& packet)
316 {
317   UINT sent = 0;
318   UCHAR packet_type = packet.getPacketType();
319   const UCHAR* packetdata = packet.getData();
320
321   if (packet_type >= PESTYPE_VID0 && packet_type <= PESTYPE_VIDMAX)
322   {
323     if (video_current == -1) video_current = packet_type;
324     if (video_current == packet_type && !vid_seeking)
325       sent = videostream.put(&packetdata[0], packet.getSize(), MPTYPE_VIDEO);
326     else
327       sent = packet.getSize();
328   }
329   else if (packet_type >= PESTYPE_AUD0 && packet_type <= PESTYPE_AUDMAX)
330   {
331     if (audio_current == -1) audio_current = packet_type;
332     avail_mpaudchan[packet_type - PESTYPE_AUD0] = true;
333     if (audio_current == packet_type && !aud_seeking)
334       sent = audiostream.put(&packetdata[0], packet.getSize(), MPTYPE_MPEG_AUDIO);
335     else
336       sent = packet.getSize();
337   }
338   else if (packet_type == PESTYPE_PRIVATE_1 &&
339            packet.getSubstream() >= PESTYPE_SUBSTREAM_AC30 &&
340            packet.getSubstream() <= PESTYPE_SUBSTREAM_AC3MAX)
341   {
342     avail_ac3audchan[packet.getSubstream() - PESTYPE_SUBSTREAM_AC30] = true;
343     if (packet.getSubstream() == audio_current)
344     {
345       sent = audiostream.put(&packetdata[0], packet.getSize(), (ispre_1_3_19)? MPTYPE_AC3_PRE13 : MPTYPE_AC3);
346     }
347     else
348     {
349       sent = packet.getSize();
350     }
351   }
352   else if (packet_type == PESTYPE_PRIVATE_1 &&
353            packet.getSubstream() == 0x20)
354   {
355     if (subtitles) subtitles->put(packet);
356     sent = packet.getSize();
357   }
358   else
359   {
360     sent = packet.getSize();
361   }
362
363   if (sent < packet.getSize()) // Stream is full.
364     return false;
365   else
366     return true;
367 }
368
369 void Demuxer::parsePacketDetails(PESPacket& packet)
370 {
371   if (packet.getPacketType() >= PESTYPE_AUD0 &&
372       packet.getPacketType() <= PESTYPE_AUDMAX)
373   {
374     // Extract audio PTS if it exists
375     if (packet.hasPTS())
376     {
377       audio_pts = packet.getPTS();
378       // We continue to seek on the audio if the video PTS that we
379       // are trying to match is ahead of the audio PTS by at most
380       // SEEK_THRESHOLD. We consider the possibility of PTS wrap.
381       if (aud_seeking && !vid_seeking &&
382           !( (video_pts_seek > audio_pts &&
383               video_pts_seek - audio_pts < SEEK_THRESHOLD)
384               ||
385              (video_pts_seek < audio_pts &&
386               video_pts_seek + (1LL<<33) - audio_pts < SEEK_THRESHOLD) ))
387       {
388         aud_seeking = 0;
389         Log::getInstance()->log("Demuxer", Log::DEBUG,
390             "Leaving  audio sync: Audio PTS = %llu", audio_pts);
391       }
392     }
393   }
394   else if (packet.getPacketType() == PESTYPE_PRIVATE_1) // Private stream
395   {
396     //Inspired by vdr's device.c
397     int payload_begin = packet[8]+9;
398     unsigned char substream_id = packet[payload_begin];
399     unsigned char substream_type = substream_id & 0xF0;
400     unsigned char substream_index = substream_id & 0x1F;
401 pre_1_3_19_Recording: //This is for old recordings stuff and live TV
402     if (ispre_1_3_19)
403     {
404       substream_id = PESTYPE_PRIVATE_1;
405       substream_type = 0x80;
406       substream_index = 0;
407     }
408     switch (substream_type)
409     {
410       case 0x20://SPU
411       case 0x30://SPU
412         packet.setSubstream(substream_id);
413         break;
414       case 0xA0: //LPCM //not supported yet, is there any LPCM transmissio out there?
415         break;
416       case 0x80: //ac3, currently only one ac3 track per recording supported
417         packet.setSubstream(substream_type+substream_index);
418
419         // Extract audio PTS if it exists
420         if (packet.hasPTS())
421         {
422           audio_pts = packet.getPTS();
423           // We continue to seek on the audio if the video PTS that we
424           // are trying to match is ahead of the audio PTS by at most
425           // SEEK_THRESHOLD. We consider the possibility of PTS wrap.
426           if (aud_seeking && !vid_seeking &&
427               !( (video_pts_seek > audio_pts &&
428                   video_pts_seek - audio_pts < SEEK_THRESHOLD)
429               ||
430               (video_pts_seek < audio_pts &&
431                     video_pts_seek + (1LL<<33) - audio_pts < SEEK_THRESHOLD) ))
432           {
433             aud_seeking = 0;
434             Log::getInstance()->log("Demuxer", Log::DEBUG, "Leaving  audio sync: Audio PTS = %llu", audio_pts);
435           }
436         }
437         break;
438       default:
439         if (!ispre_1_3_19)
440         {
441           ispre_1_3_19=true; //switching to compat mode and live tv mode
442           goto pre_1_3_19_Recording;
443         }
444         else
445         {
446           packet.setSubstream(0);
447         }
448         break;
449     }
450   }
451   else if (packet.getPacketType() >= PESTYPE_VID0 &&
452            packet.getPacketType() <= PESTYPE_VIDMAX)
453   {
454     // Extract video PTS if it exists
455     if (packet.hasPTS()) video_pts = packet.getPTS();
456
457     // If there is a sequence header, extract information
458     UINT pos = packet.findSeqHeader();
459     if (pos > 1)
460     {
461       pos += 4;
462       if (pos+6 >= packet.getSize()) return;
463       horizontal_size = ((int)packet[pos] << 4) | ((int)packet[pos+1] >> 4);
464       vertical_size = (((int)packet[pos+1] & 0xf) << 8) | (int)packet[pos+2];
465       setAspectRatio((enum AspectRatio)(packet[pos+3] >> 4));
466       frame_rate = packet[pos+3] & 0x0f;
467       if (frame_rate >= 1 && frame_rate <= 8)
468         frame_rate = FrameRates[frame_rate];
469       else
470         frame_rate = 0;
471       bit_rate = ((int)packet[pos+4] << 10) |
472                  ((int)packet[pos+5] << 2) |
473                  ((int)packet[pos+6] >> 6);
474       if (vid_seeking)
475       {
476         vid_seeking = 0;
477         video_pts_seek = video_pts;
478         Log::getInstance()->log("Demuxer", Log::DEBUG,
479             "Entering audio sync: Video PTS = %llu", video_pts);
480         Log::getInstance()->log("Demuxer", Log::DEBUG,
481             "Entering audio sync: Audio PTS = %llu", audio_pts);
482       }
483       return;
484     }
485   }
486 }
487
488 UINT Demuxer::stripAudio(UCHAR* buf, UINT len)
489 {
490   UINT read_pos = 0, write_pos = 0;
491   UINT pattern, packet_length;
492   if (len < 4) return 0;
493   pattern = (buf[0] << 16) | (buf[1] << 8) | (buf[2]);
494   while (read_pos + 7 <= len)
495   {
496     pattern = ((pattern & 0xFFFFFF) << 8) | buf[read_pos+3];
497     if (pattern < (0x100|PESTYPE_VID0) || pattern > (0x100|PESTYPE_VIDMAX))
498       read_pos++;
499     else
500     {
501       packet_length = ((buf[read_pos+4] << 8) | (buf[read_pos+5])) + 6;
502       if (read_pos + packet_length > len)
503         read_pos = len;
504       else
505       {
506         if (read_pos != write_pos)
507           memmove(buf+write_pos, buf+read_pos, packet_length);
508         read_pos += packet_length;
509         write_pos += packet_length;
510         pattern = (buf[read_pos] << 16) | (buf[read_pos+1] << 8)
511                                         | (buf[read_pos+2]);
512       }
513     }
514   }
515   return write_pos;
516 }
517
518 bool Demuxer::scanForVideo(UCHAR* buf, UINT len)
519 {
520   UINT pos = 3;
521   UINT pattern;
522   if (len < 4) return false;
523   pattern = (buf[0] << 16) | (buf[1] << 8) | (buf[2]);
524   while (pos < len)
525   {
526     pattern = ((pattern & 0xFFFFFF) << 8) | buf[pos++];
527     if (pattern >= (0x100|PESTYPE_VID0) && pattern <= (0x100|PESTYPE_VIDMAX))
528       return true;
529   }
530   return false;
531 }
532
533 bool* Demuxer::getmpAudioChannels()
534 {
535   return avail_mpaudchan;
536 }
537
538 bool* Demuxer::getac3AudioChannels()
539 {
540   return avail_ac3audchan;
541 }
542
543 int Demuxer::getselAudioChannel()
544 {
545   return audio_current;
546 }
547
548 void Demuxer::setAudioChannel(int aud_channel)
549 {
550   audio_current = aud_channel;
551 }