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