Example #1
0
/*!
 * \brief Write out any pending encoded data.
 * \param s An OGG/Vorbis filestream.
 * \param f The file to write to.
 */
static void write_stream(struct vorbis_desc *s, FILE *f)
{
	while (vorbis_analysis_blockout(&s->vd, &s->vb) == 1) {
		vorbis_analysis(&s->vb, NULL);
		vorbis_bitrate_addblock(&s->vb);

		while (vorbis_bitrate_flushpacket(&s->vd, &s->op)) {
			ogg_stream_packetin(&s->os, &s->op);
			while (!s->eos) {
				if (ogg_stream_pageout(&s->os, &s->og) == 0) {
					break;
				}
				if (!fwrite(s->og.header, 1, s->og.header_len, f)) {
				ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
				}
				if (!fwrite(s->og.body, 1, s->og.body_len, f)) {
					ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
				}
				if (ogg_page_eos(&s->og)) {
					s->eos = 1;
				}
			}
		}
	}
}
Example #2
0
void
MediaRecorder::WriteAudio()
{
    int ret;
    nsresult rv;
    PRUint32 wr;

    while (vorbis_analysis_blockout(&aState->vd, &aState->vb) == 1) {
        vorbis_analysis(&aState->vb, NULL);
        vorbis_bitrate_addblock(&aState->vb);
        while (vorbis_bitrate_flushpacket(
                &aState->vd, &aState->op)) {
            ogg_stream_packetin(&aState->os, &aState->op);

            for (;;) {
                ret = ogg_stream_pageout(&aState->os, &aState->og);
                if (ret == 0)
                    break;

                rv = WriteData(aState->og.header, aState->og.header_len, &wr);
                rv = WriteData(aState->og.body, aState->og.body_len, &wr);

                if (ogg_page_eos(&aState->og))
                    break;
            }
        }
    }
}
Example #3
0
int fetch_and_process_audio(FILE *audio,ogg_page *audiopage,
                            ogg_stream_state *vo,
                            vorbis_dsp_state *vd,
                            vorbis_block *vb,
                            int audioflag){
  ogg_packet op;
  int i,j;

  while(audio && !audioflag){
    /* process any audio already buffered */
    spinnit();
    if(ogg_stream_pageout(vo,audiopage)>0) return 1;
    if(ogg_stream_eos(vo))return 0;

    {
      /* read and process more audio */
      signed char readbuffer[4096];
      int toread=4096/2/audio_ch;
      int bytesread=fread(readbuffer,1,toread*2*audio_ch,audio);
      int sampread=bytesread/2/audio_ch;
      float **vorbis_buffer;
      int count=0;

      if(bytesread<=0){
        /* end of file.  this can be done implicitly, but it's
           easier to see here in non-clever fashion.  Tell the
           library we're at end of stream so that it can handle the
           last frame and mark end of stream in the output properly */
        vorbis_analysis_wrote(vd,0);
      }else{
        vorbis_buffer=vorbis_analysis_buffer(vd,sampread);
        /* uninterleave samples */
        for(i=0;i<sampread;i++){
          for(j=0;j<audio_ch;j++){
            vorbis_buffer[j][i]=((readbuffer[count+1]<<8)|
                                 (0x00ff&(int)readbuffer[count]))/32768.f;
            count+=2;
          }
        }
        
        vorbis_analysis_wrote(vd,sampread);
        
      }

      while(vorbis_analysis_blockout(vd,vb)==1){
        
        /* analysis, assume we want to use bitrate management */
        vorbis_analysis(vb,NULL);
        vorbis_bitrate_addblock(vb);
        
        /* weld packets into the bitstream */
        while(vorbis_bitrate_flushpacket(vd,&op))
          ogg_stream_packetin(vo,&op);
        
      }
    }
  }

  return audioflag;
}
Example #4
0
    void encode_silent_samples(int n_samples)
        {
        float **buffer;
        int i;

        /* generate a silent buffer */
        buffer = vorbis_analysis_buffer(&vd, n_samples);
        for (i = 0; i < vi.channels; i++)
            memset(buffer[i], 0, n_samples * sizeof (float));
        vorbis_analysis_wrote(&vd, n_samples);

        /* encode it */
        while (vorbis_analysis_blockout(&vd, &vb) == 1)
            {
            vorbis_analysis(&vb, NULL);
            vorbis_bitrate_addblock(&vb);
            while (vorbis_bitrate_flushpacket(&vd, &op))
                {
                ogg_stream_packetin(&os, &op);
                while (ogg_stream_pageout(&os, &og))
                    {
                    write_out(&og);
                    if (ogg_page_eos(&og))
                        break;
                    }
                }
            }
        }
