/*
 *   MediaMVP Server Library
 *
 *   (C) 2003 Dominic Morris
 *
 *   $Id: misc.c,v 1.14 2004/10/16 17:16:56 dom Exp $
 *   $Date: 2004/10/16 17:16:56 $
 *
 *
 *   Miscellaenous routines
 */


#include "libmvp_internal.h"
#include <stdarg.h>


void dump_hex(int level, unsigned char *buf, int len)
{
    int       i;

    if ( initparams->debug_level <= level ) {
        for ( i = 0; i < len; i++ ) {
            fprintf(initparams->logfile,"%02x",buf[i]);
            if ( i % 2 ) {
                fprintf(initparams->logfile," ");
            }
        }
        fprintf(initparams->logfile,"\n");
        fflush(initparams->logfile);
    }
}


void Dprintf(int level, char *fmt, ...)
{
   va_list             ap;

   va_start(ap,fmt);

   if ( initparams->debug_level <= level ) {
       vfprintf(initparams->logfile,fmt,ap);
       fflush(initparams->logfile);
   }

   va_end(ap);
}

int file_get_type(char *filename)
{
    unsigned char buf[4];
    int           fd;
    int           type;

    if ( (fd = open(filename,O_RDONLY) ) == -1 ) {
        return -1;
    }
    
    type = file_get_type_fd(fd,buf);

    close(fd);

    return type;
}

int file_get_type_fd(int fd,unsigned char *buf)
{
    unsigned long   l;
    unsigned short  s;
    int red;

    
    /* If we can't read 4 bytes then it really is a nonsense file */
    if ( (red = read(fd,buf,4)) != 4 ) {
        return -1;
    }
        
    /* Go for mpeg first of all */
    l = buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3];
    s = buf[0] << 8 | buf[1];       
    
    if ( l == 0x000001b3 ||    /* MPEG video stream data */
         l == 0x000001ba ) {   /* MPEG system stream data */
        return MEDIA_MPEG;
    }
     
    if ( l == 0x000001ea ) {
        return MEDIA_MPEG;
    }

    if ( l == 0x000001e0 || l == 0x00001e4  ) { /* VDR files */
        return MEDIA_MPEG;
    }

    if ( s == 0xffd8  ) {
        return MEDIA_JPEG|MEDIA_PICTURE;
    }
        
    /* Now, try and work out music files */
    if ( (s & 0xfffe) == 0xfffa ||  /* MP3 */
         (s & 0xfffe) == 0xfffc ||  /* MP2 */
         (s & 0xfff8) == 0xfff0 ) {  /* MPEG2.0 */
        return MEDIA_MP3;      
    }

    if ( buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3' ) {
        return MEDIA_MP3;
    }
  
    if ( l == 0x47494638 ) {    /* Gif */
        return MEDIA_PICTURE;
    } else if ( l == 0x89504e47 ) { /* Png */
        return MEDIA_PICTURE;
    } else if ( s == 0x424d ) {  /* Bmp */
        return MEDIA_PICTURE;
    } else if ( l == 0x4d4d002a || l == 0x49492a00 ) { /* Tiff */
        return MEDIA_PICTURE;
    } 




    /* If we get here, it's probably a file list, but we don't really
       want to grok it here, so just return unknown filetype */
    return 0;     /* Unknown filetype */
}
    



/*
 * Local Variables:
 *  indent-tabs-mode:nil
 *  require-final-newline:t
 *  c-basic-offset: 4
 * End:
 */
