/*
   File: vstream.cc

   By: Alex Theo de Jong
   Created: February 1996
   
   Description:
   Video Stream buffer for MPEG player
*/

#ifdef __GNUG__
#pragma implementation
#endif

#include <stdio.h>
#include <fstream.h>
#include <sys/time.h>

#include "athread.hh"

#include "error.hh"
#include "debug.hh"
#include "util.hh"

#include "sync.hh"
#include "mpeg2const.hh"
#include "mpeg2buff.hh"


#include "vstream.hh"

/*
 *
 * VideoStream
 *
 */

VideoStream::VideoStream(const char* filename, int bitrate) :
  bfr(0), value(0), bytes(0), bytes_available(0), chunksize(512), incnt(0), file(True) {
  inputstream=new Mpeg2Input(filename, 8196, bitrate);
  sync=0;
}

VideoStream::VideoStream(Mpeg2Buffer* input, Synchronization* s) :  
  bfr(0), value(0), bytes(0), bytes_available(0), chunksize(512*10), incnt(0), file(False) {
  inputstream=input;
  sync=s;
}

VideoStream::~VideoStream(){
  inputstream->close();
  if (file) delete inputstream;
}

unsigned int VideoStream::getNewByte(){
int i;
  if (sync)  i = sync->usedbytes(1, chunksize);
  if ((bytes=bytes_available=inputstream->waitforbytes(chunksize))<=0){
    TRACER("Video done - exit on waitforbytes");
    athr_exit(0);
  }
//  if (sync) sync->usedbytes(1, bytes);
//  if (sync) sync->usedbytes(1, chunksize);
  return inputstream->getbyte();
}



#ifdef DEBUG

// This stuff is declared inline if not DEBUG

void VideoStream::fill(){
  if (!incnt) bfr=0; for (; incnt<=24; incnt+=8) bfr|=(getbyte() << (24 - incnt)); 
}

unsigned int VideoStream::startcode(){
  if (incnt&7){ bfr<<=(incnt&7); incnt-=(incnt&7); }     // Byte align & fill bfr
  fill();
  for (; ((bfr >> 8)!=Packet_start_code_prefix); ){ bfr<<=8; bfr|=getbyte(); }  // search
  return bfr;
}
#endif