Example #5
0
static int
ogg_close (SF_PRIVATE *psf)
{
	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
	VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;

	if (odata == NULL || vdata == NULL)
		return 0 ;

	/*	Clean up this logical bitstream ; before exit we shuld see if we're
	**	followed by another [chained]. */

	if (psf->file.mode == SFM_WRITE)
	{
		if (psf->write_current <= 0)
			ogg_write_header (psf, 0) ;

		vorbis_analysis_wrote (&vdata->vd, 0) ;
		while (vorbis_analysis_blockout (&vdata->vd, &vdata->vb) == 1)
		{

		/* analysis, assume we want to use bitrate management */
			vorbis_analysis (&vdata->vb, NULL) ;
			vorbis_bitrate_addblock (&vdata->vb) ;

			while (vorbis_bitrate_flushpacket (&vdata->vd, &odata->op))
			{	/* weld the packet into the bitstream */
				ogg_stream_packetin (&odata->os, &odata->op) ;

				/* write out pages (if any) */
				while (!odata->eos)
				{	int result = ogg_stream_pageout (&odata->os, &odata->og) ;
					if (result == 0) break ;
					psf_fwrite (odata->og.header, 1, odata->og.header_len, psf) ;
					psf_fwrite (odata->og.body, 1, odata->og.body_len, psf) ;

		/* this could be set above, but for illustrative purposes, I do
		   it here (to show that vorbis does know where the stream ends) */

					if (ogg_page_eos (&odata->og)) odata->eos = 1 ;
				}
			}
		}
	}

	/* ogg_page and ogg_packet structs always point to storage in
	   libvorbis.  They are never freed or manipulated directly */

	vorbis_block_clear (&vdata->vb) ;
	vorbis_dsp_clear (&vdata->vd) ;
	vorbis_comment_clear (&vdata->vc) ;
	vorbis_info_clear (&vdata->vi) ;	 /* must be called last */
	/* should look here to reopen if chained */

	/* OK, clean up the framer */
	ogg_sync_clear (&odata->oy) ;
	ogg_stream_clear (&odata->os) ;

	return 0 ;
} /* ogg_close */
Example #6
0
static size_t
vorbis_encoder_read(struct encoder *_encoder, void *_dest, size_t length)
{
	struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder;
	ogg_page page;
	int ret;
	unsigned char *dest = _dest;
	size_t nbytes;

	ret = ogg_stream_pageout(&encoder->os, &page);
	if (ret == 0 && encoder->flush) {
		encoder->flush = false;
		ret = ogg_stream_flush(&encoder->os, &page);

	}

	if (ret == 0)
		return 0;

	assert(page.header_len > 0 || page.body_len > 0);

	nbytes = (size_t)page.header_len + (size_t)page.body_len;

	if (nbytes > length)
		/* XXX better error handling */
		MPD_ERROR("buffer too small");

	memcpy(dest, page.header, page.header_len);
	memcpy(dest + page.header_len, page.body, page.body_len);

	return nbytes;
}
bool VorbisWriter::write(QByteArray &left, QByteArray &right, long samples, bool flush) {
	const long maxChunkSize = 4096;

	const qint16 *leftData = (const qint16 *)left.constData();
	const qint16 *rightData = stereo ? (const qint16 *)right.constData() : NULL;

	long todoSamples = samples;
	int eos = 0;

	while (!eos) {
		long chunkSize = todoSamples > maxChunkSize ? maxChunkSize : todoSamples;
		todoSamples -= chunkSize;

		if (chunkSize == 0) {
			if (!flush)
				break;
			hasFlushed = true;
			vorbis_analysis_wrote(&pd->vd, 0);
		} else {
			float **buffer = vorbis_analysis_buffer(&pd->vd, chunkSize);

			for (long i = 0; i < chunkSize; i++)
				buffer[0][i] = (float)leftData[i] / 32768.0f;
			leftData += chunkSize;

			if (stereo) {
				for (long i = 0; i < chunkSize; i++)
					buffer[1][i] = (float)rightData[i] / 32768.0f;
				rightData += chunkSize;
			}

			vorbis_analysis_wrote(&pd->vd, chunkSize);
		}

		while (vorbis_analysis_blockout(&pd->vd, &pd->vb) == 1) {
			vorbis_analysis(&pd->vb, NULL);
			vorbis_bitrate_addblock(&pd->vb);

			while (vorbis_bitrate_flushpacket(&pd->vd, &pd->op)) {
				ogg_stream_packetin(&pd->os, &pd->op);

				while (!eos && ogg_stream_pageout(&pd->os, &pd->og) != 0) {
					file.write((const char *)pd->og.header, pd->og.header_len);
					file.write((const char *)pd->og.body, pd->og.body_len);

					if (ogg_page_eos(&pd->og))
						eos = 1;
				}
			}
		}
	}

	samplesWritten += samples;

	left.remove(0, samples * 2);
	if (stereo)
		right.remove(0, samples * 2);

	return true;
}
Example #8
0
/*------------------------------------------------------------------------------
 *  Send pending Vorbis blocks to the underlying stream
 *----------------------------------------------------------------------------*/
