/*
 *   MediaMVP Server
 *
 *   (C) 2003 Dominic Morris
 *
 *   $Id: audio.c,v 1.1 2004/10/24 11:37:37 dom Exp $
 *   $Date: 2004/10/24 11:37:37 $
 *
 *
 *   Audio stripper
 */

#include "libmvp_internal.h"




void audio_strip(astrip_t *astrip, unsigned char *buf, int buflen)
{
    int     i = 0;

    if ( astrip->tmplen > 0 && buflen > 6 ) {
        unsigned char *lbuf = astrip->tmp;
        unsigned char *modify = buf - astrip->tmplen;

        memcpy(astrip->tmp + astrip->tmplen,buf,6);

        if ( lbuf[0] == 0x00 && lbuf[1] == 0x00 && lbuf[2] == 0x01 && lbuf[3] == astrip->pid ) {
            modify[3] = 0xbf;
        }
    }
    astrip->tmplen = 0;


    /* Lets try and strip out any additional audio tracks here */
    if ( buflen > astrip->offset + 6) {
        for ( i = astrip->offset; i < buflen - 6; i++ ) {
            if ( buf[i] == 0x00 && buf[i+1] == 0x00 && buf[i + 2] == 0x01 ) {
                uint8_t c = buf[i+3];
                int l = buf[i + 4] * 256 + buf[i + 5] + 6;           
                if ( c == astrip->pid  ) {
                    buf[i+3] = 0xBF;
                }
                
                if ( ( c >= 0xE0 && c <= 0xEF ) || ( c >= 0xC0 || c <= 0xCF ) ) {
                    if ( l ) 
                        i += l -1;
                }
            }
        }
        astrip->offset = 0;
    }
   
    if ( i > 0 &&  i <= buflen ) {
        --i;  /* We incremented at top of loop */
        memcpy(astrip->tmp + astrip->tmplen,&buf[i],(buflen - i) );
        astrip->tmplen += (buflen -  i) ;
    } else {
        astrip->offset = i - buflen;
    }
}
      
