]> git.vomp.tv Git - vompclient-marten.git/blob - demuxer.cc
remove seek call
[vompclient-marten.git] / demuxer.cc
1 /*
2     Copyright 2005-2006 Mark Calderbank
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP; if not, write to the Free Software
18     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 */
20
21 #include "demuxer.h"
22 #include <endian.h>
23
24 const int Demuxer::FrameRates[9] = { 0, 23, 24, 25, 29, 30, 50, 59, 60 };
25
26 Demuxer* Demuxer::instance = NULL;
27
28 Demuxer::Demuxer()
29 {
30   if (instance) return;
31   instance = this;
32   initted = 0;
33   callback = NULL;
34   arcnt = 0;
35 }
36
37 Demuxer::~Demuxer()
38 {
39   shutdown();
40   instance = NULL;
41 }
42
43 Demuxer* Demuxer::getInstance()
44 {
45   return instance;
46 }
47
48 int Demuxer::init(Callback* tcallback)
49 {
50   if (!initted)
51   {
52     if ( !videostream.init(demuxMemoryV) ||
53          !audiostream.init(demuxMemoryA) ||
54          !(local_frame = (UCHAR *) malloc(0x10000)))
55     {
56       Log::getInstance()->log("Demuxer", Log::CRIT, "Failed to initialize demuxer");
57       shutdown();
58       return 0;
59     }
60 #ifdef NEW_DEMUXER
61     videostream.setDrainTarget(Video::getInstance());
62     audiostream.setDrainTarget(Audio::getInstance());
63 #endif
64   }
65
66   reset();
67   initted = 1;
68   callback = tcallback;
69   return 1;
70 }
71
72 void Demuxer::reset()
73 {
74   flush();
75   video_current = audio_current = -1;
76   horizontal_size = vertical_size = 0;
77   aspect_ratio = (enum AspectRatio) 0;
78   frame_rate = bit_rate = 0;
79 }
80
81 int Demuxer::shutdown()
82 {
83   videostream.shutdown();
84   audiostream.shutdown();
85   free(local_frame);
86   initted = 0;
87   return 1;
88 }
89
90 void Demuxer::flush()
91 {
92   videostream.flush();
93   audiostream.flush();
94   state_frametype = state_framepos = 0;
95 }
96
97 void Demuxer::flushAudio()
98 {
99   audiostream.flush();
100 }
101
102 void Demuxer::seek()
103 {
104   vid_seeking = aud_seeking = 1;
105   video_pts = audio_pts = 0;
106 }
107
108 void Demuxer::setAudioStream(int id)
109 {
110   audio_current = id;
111 }
112
113 void Demuxer::setVideoStream(int id)
114 {
115   video_current = id;
116 }
117
118 void Demuxer::setAspectRatio(enum AspectRatio ar)
119 {
120   if (aspect_ratio != ar)
121   {
122     Log::getInstance()->log("Demux", Log::DEBUG, "Aspect ratio difference signalled");
123     if (++arcnt > 3) // avoid changing aspect ratio if glitch in signal
124     {
125       arcnt = 0;
126       aspect_ratio = ar;
127       callback->call(this);
128     }
129   }
130   else
131     arcnt = 0;
132 }
133 #ifndef NEW_DEMUXER
134 int Demuxer::writeAudio(int fd)
135 {
136   return audiostream.drain(fd);
137 }
138
139 int Demuxer::writeVideo(int fd)
140 {
141   return videostream.drain(fd);
142 }
143 #else
144 int Demuxer::writeAudio(DrainTarget* dt)
145 {
146   return audiostream.drain(dt);
147 }
148
149 int Demuxer::writeVideo(DrainTarget* dt)
150 {
151   return videostream.drain(dt);
152 }
153 #endif
154
155
156 int Demuxer::scan(UCHAR *buf, int len)
157 {
158   // Temporarily, just look for the lowest audio stream and return it
159   int ret = 0;
160   UCHAR byte;
161   int zeros = 0;
162   while (len > 1)
163   {
164     // We are searching for a string of bytes (0,0,1).
165     byte = *(buf++); --len;
166
167     if (byte == 0)
168     {
169       ++zeros; continue;
170     }
171     if (zeros < 2 || byte != 1)
172     {
173       zeros = 0; continue;
174     }
175     zeros = 0;
176     // We have found the pattern (0,0,1).
177     // Check the next byte for the sub-frame type.
178     byte = *(buf++); --len;
179     if (byte >= 0xc0 && byte <= 0xdf) // Audio
180       if (ret == 0 || ret > byte) ret = byte;
181   }
182   return ret;
183 }
184
185 int Demuxer::put(UCHAR* buf, int len)
186 {
187   int ret = 0;    // return number of bytes consumed
188   int parsed = 0; // number of bytes parsed by sub-function
189   int full;       // sub-function sets this to tell us to exit early
190   inbuf = buf;    // Initialize buffer pointer
191
192   while (len)
193   {
194     full = 0;
195
196     if (state_frametype == 0) // Search for frame
197     {
198       parsed = parse_find_frame(len);
199     }
200     else if ((state_frametype >= FRAMETYPE_VID0) && (state_frametype <= FRAMETYPE_VIDMAX))
201     {
202       parsed = parse_video_frame(len, &full);
203     }
204     else if ((state_frametype >= FRAMETYPE_AUD0) && (state_frametype <= FRAMETYPE_AUDMAX))
205     {
206       parsed = parse_audio_frame(len, &full);
207     }
208     else if (state_frametype == FRAMETYPE_PRIVATE_1)
209     {
210       parsed = parse_private1_frame(len, &full);
211     }
212
213     ret += parsed; len -= parsed;
214     if (full) // We have to exit early.
215       break; // out of while loop
216   }
217   //Log::getInstance()->log("Demuxer", Log::DEBUG, "Put %d; took %d", ret + len, ret);
218   return ret;
219 }
220
221 int Demuxer::parse_find_frame(int len)
222 {
223   int ret = 0; // return number of bytes parsed
224   UCHAR byte;
225
226   // In this function, state_framepos represents
227   // the number of fixed header bytes found so far.
228   if (state_framepos > 3 || state_framepos < 0)
229   {
230     // ERROR!
231     state_framepos = 0;
232   }
233
234   while (len)
235   {
236     byte = *inbuf++;
237     ++ret; --len;
238     switch (state_framepos)
239     {
240       case 0:
241       case 1:
242         if (byte == 0)
243           ++state_framepos;
244         else
245           state_framepos = 0;
246         break;
247       case 2:
248         if (byte == 1)
249           ++state_framepos;
250         else if (byte != 0)
251           state_framepos = 0;
252         break;
253       default:
254         state_framepos = 0; // Set initial state for the new frame
255
256         if (byte == 0)
257         {
258           state_framepos = 1; // Count this as a first header byte!
259         }
260         else if (  ((byte >= FRAMETYPE_VID0) && (byte <= FRAMETYPE_VIDMAX))
261                 || ((byte >= FRAMETYPE_AUD0) && (byte <= FRAMETYPE_AUDMAX))
262                 || byte==FRAMETYPE_PRIVATE_1 )
263         {
264           state_frametype = byte;
265           return ret;
266         }
267
268         // Not a recognised frame type. Go back to Old Kent Road.
269         break;
270     }
271   }
272   return ret;
273 }
274
275 int Demuxer::parse_video_frame(int len, int* full)
276 {
277   int ret = 0; // return number of bytes consumed
278   int bytes_remaining;
279
280   switch(state_framepos)
281   {
282     case 0: // Brand new video frame. Set initial states.
283       state_stream_fill = 0; state_vid_parsed = 0;
284       // Create a local copy of the frame header
285       local_frame[0] = local_frame[1] = 0; local_frame[2] = 1;
286       local_frame[3] = state_frametype;
287       // If no video stream has been set, use this one.
288       if (video_current == -1) video_current = state_frametype;
289       // Get MSB of frame length and copy to local frame.
290       frame_length = *inbuf << 8;
291       local_frame[4] = *inbuf;
292       ++inbuf; ++state_framepos; ++ret; --len;
293       if (len == 0) return ret;
294       // FALL THROUGH TO NEXT BYTE IN STREAM
295     case 1: // Get LSB of frame length and copy to local frame.
296       frame_length += *inbuf;
297       local_frame[5] = *inbuf;
298       ++inbuf; ++state_framepos; ++ret; --len;
299       if (len == 0) return ret;
300   }
301   // We are in the frame data
302   bytes_remaining = 2 + frame_length - state_framepos;
303   if (video_current != state_frametype)
304   {
305     // We don't want this frame. Throw it away.
306     if (len >= bytes_remaining)
307     {
308       inbuf += bytes_remaining;
309       ret += bytes_remaining;
310       state_frametype = state_framepos = 0;
311       return ret;
312     }
313     else
314     {
315       inbuf += len; ret += len;
316       state_framepos += len;
317       return ret;
318     }
319   } // No fall through here
320
321   if (bytes_remaining)   // There is data yet to copy to local_frame
322   {
323     if (len > bytes_remaining) len = bytes_remaining;
324     memcpy(local_frame + state_framepos + 4, inbuf, len);
325     inbuf += len; ret += len; state_framepos += len;
326     if (len < bytes_remaining)   // Not all arrived yet
327       return ret;
328     parse_video_details(local_frame+6, frame_length);
329   }
330
331   if (!vid_seeking)
332   {
333   // We have the whole frame in local_frame. Send it to the stream.
334   // We still support streams that might not consume all the data.
335     state_stream_fill += videostream.put(local_frame,
336                     6 + frame_length - state_stream_fill);
337     if (state_stream_fill < frame_length + 6)   // stream is full!
338     {
339       *full = 1; return ret;
340     }
341   }
342   state_frametype = state_framepos = 0;
343   return ret;
344 }
345
346 int Demuxer::parse_audio_frame(int len, int* full)
347 {
348   int ret = 0; // return number of bytes consumed
349   int bytes_remaining;
350
351   switch(state_framepos)
352   {
353     case 0: // Brand new audio frame. Set initial states.
354       state_stream_fill = 0;
355       // Create a local copy of the frame header
356       local_frame[0] = local_frame[1] = 0; local_frame[2] = 1;
357       local_frame[3] = state_frametype;
358       // If no audio stream has been set, use this one.
359       if (audio_current == -1) audio_current = state_frametype;
360       // Get MSB of frame length and copy to local frame.
361       frame_length = *inbuf << 8;
362       local_frame[4] = *inbuf;
363       ++inbuf; ++state_framepos; ++ret; --len;
364       if (len == 0) return ret;
365       // FALL THROUGH TO NEXT BYTE IN STREAM
366     case 1: // Get LSB of frame length and copy to local frame.
367       frame_length += *inbuf;
368       local_frame[5] = *inbuf;
369       ++inbuf; ++state_framepos; ++ret; --len;
370       if (len == 0) return ret;
371   }
372   // We are in the frame data
373   bytes_remaining = 2 + frame_length - state_framepos;
374   if (audio_current != state_frametype)
375   {
376     // We don't want this frame. Throw it away.
377     if (len >= bytes_remaining)
378     {
379       inbuf += bytes_remaining;
380       ret += bytes_remaining;
381       state_frametype = state_framepos = 0;
382       return ret;
383     }
384     else
385     {
386       inbuf += len; ret += len;
387       state_framepos += len;
388       return ret;
389     }
390   } // No fall through is allowed here
391
392   if (bytes_remaining)   // There is data yet to copy to local_frame
393   {
394     if (len > bytes_remaining) len = bytes_remaining;
395     memcpy(local_frame + state_framepos + 4, inbuf, len);
396     inbuf += len; ret += len; state_framepos += len;
397     if (len < bytes_remaining)   // Not all arrived yet
398       return ret;
399     parse_audio_details(local_frame+6, frame_length);
400   }
401
402   if (!aud_seeking)
403   {
404     // We have the whole frame in local_frame. Send it to the stream.
405     // We still support streams that might not consume all the data.
406     state_stream_fill += audiostream.put(local_frame,
407                     6 + frame_length - state_stream_fill);
408     if (state_stream_fill < frame_length + 6)   // stream is full!
409     {
410       *full = 1; return ret;
411     }
412   }
413   state_frametype = state_framepos = 0;
414   return ret;
415 }
416
417 int Demuxer::parse_private1_frame(int len, int* full)
418 {
419   int ret = 0; // return number of bytes consumed
420   int bytes_remaining;
421
422   switch(state_framepos)
423   {
424     case 0: // Brand new frame. Set initial states.
425       // Get MSB of frame length and copy to local frame.
426       frame_length = *inbuf << 8;
427       ++inbuf; ++state_framepos; ++ret; --len;
428       if (len == 0) return ret;
429       // FALL THROUGH TO NEXT BYTE IN STREAM
430     case 1: // Get LSB of frame length and copy to local frame.
431       frame_length += *inbuf;
432       local_frame[5] = *inbuf;
433       ++inbuf; ++state_framepos; ++ret; --len;
434       if (len == 0) return ret;
435   }
436   // We are in the frame data
437   bytes_remaining = 2 + frame_length - state_framepos;
438   // Temporary - just discard the frame.
439   if (len >= bytes_remaining)
440   {
441     inbuf += bytes_remaining;
442     ret += bytes_remaining;
443     state_frametype = state_framepos = 0;
444     return ret;
445   }
446   else
447   {
448     inbuf += len; ret += len;
449     state_framepos += len;
450     return ret;
451   }
452 }
453
454 void Demuxer::parse_audio_details(UCHAR* buf, int len)
455 {
456   // Extract audio PTS if it exists
457   if ( buf[1] & 0x80 ) // PTS_DTS_flags indicate that PTS is present
458   {
459     audio_pts = ( (ULLONG)(buf[3] & 0x0E) << 29 ) |
460                 ( (ULLONG)(buf[4])        << 22 ) |
461                 ( (ULLONG)(buf[5] & 0xFE) << 14 ) |
462                 ( (ULLONG)(buf[6])        <<  7 ) |
463                 ( (ULLONG)(buf[7] & 0xFE) >>  1 );
464     if (aud_seeking && !vid_seeking && audio_pts >= video_pts_seek)
465     {
466       aud_seeking = 0;
467       Log::getInstance()->log("Demuxer", Log::DEBUG,
468           "Leaving  audio seek: Audio PTS = %llu", audio_pts);
469     }
470   }
471 }
472
473 void Demuxer::parse_video_details(UCHAR* buf, int len)
474 {
475   // Extract video PTS if it exists
476   if ( buf[1] & 0x80 ) // PTS_DTS_flags indicate that PTS is present
477   {
478     video_pts = ( (ULLONG)(buf[3] & 0x0E) << 29 ) |
479                 ( (ULLONG)(buf[4])        << 22 ) |
480                 ( (ULLONG)(buf[5] & 0xFE) << 14 ) |
481                 ( (ULLONG)(buf[6])        <<  7 ) |
482                 ( (ULLONG)(buf[7] & 0xFE) >>  1 );
483   }
484   // Now, scan for a GOP header and extract video information
485   UCHAR byte;
486   int zeros = 0;
487   while (len >= 8) // 8 is length of a GOP header
488   {
489     // We are searching for a string of bytes (0,0,1).
490     byte = *(buf++); --len;
491
492     if (byte == 0)
493     {
494       ++zeros; continue;
495     }
496     if (zeros < 2 || byte != 1)
497     {
498       zeros = 0; continue;
499     }
500     zeros = 0;
501     // We have found the pattern (0,0,1).
502     // Check the next byte for the sub-frame type.
503     byte = *(buf++); --len;
504     switch (byte)
505     {
506 /*      case 0x00: // Picture header
507                  // 10 bits: temporal reference
508                  //  3 bits: coding type (I/P/B)
509                  //  ...
510         if (len < 2) return;
511         if ( (buf[1] & 0x38) == 0x08 ) // I-frame
512           seeking = 0;
513         buf += 4; // Minimum length of picture header
514         len -= 4;
515         break;
516 */
517       case 0xb3: // Sequence header
518                  // 12 bits: Horizontal size
519                  // 12 bits: Vertical size
520                  //  4 bits: Aspect ratio
521                  //  4 bits: Frame rate code
522                  // 18 bits: Bit rate value
523                  // ...
524         if (len < 7) return;
525         horizontal_size = ((int)buf[0] << 4) | ((int)buf[1] >> 4);
526         vertical_size = (((int)buf[1] & 0xf) << 8) | (int)buf[2];
527         setAspectRatio((enum AspectRatio)(buf[3] >> 4));
528         frame_rate = buf[3] & 0x0f;
529         if (frame_rate >= 1 && frame_rate <= 8)
530           frame_rate = FrameRates[frame_rate];
531         else
532           frame_rate = 0;
533         bit_rate = ((int)buf[4] << 10) |
534                    ((int)buf[5] << 2) |
535                    ((int)buf[6] >> 6);
536         if (vid_seeking)
537         {
538           vid_seeking = 0;
539           video_pts_seek = video_pts;
540           Log::getInstance()->log("Demuxer", Log::DEBUG,
541               "Entering video seek: Video PTS = %llu", video_pts);
542           Log::getInstance()->log("Demuxer", Log::DEBUG,
543               "Entering video seek: Audio PTS = %llu", audio_pts);
544         }
545         buf += 8; // Minimum length of sequence header
546         len -= 8;
547         break;
548 /*
549       case 0xb8: // Group header
550                  // We're not going to bother parsing anything.
551         seeking = 0;
552         buf += 4; // Minimum length of group header
553         len -= 4;
554         break;
555 */
556     }
557   }
558 }
559
560 int Demuxer::findVideoPTS(UCHAR* buf, int len, ULLONG* dest)
561 {
562   while (len >= 14)
563   {
564     UINT pattern = *(UINT*)buf;
565     buf++; len--;
566 #if __BYTE_ORDER == __BIG_ENDIAN
567     if (pattern < (0x100 | FRAMETYPE_VID0) ||
568         pattern > (0x100 | FRAMETYPE_VIDMAX)) continue;
569 #else
570     if ((pattern & 0xFFFFFF) != 0x010000 ||
571          pattern < ((UINT)FRAMETYPE_VID0 << 24) ||
572          pattern > ((UINT)FRAMETYPE_VIDMAX << 24)) continue;
573 #endif
574     if ((buf[5] & 0xC0) != 0x80) continue;
575
576     UINT framelength = ((UINT)buf[3] << 8) | buf[4];
577
578     if ( buf[6] & 0x80 ) // PTS_DTS_flags indicate that PTS is present
579     {
580       if ( (buf[8]  & 0x01) != 0x01 ||
581            (buf[10] & 0x01) != 0x01 ||
582            (buf[12] & 0x01) != 0x01) continue;
583
584       *dest = ( (ULLONG)(buf[8]  & 0x0E) << 29 ) |
585               ( (ULLONG)(buf[9])         << 22 ) |
586               ( (ULLONG)(buf[10] & 0xFE) << 14 ) |
587               ( (ULLONG)(buf[11])        <<  7 ) |
588               ( (ULLONG)(buf[12] & 0xFE) >>  1 );
589       return 1;
590     }
591
592     buf += 5; len -= 5;
593     buf += framelength; len -= framelength;
594   }
595   // No PTS found.
596   return 0;
597 }