void
VorbisLibEncoder :: vorbisBlocksOut ( void )                throw ()
{
    while ( 1 == vorbis_analysis_blockout( &vorbisDspState, &vorbisBlock) ) {
        ogg_packet      oggPacket;
        ogg_page        oggPage;

        vorbis_analysis( &vorbisBlock, &oggPacket);
#ifdef VORBIS_LIB_RC3
        vorbis_bitrate_addblock( &vorbisBlock);

        while ( vorbis_bitrate_flushpacket( &vorbisDspState, &oggPacket) ) {
#endif

            ogg_stream_packetin( &oggStreamState, &oggPacket);

            while ( ogg_stream_pageout( &oggStreamState, &oggPage) ) {
                int    written;
                
                written  = sink->write( oggPage.header, oggPage.header_len);
                written += sink->write( oggPage.body, oggPage.body_len);

                if ( written < oggPage.header_len + oggPage.body_len ) {
                    // just let go data that could not be written
                    reportEvent( 2,
                           "couldn't write full vorbis data to underlying sink",
                           oggPage.header_len + oggPage.body_len - written);
                }
            }
#ifdef VORBIS_LIB_RC3
        }
#endif
    }
}
Example #9
0
static int bg_ogg_stream_flush_page(bg_ogg_stream_t * s, int force)
  {
  int result;
  ogg_page og;
  memset(&og, 0, sizeof(og));
  if(force || (s->flags & STREAM_FORCE_FLUSH))
    result = ogg_stream_flush(&s->os,&og);
  else
    result = ogg_stream_pageout(&s->os,&og);
  
  if(result)
    {
    //    fprintf(stderr, "Writing page %d %d %d\n", ogg_page_serialno(&og),
    //            og.header_len, og.body_len);

    if((s->enc->write_callback(s->enc->write_callback_data,
                               og.header,og.header_len) < og.header_len) ||
       (s->enc->write_callback(s->enc->write_callback_data,
                               og.body,og.body_len) < og.body_len))
      return -1;
    else
      return 1;
    }
  return 0;
  }
		void OggWriter::closeResource() {
			vorbis_analysis_wrote( this->dsp_.get(), 0 );

			while( vorbis_analysis_blockout( this->dsp_.get(), this->block_.get() ) == 1 ) {
				vorbis_analysis( this->block_.get(), NULL );
				vorbis_bitrate_addblock( this->block_.get() );

				ogg_packet op;
				while( vorbis_bitrate_flushpacket( this->dsp_.get(), &op ) ) {
					ogg_stream_packetin( this->muxer_.get(), &op );
				}

				for(;;) {
					ogg_page og;
					int ret = ogg_stream_pageout( this->muxer_.get(), &og );
					if( ret == 0 ) {
						break;
					}
					std::fwrite( og.header, 1, og.header_len, this->fout_.get() );
					std::fwrite( og.body, 1, og.body_len, this->fout_.get() );
				}
			}

			this->quality_ = -1.f;
			this->comments_.reset();
			this->block_.reset();
			this->dsp_.reset();
			this->muxer_.reset();
			this->encoder_.reset();
			this->fout_.reset();
		}
Example #11
0
void Ihu2Spx::process(char *cbits, int len)
{
	if (fout)
	{
		id++;
		
		total_samples += frame_size;
		
		op.packet = (unsigned char *)cbits;
		op.bytes = len;
		if (len)
			op.e_o_s = 0;
		else
			op.e_o_s = 1;
		op.b_o_s = 0;
		
		op.granulepos = (id+1)*frame_size;
		if (op.granulepos>total_samples)
			op.granulepos = total_samples;
		
		op.packetno = 2+id;
		ogg_stream_packetin(&os, &op);
		
		while (ogg_stream_pageout(&os,&og))
		{
			ret = oe_write_page(&og, fout);
			if(ret != og.header_len + og.body_len)
				throw Error(QString("failed writing header to output stream"));
			else
				bytes_written += ret;
		}
	}
}
Example #12
0
int  lame_encode_ogg_frame (
	lame_global_flags*  gfp,
	const sample_t*     inbuf_l, 
	const sample_t*     inbuf_r,
	unsigned char*      mp3buf, 
	size_t              mp3buf_size )
{
    lame_internal_flags *gfc = gfp->internal_flags;
    int  i;
    int  eos   = 0;
    int  bytes = 0;
  
    /* expose the buffer to submit data */
    double **buffer = vorbis_analysis_buffer(&vd2,gfp->framesize);
  
    /* change level of input by -90 dB (no de-interleaving!) */
    for ( i = 0; i < gfp->framesize; i++ )
        buffer [0] [i] = (1/32768.) * inbuf_l [i];
    if ( gfc->channels_out == 2 )
        for ( i = 0; i < gfp->framesize; i++ )
            buffer [1] [i] = (1/32768.) * inbuf_r [i];
  
  /* tell the library how much we actually submitted */
  vorbis_analysis_wrote(&vd2,i);

  /* vorbis does some data preanalysis, then divvies up blocks for
     more involved (potentially parallel) processing.  Get a single
     block for encoding now */
  while(vorbis_analysis_blockout(&vd2,&vb2)==1){
    int result;
    /* analysis */
    vorbis_analysis(&vb2,&op2);
    
    /* weld the packet into the bitstream */
    ogg_stream_packetin(&os2,&op2);
    
    /* write out pages (if any) */
    do {
      result=ogg_stream_pageout(&os2,&og2);
      if (result==0) break;
	
      /* check if mp3buffer is big enough for the output */
      bytes += og2.header_len + og2.body_len;
      /*
      DEBUGF("\n\n*********\ndecoded bytes=%i  %i \n",bytes,mp3buf_size);
      */
      if (bytes > mp3buf_size && mp3buf_size>0)
	return -6;
      
      memcpy(mp3buf,og2.header,og2.header_len);
      memcpy(mp3buf+og2.header_len,og2.body,og2.body_len);
      mp3buf += og2.header_len + og2.body_len;
      
      if(ogg_page_eos(&og2))eos=1;
    } while (1);
  }
  (gfp -> frameNum)++;
  return bytes;
}
Example #13
0
void ogg_ostream::write_packet(ogg_packet & packet) {
  CHECK(ogg_stream_packetin(&stream_state_, &packet) == 0);
    
  ogg_page page;
  while (ogg_stream_pageout(&stream_state_, &page)) {
    write_page(page);
  }
}
Example #14
0
/*
 * Theora beginning of stream
 */
