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