nsresult
MediaRecorder::SetupTheoraBOS()
{
    int i;
    nsresult rv;
    PRUint32 wr;
    ogg_uint32_t keyframe;

    if (ogg_stream_init(&vState->os, rand())) {
        PR_LOG(log, PR_LOG_NOTICE, ("Failed ogg_stream_init\n"));
        return NS_ERROR_FAILURE;
    }

    th_info_init(&vState->ti);

    /* Must be multiples of 16 */
    vState->ti.frame_width = (params->width + 15) & ~0xF;
    vState->ti.frame_height = (params->height + 15) & ~0xF;
    vState->ti.pic_width = params->width;
    vState->ti.pic_height = params->height;
    vState->ti.pic_x = (vState->ti.frame_width - params->width) >> 1 & ~1;
    vState->ti.pic_y = (vState->ti.frame_height - params->height) >> 1 & ~1;
    vState->ti.fps_numerator = params->fps_n;
    vState->ti.fps_denominator = params->fps_d;

    /* Are these the right values? */
    keyframe = 64 - 1;
    for (i = 0; keyframe; i++)
        keyframe >>= 1;
    vState->ti.quality = (int)(params->qual * 100);
    vState->ti.colorspace = TH_CS_ITU_REC_470M;
    vState->ti.pixel_fmt = TH_PF_420;
    vState->ti.keyframe_granule_shift = i;

    vState->th = th_encode_alloc(&vState->ti);
    th_info_clear(&vState->ti);

    /* Header init */
    th_comment_init(&vState->tc);
    th_comment_add_tag(&vState->tc, (char *)"ENCODER", (char *)"rainbow");
    if (th_encode_flushheader(
        vState->th, &vState->tc, &vState->op) <= 0) {
        PR_LOG(log, PR_LOG_NOTICE, ("Internal Theora library error\n"));
        return NS_ERROR_FAILURE;
    }
    th_comment_clear(&vState->tc);

    ogg_stream_packetin(&vState->os, &vState->op);
    if (ogg_stream_pageout(&vState->os, &vState->og) != 1) {
        PR_LOG(log, PR_LOG_NOTICE, ("Internal Ogg library error\n"));
        return NS_ERROR_FAILURE;
    }

    rv = WriteData(vState->og.header, vState->og.header_len, &wr);
    rv = WriteData(vState->og.body, vState->og.body_len, &wr);

    return NS_OK;
}
Example #15
0
int encode_flush(encoder_state *s, ogg_page *og)
{
    int result = ogg_stream_pageout(&s->os, og);

    if(result<=0)
        return 0;
    else
        return 1;
}
Example #16
0
static PyObject * py_ogg_ogg_stream_pageout(PyObject *self, PyObject *args) {
  int c_out;
  int size1, size2;
  ogg_stream_state * os;
  ogg_page * og;
  PyArg_ParseTuple(args, "s#s#", &os, &size1, &og, &size2);
  c_out = ogg_stream_pageout(os, og);
  return Py_BuildValue("i", c_out);
};
Example #17
0
void
xtr_oggbase_c::write_pages() {
  ogg_page page;

  while (ogg_stream_pageout(&m_os, &page)) {
    m_out->write(page.header, page.header_len);
    m_out->write(page.body,   page.body_len);
  }
}
Example #18
0
static double encode_vorbis( FILE *f, vorbis_dsp_state *vd, ogg_stream_state *vo, vorbis_block *vb, 
			     unsigned int audio_rate, double audiopos, signed char *buf, int n_samples )
{
   float **vorbis_buffer;
   const int audio_ch = 2;
   int i,j;
   int count = 0;
   ogg_page og;
   int got_page = 0;

   vorbis_buffer = vorbis_analysis_buffer( vd, n_samples );
   
   for( i = 0; i < n_samples; i++ )
   {
      for( j = 0; j < audio_ch; j++ )
      {
	 vorbis_buffer[j][i] = ( ( buf[count+1] << 8 ) | ( buf[count] & 0xff ) ) / 32768.0f;
	 count += 2;
      }
   }
   
   vorbis_analysis_wrote( vd, n_samples );

   while( vorbis_analysis_blockout( vd, vb ) == 1 )
   {
      ogg_packet op;
      
      vorbis_analysis( vb, NULL );
      vorbis_bitrate_addblock( vb );
      
      while( vorbis_bitrate_flushpacket( vd, &op ) )
      {
	 ogg_stream_packetin( vo, &op );
      }
   }
   
   while( ogg_stream_pageout( vo, &og ) )
   {
      got_page = 1;
      audiopos = vorbis_granule_time( vd, ogg_page_granulepos( &og ) );
/*       printf( "VORBIS: %f\n", audiopos ); */
      fwrite( og.header, og.header_len, 1, f );
      fwrite( og.body, og.body_len, 1, f );
   }

   if( !got_page )
   {
      double t;
      
      t = ( ( 1.0 * n_samples ) / audio_rate );
      
      audiopos += t;
   }

   return audiopos;
}
tbool CVorbisEncoder::Finalize_Descendant()
{
	if (miOutputSamplesTotal > 0) {
		// Actually done any processing?
		
		// Tell the library we're at end of stream so that it can handle
		// the last frame and mark end of stream in the output properly
		vorbis_analysis_wrote(&vd,0);
		
		while(vorbis_analysis_blockout(&vd,&vb)==1){
			
			/* analysis, assume we want to use bitrate management */
			vorbis_analysis(&vb,NULL);
			vorbis_bitrate_addblock(&vb);
			
			while(vorbis_bitrate_flushpacket(&vd,&op)){
				
				/* weld the packet into the bitstream */
				ogg_stream_packetin(&os,&op);
				
				/* write out pages (if any) */
				tbool bEOS = false;
				while(!bEOS){
					int result=ogg_stream_pageout(&os,&og);
					if(result==0)break;
					//fwrite(og.header,1,og.header_len,stdout);
					//fwrite(og.body,1,og.body_len,stdout);
					WriteOutput((char*)og.header, og.header_len);
					WriteOutput((char*)og.body, og.body_len);
					
					/* this could be set above, but for illustrative purposes, I do
						it here (to show that vorbis does know where the stream ends) */
					
					if(ogg_page_eos(&og))bEOS=1;
				}
			}
		}

		/* clean up and exit.  vorbis_info_clear() must be called last */
		ogg_stream_clear(&os);
		vorbis_block_clear(&vb);
		vorbis_dsp_clear(&vd);
		vorbis_comment_clear(&vc);
		vorbis_info_clear(&vi);
		
		/* ogg_page and ogg_packet structs always point to storage in
			libvorbis.  They're never freed or manipulated directly */
	}

	tfloat fSecs = ((tfloat)miOutputSamplesTotal) / miOutputSampleFreq;
	tfloat fKbps = muiBytesTotalOutput * 8.0f / (fSecs * 1000);
	std::cout << "Done (wrote " << muiBytesTotalOutput << " bytes, " << fSecs << " secs, avg rate " << fKbps << " kbps)\n\n";
	
	return true;
}
Example #20
0
/* Returns:
 *   0     No output at this time
 *   >0    Page produced
 *
 * Caller should loop over this to ensure that we don't end up with
 * excessive buffering in libvorbis.
 */
int encode_dataout(encoder_state *s, ogg_page *og)
{
    ogg_packet op;
    int result;

    if(s->in_header)
    {
        result = ogg_stream_flush(&s->os, og);
        if(result==0) 
        {
            s->in_header = 0;
            return encode_dataout(s,og);
        }
        else
            return 1;
    }
    else
    {
        while(vorbis_analysis_blockout(&s->vd, &s->vb)==1)
        {
            vorbis_analysis(&s->vb, NULL);
            vorbis_bitrate_addblock(&s->vb);

            while(vorbis_bitrate_flushpacket(&s->vd, &op)) 
                ogg_stream_packetin(&s->os, &op);
        }

        /* FIXME: Make this threshold configurable.
         * We don't want to buffer too many samples in one page when doing
         * live encoding - that's fine for non-live encoding, but breaks
         * badly when doing things live. 
         * So, we flush the stream if we have too many samples buffered
         */
        if(s->samples_in_current_page > s->samplerate * 2)
        {
            /*LOG_DEBUG1("Forcing flush: Too many samples in current page (%d)",
                    s->samples_in_current_page); */
            result = ogg_stream_flush(&s->os, og);
        }
        else
            result = ogg_stream_pageout(&s->os, og);

        if(result==0)
            return 0;
        else /* Page found! */
        {
            s->samples_in_current_page -= ogg_page_granulepos(og) - 
                    s->prevgranulepos;
            s->prevgranulepos = ogg_page_granulepos(og);
            return 1;
        }
    }
}
Example #21
0
/* Returns TRUE if an ogg page was output, FALSE if there is nothing
 * left to do.
 */
gboolean xmms_ices_encoder_output (encoder_state *s, ogg_page *og)
{
	ogg_packet op;

	/* As long as we're still in the header, we still have the header
	 * packets to output. Loop over those before going to the actual
	 * vorbis data. */
	if (s->in_header) {
		if (ogg_stream_flush (&s->os, og))
			return TRUE;
		else
			s->in_header = FALSE;
	}

	/* If we're flushing the end of the stream, just output. */
	if (s->flushing) {
		if (ogg_stream_flush (&s->os, og))
			return TRUE;
		else
			return FALSE;
	}

	/* Flush the vorbis analysis stream into ogg packets, and add
	 * those to the ogg packet stream. */
	while (vorbis_analysis_blockout (&s->vd, &s->vb) == 1) {
		vorbis_analysis (&s->vb, NULL);
		vorbis_bitrate_addblock (&s->vb);

		while (vorbis_bitrate_flushpacket (&s->vd, &op))
			ogg_stream_packetin (&s->os, &op);
	}

	/* For live encoding, we want to stream pages regularly, rather
	 * than burst huge pages. Therefore, we periodically manually
	 * flush the stream. */
	if (s->samples_in_current_page > s->rate * 2) {
		if (!ogg_stream_flush (&s->os, og))
			return FALSE;
	} else {
		if (!ogg_stream_pageout (&s->os, og))
			return FALSE;
	}

	/* At this point, we have an ogg page in og. Keep bookkeeping
	 * accurate regarding the number of samples still in the page
	 * buffer, and return. */
	s->samples_in_current_page -= (ogg_page_granulepos (og)
	                               - s->previous_granulepos);
	s->previous_granulepos = ogg_page_granulepos (og);

	return TRUE;
}
Example #22
0
static void close_output(void)
{
  int eos = 0;
  ogg_page   og; /* one Ogg bitstream page.  Vorbis packets are inside */
  ogg_packet op; /* one raw packet of data for decode */

  if(dpm.fd < 0)
    return;

  /* end of file.  this can be done implicitly in the mainline,
     but it's easier to see here in non-clever fashion.
     Tell the library we're at end of stream so that it can handle
     the last frame and mark end of stream in the output properly */
  vorbis_analysis_wrote(&vd, 0);

  /* vorbis does some data preanalysis, then divvies up blocks for
     more involved (potentially parallel) processing.  Get a single
     block for encoding now */
  while(vorbis_analysis_blockout(&vd, &vb) == 1) {

    /* analysis */
    vorbis_analysis(&vb, &op);
      
    /* weld the packet into the bitstream */
    ogg_stream_packetin(&os, &op);

    /* write out pages (if any) */
    while(!eos){
      int result = ogg_stream_pageout(&os,&og);
      if(result == 0)
	break;
      write(dpm.fd, og.header, og.header_len);
      write(dpm.fd, og.body, og.body_len);

      /* this could be set above, but for illustrative purposes, I do
	 it here (to show that vorbis does know where the stream ends) */

      if(ogg_page_eos(&og))
	eos = 1;
    }
  }

  /* clean up and exit.  vorbis_info_clear() must be called last */

  ogg_stream_clear(&os);
  vorbis_block_clear(&vb);
  vorbis_dsp_clear(&vd);
  close(dpm.fd);
  dpm.fd = -1;
}
Example #23
0
/*
 * Vorbis beginning of stream
 */
nsresult
MediaRecorder::SetupVorbisBOS()
{
    int ret;
    nsresult rv;
    PRUint32 wr;

    if (ogg_stream_init(&aState->os, rand())) {
        PR_LOG(log, PR_LOG_NOTICE, ("Failed ogg_stream_init\n"));
        return NS_ERROR_FAILURE;
    }

    vorbis_info_init(&aState->vi);
    ret = vorbis_encode_init_vbr(
        &aState->vi, params->chan, params->rate, (float)params->qual
    );
    if (ret) {
        PR_LOG(log, PR_LOG_NOTICE, ("Failed vorbis_encode_init\n"));
        return NS_ERROR_FAILURE;
    }

    vorbis_comment_init(&aState->vc);
    vorbis_comment_add_tag(&aState->vc, "ENCODER", "rainbow");
    vorbis_analysis_init(&aState->vd, &aState->vi);
    vorbis_block_init(&aState->vd, &aState->vb);

    {
        ogg_packet header;
        ogg_packet header_comm;
        ogg_packet header_code;

        vorbis_analysis_headerout(
            &aState->vd, &aState->vc,
            &header, &header_comm, &header_code
        );
        ogg_stream_packetin(&aState->os, &header);
        ogg_stream_packetin(&aState->os, &header_comm);
        ogg_stream_packetin(&aState->os, &header_code);

        if (ogg_stream_pageout(&aState->os, &aState->og) != 1) {
            PR_LOG(log, PR_LOG_NOTICE, ("Internal Ogg library error\n"));
            return NS_ERROR_FAILURE;
        }

        rv = WriteData(aState->og.header, aState->og.header_len, &wr);
        rv = WriteData(aState->og.body, aState->og.body_len, &wr);
    }

    return NS_OK;
}
Example #24
0
nsresult
OggWriter::GetContainerData(nsTArray<nsTArray<uint8_t> >* aOutputBufs,
                            uint32_t aFlags)
{
  int rc = -1;
  PROFILER_LABEL("OggWriter", "GetContainerData",
    js::ProfileEntry::Category::OTHER);
  // Generate the oggOpus Header
  if (aFlags & ContainerWriter::GET_HEADER) {
    OpusMetadata* meta = static_cast<OpusMetadata*>(mMetadata.get());
    NS_ASSERTION(meta, "should have meta data");
    NS_ASSERTION(meta->GetKind() == TrackMetadataBase::METADATA_OPUS,
                 "should have Opus meta data");

    nsresult rv = WriteEncodedData(meta->mIdHeader, 0);
    NS_ENSURE_SUCCESS(rv, rv);

    rc = ogg_stream_flush(&mOggStreamState, &mOggPage);
    NS_ENSURE_TRUE(rc > 0, NS_ERROR_FAILURE);
    ProduceOggPage(aOutputBufs);

    rv = WriteEncodedData(meta->mCommentHeader, 0);
    NS_ENSURE_SUCCESS(rv, rv);

    rc = ogg_stream_flush(&mOggStreamState, &mOggPage);
    NS_ENSURE_TRUE(rc > 0, NS_ERROR_FAILURE);

    ProduceOggPage(aOutputBufs);
    return NS_OK;

  // Force generate a page even if the amount of packet data is not enough.
  // Usually do so after a header packet.
  } else if (aFlags & ContainerWriter::FLUSH_NEEDED) {
    // rc = 0 means no packet to put into a page, or an internal error.
    rc = ogg_stream_flush(&mOggStreamState, &mOggPage);
  } else {
    // rc = 0 means insufficient data has accumulated to fill a page, or an
    // internal error has occurred.
    rc = ogg_stream_pageout(&mOggStreamState, &mOggPage);
  }

  if (rc) {
    ProduceOggPage(aOutputBufs);
  }
  if (aFlags & ContainerWriter::FLUSH_NEEDED) {
    mIsWritingComplete = true;
  }
  return (rc > 0) ? NS_OK : NS_ERROR_FAILURE;
}
/*
 * Class:     org_tritonus_lowlevel_ogg_StreamState
 * Method:    pageOut
 * Signature: (Lorg/tritonus/lowlevel/ogg/Page;)I
 */
JNIEXPORT jint JNICALL
Java_org_tritonus_lowlevel_ogg_StreamState_pageOut
(JNIEnv* env, jobject obj, jobject page)
{
	ogg_stream_state*	handle;
	ogg_page*		pageHandle;
	int			nReturn;

	if (debug_flag) { fprintf(debug_file, "Java_org_tritonus_lowlevel_ogg_StreamState_pageOut(): begin\n"); }
	handle = getHandle(env, obj);
	pageHandle = getPageNativeHandle(env, page);
	nReturn = ogg_stream_pageout(handle, pageHandle);
	if (debug_flag) { fprintf(debug_file, "Java_org_tritonus_lowlevel_ogg_StreamState_pageOut(): end\n"); }
	return nReturn;
}
Example #26
0
int lame_encode_ogg_finish(lame_global_flags *gfp,
			  char *mp3buf, int mp3buf_size)
{
  int eos=0,bytes=0;

  vorbis_analysis_wrote(&vd2,0);

  while(vorbis_analysis_blockout(&vd2,&vb2)==1){
    
    /* analysis */
    vorbis_analysis(&vb2,&op2);

      /* weld the packet into the bitstream */
      ogg_stream_packetin(&os2,&op2);

      /* write out pages (if any) */
      while(!eos){
	int result=ogg_stream_pageout(&os2,&og2);
	if(result==0)break;


	/* check if mp3buffer is big enough for the output */
	bytes += og2.header_len + og2.body_len;
	if (bytes > mp3buf_size && mp3buf_size>0)
	  return -5;
	
	memcpy(mp3buf,og2.header,og2.header_len);
	memcpy(mp3buf+og2.header_len,og2.body,og2.body_len);

	/* this could be set above, but for illustrative purposes, I do
	   it here (to show that vorbis does know where the stream ends) */
	if(ogg_page_eos(&og2))eos=1;

      }
    }


  /* clean up and exit.  vorbis_info_clear() must be called last */
  ogg_stream_clear(&os2);
  vorbis_block_clear(&vb2);
  vorbis_dsp_clear(&vd2);

  
  /* ogg_page and ogg_packet structs always point to storage in
     libvorbis.  They're never freed or manipulated directly */
  return bytes;

}
Example #27
0
void TargetFileOggVorbis::processAndWriteVorbisBlocks()
{
	while ( vorbis_analysis_blockout( &mVorbisDspState, &mVorbisBlock ) == 1 ) {
		vorbis_analysis( &mVorbisBlock, NULL );
		vorbis_bitrate_addblock( &mVorbisBlock );

		while ( vorbis_bitrate_flushpacket( &mVorbisDspState, &mOggPacket ) == 1 ) {
			ogg_stream_packetin( &mOggStream, &mOggPacket );

			while ( ogg_stream_pageout( &mOggStream, &mOggPage ) != 0 ) {
				mStream->writeData( mOggPage.header, mOggPage.header_len );
				mStream->writeData( mOggPage.body, mOggPage.body_len );
			}
		}
	}
}
bool ShoutVSTEncoderOGG::Process( float **inputs, long sampleFrames )
{
  if (!bInitialized) return false;

  float **buffer=vorbis_analysis_buffer(&vd,sampleFrames);

  /* uninterleave samples */
  for(int i=0;i<sampleFrames;i++){
    buffer[0][i] = inputs[0][i];
    buffer[1][i] = inputs[1][i];
  }

  /* tell the library how much we actually submitted */
  vorbis_analysis_wrote(&vd,sampleFrames);

  /* vorbis does some data preanalysis, then divvies up blocks for
  more involved (potentially parallel) processing.  Get a single
  block for encoding now */
  int eos = 0;

  while(vorbis_analysis_blockout(&vd,&vb)==1){

    /* analysis, assume we want to use bitrate management */
    vorbis_analysis(&vb,NULL);
    vorbis_bitrate_addblock(&vb);

    while(vorbis_bitrate_flushpacket(&vd,&op)){

      /* weld the packet into the bitstream */
      ogg_stream_packetin(&os,&op);

      /* write out pages (if any) */
      while(!eos){
        int result=ogg_stream_pageout(&os,&og);
        if(result==0)break;
        if (!SendOGGPageToICE(&og)) return false;

        /* this could be set above, but for illustrative purposes, I do
        it here (to show that vorbis does know where the stream ends) */

        if(ogg_page_eos(&og))eos=1;
      }
    }
  } 

  return true;
}
Example #29
0
int fetch_and_process_video(av_input *_avin,ogg_page *_page,
 ogg_stream_state *_vo,daala_enc_ctx *_dd,int _video_ready){
  ogg_packet op;
  while(!_video_ready){
    size_t ret;
    char   frame[6];
    char   c;
    int    last;
    if(ogg_stream_pageout(_vo,_page)>0)return 1;
    else if(ogg_stream_eos(_vo))return 0;
    ret=fread(frame,1,6,_avin->video_infile);
    if(ret==6){
      od_img *img;
      int     pli;
      if(memcmp(frame,"FRAME",5)!=0){
        fprintf(stderr,"Loss of framing in YUV input data.\n");
        exit(1);
      }
      if(frame[5]!='\n'){
        int bi;
        for(bi=0;bi<121;bi++){
          if(fread(&c,1,1,_avin->video_infile)==1&&c=='\n')break;
        }
        if(bi>=121){
          fprintf(stderr,"Error parsing YUV frame header.\n");
          exit(1);
        }
      }
      /*Read the frame data.*/
      img=&_avin->video_img;
      for(pli=0;pli<img->nplanes;pli++){
        od_img_plane *iplane;
        size_t        plane_sz;
        iplane=img->planes+pli;
        plane_sz=((_avin->video_pic_w+(1<<iplane->xdec)-1)>>iplane->xdec)*
         ((_avin->video_pic_h+(1<<iplane->ydec)-1)>>iplane->ydec);
        ret=fread(iplane->data/*+(_avin->video_pic_y>>iplane->ydec)*iplane->ystride+
         (_avin->video_pic_x>>iplane->xdec)*/,1,plane_sz,_avin->video_infile);
        if(ret!=plane_sz){
          fprintf(stderr,"Error reading YUV frame data.\n");
          exit(1);
        }
      }
      last=0;
    }
    else last=1;
Example #30
-1
void OpusCodec::encodeData(Connector *conn,const float *pcm,int frames)
{
#ifdef HAVE_OPUS
  int s;
  unsigned char data[4096];

  if(!opus_prologue_sent) {
    conn->writeData(0,(const unsigned char *)opus_stream_prologue.constData(),
		    opus_stream_prologue.size());
    opus_prologue_sent=true;
  }

  if((s=opus_encode_float(opus_encoder,pcm,frames,data,4096))>1) {
    opus_packet_granulepos+=frames;
    opus_ogg_packet.packet=data;
    opus_ogg_packet.bytes=s;
    opus_ogg_packet.b_o_s=0;
    opus_ogg_packet.e_o_s=0;
    opus_ogg_packet.granulepos=opus_packet_granulepos;
    opus_ogg_packet.packetno=opus_packet_number++;
    ogg_stream_packetin(&opus_ogg_stream,&opus_ogg_packet);
    while(ogg_stream_pageout(&opus_ogg_stream,&opus_ogg_page)!=0) {
      conn->
	writeData(frames,opus_ogg_page.header,opus_ogg_page.header_len);
      conn->writeData(0,opus_ogg_page.body,opus_ogg_page.body_len);
    }
  }
  else {
    Log(LOG_WARNING,QString().sprintf("opus encoding error %d",s));
  }

#endif  // HAVE_OPUS
}