Exemplo n.º 1
0
Arquivo: unix.c Projeto: bremac/ntx
/* System-dependent functions for POSIX. */
void ntx_editor(char *file)
{
  if(isatty(STDIN_FILENO)) {
    /* Open an editor if we're in interactive mode. */
    char *editor = getenv("EDITOR");
    pid_t child;

    if(editor) {
      if((child = fork()) == 0) execlp(editor, editor, file, (char*)NULL);
      else waitpid(child, NULL, 0);
    } else die("The environment variable EDITOR is unset.\n");
  } else {
    FILE *f = raw_open(file, "w");
    char buffer[BUFFER_LEN];

    /* Copy data from stdin to the target file. */
    while(fgets(buffer, BUFFER_LEN, stdin)) fputs(buffer, f);
    release(f);
  }
}
Exemplo n.º 2
0
static
pcm_reader_t *open_input(aacenc_param_ex_t *params)
{
    pcm_io_context_t io = { 0 };
    pcm_reader_t *reader = 0;
    struct stat stb = { 0 };

    if ((params->input_fp = aacenc_fopen(params->input_filename, "rb")) == 0) {
        aacenc_fprintf(stderr, "ERROR: %s: %s\n", params->input_filename,
                       strerror(errno));
        goto END;
    }
    io.cookie = params->input_fp;
    if (fstat(fileno(params->input_fp), &stb) == 0
            && (stb.st_mode & S_IFMT) == S_IFREG)
        io.vtbl = &pcm_io_vtbl;
    else
        io.vtbl = &pcm_io_vtbl_noseek;

    if (params->is_raw) {
        int bytes_per_channel;
        pcm_sample_description_t desc = { 0 };
        if (parse_raw_spec(params->raw_format, &desc) < 0) {
            fprintf(stderr, "ERROR: invalid raw-format spec\n");
            goto END;
        }
        desc.sample_rate = params->raw_rate;
        desc.channels_per_frame = params->raw_channels;
        bytes_per_channel = (desc.bits_per_channel + 7) / 8;
        desc.bytes_per_frame = params->raw_channels * bytes_per_channel;
        if ((reader = raw_open(&io, &desc)) == 0) {
            fprintf(stderr, "ERROR: failed to open raw input\n");
            goto END;
        }
    } else {
        int c;
        ungetc(c = getc(params->input_fp), params->input_fp);

        switch (c) {
        case 'R':
            if ((reader = wav_open(&io, params->ignore_length)) == 0) {
                fprintf(stderr, "ERROR: broken / unsupported input file\n");
                goto END;
            }
            break;
        case 'c':
            params->source_tag_ctx.add = aacenc_add_tag_entry_to_store;
            params->source_tag_ctx.add_ctx = &params->source_tags;
            if ((reader = caf_open(&io,
                                   aacenc_translate_generic_text_tag,
                                   &params->source_tag_ctx)) == 0) {
                fprintf(stderr, "ERROR: broken / unsupported input file\n");
                goto END;
            }
            break;
        default:
            fprintf(stderr, "ERROR: unsupported input file\n");
            goto END;
        }
    }
    if ((reader = pcm_open_sint16_converter(reader)) != 0)
        reader = extrapolater_open(reader);
    return reader;
END:
    return 0;
}
Exemplo n.º 3
0
/**
 * \ingroup imglib
 * Opens one or more disk image files so that they can be read.  If a file format
 * type is specified, this function will call the specific routine to open the file.
 * Otherwise, it will detect the type (it will default to raw if no specific type can
 * be detected).   This function must be called before a disk image can be read from. 
 * Note that the data type used to store the image paths is a TSK_TCHAR, which changes
 * depending on a Unix or Windows build.  If you will always have UTF8, then consider
 * using tsk_img_open_utf8(). 
 *
 * @param num_img The number of images to open (will be > 1 for split images).
 * @param images The path to the image files (the number of files must
 * be equal to num_img and they must be in a sorted order)
 * @param type The disk image type (can be autodetection)
 * @param a_ssize Size of device sector in bytes (or 0 for default)
 *
 * @return Pointer to TSK_IMG_INFO or NULL on error
 */
TSK_IMG_INFO *
tsk_img_open(int num_img,
    const TSK_TCHAR * const images[], TSK_IMG_TYPE_ENUM type,
    unsigned int a_ssize)
{
    TSK_IMG_INFO *img_info = NULL;

    // Get rid of any old error messages laying around
    tsk_error_reset();

    if ((num_img == 0) || (images[0] == NULL)) {
        tsk_error_reset();
        tsk_errno = TSK_ERR_IMG_NOFILE;
        snprintf(tsk_errstr, TSK_ERRSTR_L, "tsk_img_open");
        return NULL;
    }
    
    if ((a_ssize > 0) && (a_ssize < 512)) {
        tsk_error_reset(); 
        tsk_errno = TSK_ERR_IMG_ARG;
        snprintf(tsk_errstr, TSK_ERRSTR_L, "sector size is less than 512 bytes (%d)", a_ssize);
        return NULL;
    }
    
    if ((a_ssize % 512) != 0) {
        tsk_error_reset(); 
        tsk_errno = TSK_ERR_IMG_ARG;
        snprintf(tsk_errstr, TSK_ERRSTR_L, "sector size is not a multiple of 512 (%d)", a_ssize);
        return NULL;
    }
    

    if (tsk_verbose)
        TFPRINTF(stderr,
            _TSK_T("tsk_img_open: Type: %d   NumImg: %d  Img1: %s\n"),
            type, num_img, images[0]);

    /* If no type is given, then we use the autodetection methods 
     * In case the image file matches the signatures of multiple formats,
     * we try all of the embedded formats 
     */
    if (type == TSK_IMG_TYPE_DETECT) {
        TSK_IMG_INFO *img_set = NULL;
#if HAVE_LIBAFFLIB || HAVE_LIBEWF
        char *set = NULL;
#endif
        struct STAT_STR stat_buf;

        // we rely on tsk_errno, so make sure it is 0
        tsk_error_reset();

        /* Try the non-raw formats first */
#if HAVE_LIBAFFLIB
        if ((img_info = aff_open(images, a_ssize)) != NULL) {
            /* we don't allow the "ANY" when autodetect is used because
             * we only want to detect the tested formats. */
            if (img_info->itype == TSK_IMG_TYPE_AFF_ANY) {
                img_info->close(img_info);
            }
            else {
                set = "AFF";
                img_set = img_info;
            }
        }
        else {
            // If AFF is otherwise happy except for a password, stop trying to guess
            if (tsk_errno == TSK_ERR_IMG_PASSWD) {
                return NULL;
            }
            tsk_error_reset();
        }
#endif

#if HAVE_LIBEWF
        if ((img_info = ewf_open(num_img, images, a_ssize)) != NULL) {
            if (set == NULL) {
                set = "EWF";
                img_set = img_info;
            }
            else {
                img_set->close(img_set);
                img_info->close(img_info);
                tsk_error_reset();
                tsk_errno = TSK_ERR_IMG_UNKTYPE;
                snprintf(tsk_errstr, TSK_ERRSTR_L, "EWF or %s", set);
                return NULL;
            }
        }
        else {
            tsk_error_reset();
        }
#endif
        // if any of the non-raw formats were detected, then use it. 
        if (img_set != NULL)
            return img_set;

        /* We'll use the raw format */
        if (num_img == 1) {
            if ((img_info = raw_open(images[0], a_ssize)) != NULL) {
                return img_info;
            }
            else if (tsk_errno) {
                return NULL;
            }
        }
        else {
            if ((img_info = split_open(num_img, images, a_ssize)) != NULL) {
                return img_info;
            }
            else if (tsk_errno) {
                return NULL;
            }
        }

        /* To improve the error message, verify the file can be read. */
        if (TSTAT(images[0], &stat_buf) < 0) {
            // special case to handle windows objects
#if defined(TSK_WIN32) || defined(__CYGWIN__)
            if (TSTRNCMP(_TSK_T("\\\\.\\"), images[0], 4) == 0) {
                if (tsk_verbose)
                    TFPRINTF(stderr,
                        _TSK_T
                        ("tsk_img_open: Ignoring stat error because of windows object: %s\n"),
                        images[0]);
            }
            else {
#endif
                tsk_error_reset();
                tsk_errno = TSK_ERR_IMG_STAT;
                snprintf(tsk_errstr, TSK_ERRSTR_L, "%" PRIttocTSK " : %s",
                    images[0], strerror(errno));
                return NULL;
#if defined(TSK_WIN32) || defined(__CYGWIN__)
            }
#endif
        }

        tsk_errno = TSK_ERR_IMG_UNKTYPE;
        tsk_errstr[0] = '\0';
        tsk_errstr2[0] = '\0';
        return NULL;
    }

    /*
     * Type values
     * Make a local copy that we can modify the string as we parse it
     */

    switch (type) {
    case TSK_IMG_TYPE_RAW_SING:

        /* If we have more than one image name, and raw was the only
         * type given, then use split */
        if (num_img > 1)
            img_info = split_open(num_img, images, a_ssize);
        else
            img_info = raw_open(images[0], a_ssize);
        break;

    case TSK_IMG_TYPE_RAW_SPLIT:

        /* If only one image file is given, and only one type was
         * given then use raw */
        if (num_img == 1)
            img_info = raw_open(images[0], a_ssize);
        else
            img_info = split_open(num_img, images, a_ssize);
        break;

#if HAVE_LIBAFFLIB
    case TSK_IMG_TYPE_AFF_AFF:
    case TSK_IMG_TYPE_AFF_AFD:
    case TSK_IMG_TYPE_AFF_AFM:
    case TSK_IMG_TYPE_AFF_ANY:
        img_info = aff_open(images, a_ssize);
        break;
#endif

#if HAVE_LIBEWF
    case TSK_IMG_TYPE_EWF_EWF:
        img_info = ewf_open(num_img, images, a_ssize);
        break;
#endif
    case TSK_IMG_TYPE_QEMU:
        img_info = qemu_open(images[0], a_ssize);
        break;

    default:
        tsk_error_reset();
        tsk_errno = TSK_ERR_IMG_UNSUPTYPE;
        snprintf(tsk_errstr, TSK_ERRSTR_L, "%d", type);
        return NULL;
    }

    return img_info;
}
Exemplo n.º 4
0
int main(int argc,char *argv[]) {

  unsigned char help=0;
  unsigned char option=0;


  int arg=0;

  struct rawfp *rawfpA=NULL;
  struct rawfp *rawfpB=NULL;
  
  int sA,sB;
  int c,x;

  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);
 
  arg=OptionProcess(1,argc,argv,&opt,NULL);  

  if (help==1) {
    OptionPrintInfo(stdout,hlpstr);
    exit(0);
  }

  if (option==1) {
    OptionDump(stdout,&opt);
    exit(0);
  }


  if (argc-arg<2) {
    OptionPrintInfo(stderr,errstr);
    exit(-1);
  }


  rawfpA=raw_open(argv[arg],NULL);
  rawfpB=raw_open(argv[arg+1],NULL);

  while (1) {
    sA=raw_read(rawfpA,&rawA);
    sB=raw_read(rawfpB,&rawB);
    if ((sA==-1) || (sB==-1)) break;
  
    fprintf(stdout,
    "%.4d-%.2d-%.2d %.2d:%.2d:%.2d\t%.4d-%.2d-%.2d %.2d:%.2d:%.2d\n",
	    rawA.PARMS.YEAR,rawA.PARMS.MONTH,rawA.PARMS.DAY,
            rawA.PARMS.HOUR,rawA.PARMS.MINUT,rawA.PARMS.SEC,
            rawB.PARMS.YEAR,rawB.PARMS.MONTH,rawB.PARMS.DAY,
            rawB.PARMS.HOUR,rawB.PARMS.MINUT,rawB.PARMS.SEC);
    
    if (rawA.PARMS.REV.MAJOR !=rawB.PARMS.REV.MAJOR) fprintf(stdout,"raw.PARMS.REV.MAJOR: %d !=%d \n",rawA.PARMS.REV.MAJOR,rawB.PARMS.REV.MAJOR);


    if (rawA.PARMS.REV.MINOR !=rawB.PARMS.REV.MINOR) fprintf(stdout,"raw.PARMS.REV.MINOR: %d !=%d \n",rawA.PARMS.REV.MINOR,rawB.PARMS.REV.MINOR);

    if (rawA.PARMS.NPARM !=rawB.PARMS.NPARM) fprintf(stdout,"raw.PARMS.NPARM: %d !=%d \n",rawA.PARMS.NPARM,rawB.PARMS.NPARM);

   if (rawA.PARMS.ST_ID !=rawB.PARMS.ST_ID) fprintf(stdout,"raw.PARMS.ST_ID: %d !=%d \n",rawA.PARMS.ST_ID,rawB.PARMS.ST_ID);

   if (rawA.PARMS.YEAR !=rawB.PARMS.YEAR) fprintf(stdout,"raw.PARMS.YEAR: %d !=%d \n",rawA.PARMS.YEAR,rawB.PARMS.YEAR);

   if (rawA.PARMS.MONTH !=rawB.PARMS.MONTH) fprintf(stdout,"raw.PARMS.MONTH: %d !=%d \n",rawA.PARMS.MONTH,rawB.PARMS.MONTH);

   if (rawA.PARMS.DAY !=rawB.PARMS.DAY) fprintf(stdout,"raw.PARMS.DAY: %d !=%d \n",rawA.PARMS.DAY,rawB.PARMS.DAY);

   if (rawA.PARMS.HOUR !=rawB.PARMS.HOUR) fprintf(stdout,"raw.PARMS.HOUR: %d !=%d \n",rawA.PARMS.HOUR,rawB.PARMS.HOUR);

   if (rawA.PARMS.MINUT !=rawB.PARMS.MINUT) fprintf(stdout,"raw.PARMS.MINUT: %d !=%d \n",rawA.PARMS.MINUT,rawB.PARMS.MINUT);

   if (rawA.PARMS.SEC !=rawB.PARMS.SEC) fprintf(stdout,"raw.PARMS.SEC: %d !=%d \n",rawA.PARMS.SEC,rawB.PARMS.SEC);

   if (rawA.PARMS.TXPOW !=rawB.PARMS.TXPOW) fprintf(stdout,"raw.PARMS.TXPOW: %d !=%d \n",rawA.PARMS.TXPOW,rawB.PARMS.TXPOW);

   if (rawA.PARMS.NAVE !=rawB.PARMS.NAVE) fprintf(stdout,"raw.PARMS.NAVE: %d !=%d \n",rawA.PARMS.NAVE,rawB.PARMS.NAVE);

   if (rawA.PARMS.ATTEN !=rawB.PARMS.ATTEN) fprintf(stdout,"raw.PARMS.ATTEN: %d !=%d \n",rawA.PARMS.ATTEN,rawB.PARMS.ATTEN);

   if (rawA.PARMS.LAGFR !=rawB.PARMS.LAGFR) fprintf(stdout,"raw.PARMS.LAGFR: %d !=%d \n",rawA.PARMS.LAGFR,rawB.PARMS.LAGFR); 

   if (rawA.PARMS.SMSEP !=rawB.PARMS.SMSEP) fprintf(stdout,"raw.PARMS.SMSEP: %d !=%d \n",rawA.PARMS.SMSEP,rawB.PARMS.SMSEP);


   if (rawA.PARMS.ERCOD !=rawB.PARMS.ERCOD) fprintf(stdout,"raw.PARMS.ERCOD: %d !=%d \n",rawA.PARMS.ERCOD,rawB.PARMS.ERCOD);

   if (rawA.PARMS.AGC_STAT !=rawB.PARMS.AGC_STAT) fprintf(stdout,"raw.PARMS.AGC_STAT: %d !=%d \n",rawA.PARMS.AGC_STAT,rawB.PARMS.AGC_STAT);

   if (rawA.PARMS.LOPWR_STAT !=rawB.PARMS.LOPWR_STAT) fprintf(stdout,"raw.PARMS.LOPWR_STAT: %d !=%d \n",rawA.PARMS.LOPWR_STAT,rawB.PARMS.LOPWR_STAT);

   if (rawA.PARMS.NBAUD !=rawB.PARMS.NBAUD) fprintf(stdout,"raw.PARMS.NBAUD: %d !=%d \n",rawA.PARMS.NBAUD,rawB.PARMS.NBAUD);

   if (rawA.PARMS.NOISE !=rawB.PARMS.NOISE) fprintf(stdout,"raw.PARMS.NOISE: %d !=%d \n",rawA.PARMS.NOISE,rawB.PARMS.NOISE);

   if (rawA.PARMS.NOISE_MEAN !=rawB.PARMS.NOISE_MEAN) fprintf(stdout,"raw.PARMS.NOISE_MEAN: %d !=%d \n",rawA.PARMS.NOISE_MEAN,rawB.PARMS.NOISE_MEAN);

   if (rawA.PARMS.CHANNEL !=rawB.PARMS.CHANNEL) fprintf(stdout,"raw.PARMS.CHANNEL: %d !=%d \n",rawA.PARMS.CHANNEL,rawB.PARMS.CHANNEL);


   if (rawA.PARMS.RXRISE !=rawB.PARMS.RXRISE) fprintf(stdout,"raw.PARMS.RXRISE: %d !=%d \n",rawA.PARMS.RXRISE,rawB.PARMS.RXRISE);


   if (rawA.PARMS.INTT !=rawB.PARMS.INTT) fprintf(stdout,"raw.PARMS.INTT: %d !=%d \n",rawA.PARMS.INTT,rawB.PARMS.INTT);


   if (rawA.PARMS.TXPL !=rawB.PARMS.TXPL) fprintf(stdout,"raw.PARMS.TXPL: %d !=%d \n",rawA.PARMS.TXPL,rawB.PARMS.TXPL);


   if (rawA.PARMS.MPINC !=rawB.PARMS.MPINC) fprintf(stdout,"raw.PARMS.MPINC: %d !=%d \n",rawA.PARMS.MPINC,rawB.PARMS.MPINC);




   if (rawA.PARMS.MPPUL !=rawB.PARMS.MPPUL) fprintf(stdout,"raw.PARMS.MPPUL: %d !=%d \n",rawA.PARMS.MPPUL,rawB.PARMS.MPPUL);


   if (rawA.PARMS.MPLGS !=rawB.PARMS.MPLGS) fprintf(stdout,"raw.PARMS.MPLGS: %d !=%d \n",rawA.PARMS.MPLGS,rawB.PARMS.MPLGS);


   if (rawA.PARMS.NRANG !=rawB.PARMS.NRANG) fprintf(stdout,"raw.PARMS.NRANG: %d !=%d \n",rawA.PARMS.NRANG,rawB.PARMS.NRANG);


   if (rawA.PARMS.FRANG !=rawB.PARMS.FRANG) fprintf(stdout,"raw.PARMS.FRANG: %d !=%d \n",rawA.PARMS.FRANG,rawB.PARMS.FRANG);


   if (rawA.PARMS.RSEP !=rawB.PARMS.RSEP) fprintf(stdout,"raw.PARMS.RSEP: %d !=%d \n",rawA.PARMS.RSEP,rawB.PARMS.RSEP);

   if (rawA.PARMS.BMNUM !=rawB.PARMS.BMNUM) fprintf(stdout,"raw.PARMS.BMNUM: %d !=%d \n",rawA.PARMS.BMNUM,rawB.PARMS.BMNUM);


   if (rawA.PARMS.XCF !=rawB.PARMS.XCF) fprintf(stdout,"raw.PARMS.XCF: %d !=%d \n",rawA.PARMS.XCF,rawB.PARMS.XCF);

 
   if (rawA.PARMS.TFREQ !=rawB.PARMS.TFREQ) fprintf(stdout,"raw.PARMS.TFREQ: %d !=%d \n",rawA.PARMS.TFREQ,rawB.PARMS.TFREQ);

   if (rawA.PARMS.SCAN !=rawB.PARMS.SCAN) fprintf(stdout,"raw.PARMS.SCAN: %d !=%d \n",rawA.PARMS.SCAN,rawB.PARMS.SCAN);

   if (rawA.PARMS.MXPWR !=rawB.PARMS.MXPWR) fprintf(stdout,"raw.PARMS.MXPWR: %d !=%d \n",rawA.PARMS.MXPWR,rawB.PARMS.MXPWR);


   if (rawA.PARMS.LVMAX !=rawB.PARMS.LVMAX) fprintf(stdout,"raw.PARMS.LVMAX: %d !=%d \n",rawA.PARMS.LVMAX,rawB.PARMS.LVMAX);


   if (rawA.PARMS.CP !=rawB.PARMS.CP) fprintf(stdout,"raw.PARMS.CP: %d !=%d \n",rawA.PARMS.CP,rawB.PARMS.CP);

   if (strcmp(rawA.COMBF,rawB.COMBF) !=0)  fprintf(stdout,"raw.combf: %s !=%s \n",rawA.COMBF,rawB.COMBF);

   for (c=0;c<rawA.PARMS.MPPUL;c++) if (rawA.PULSE_PATTERN[c] !=rawB.PULSE_PATTERN[c]) break;
   if (c !=rawA.PARMS.MPPUL) fprintf(stdout,"Pulse pattern does not match\n");

   for (c=0;c<rawA.PARMS.MPLGS;c++) {
     if (rawA.LAG_TABLE[0][c] !=rawB.LAG_TABLE[0][c]) break;
     if (rawA.LAG_TABLE[1][c] !=rawB.LAG_TABLE[1][c]) break;

   }
   if (c !=rawA.PARMS.MPLGS) fprintf(stdout,"Lag table does not match\n");

 
   for (c=0;c<rawA.PARMS.NRANG;c++) {
     if (rawA.pwr0[c] !=rawB.pwr0[c]) {
       fprintf(stdout,"pwr0[%d]: %g != %g\n",c,rawA.pwr0[c],rawB.pwr0[c]);
     }
   }

   if (c !=rawA.PARMS.NRANG) fprintf(stdout,"Lag-zero power does not match\n");

   for (c=0;c<rawA.PARMS.NRANG;c++) {
     for (x=0;x<rawA.PARMS.MPLGS;x++) {
     
       if (rawA.acfd[c][x][0] !=rawB.acfd[c][x][0]) {
         fprintf(stdout,"acfd[%d][%d][0]: %g != %g\n",c,x,rawA.acfd[c][x][0],
	         rawB.acfd[c][x][0]);
       }

       if (rawA.acfd[c][x][1] !=rawB.acfd[c][x][1]) {
         fprintf(stdout,"acfd[%d][%d][1]: %g != %g\n",c,x,rawA.acfd[c][x][1],
	       rawB.acfd[c][x][1]);
       }
     }
   }

   if (rawA.PARMS.XCF) {

     for (c=0;c<rawA.PARMS.NRANG;c++) {
       for (x=0;x<rawA.PARMS.MPLGS;x++) {
     
         if (rawA.acfd[c][x][0] !=rawB.acfd[c][x][0]) {
           fprintf(stdout,"acfd[%d][%d][0]: %g != %g\n",c,x,rawA.acfd[c][x][0],
	         rawB.acfd[c][x][0]);
         }

         if (rawA.acfd[c][x][1] !=rawB.acfd[c][x][1]) {
           fprintf(stdout,"acfd[%d][%d][1]: %g != %g\n",c,x,rawA.acfd[c][x][1],
	         rawB.acfd[c][x][1]);
         }
       }
     }

   }


   if (c !=rawA.PARMS.NRANG) fprintf(stdout,"Data does not match\n");

  }
  return 0;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
    int fd = 0;
    char *currentfile, old_dir[PATH_MAX];
    playlist *pl = NULL;
    struct id3_file *id3struct = NULL;
    struct id3_tag *id3tag = NULL;
    int retval;

    buffer playbuf;
    
    struct mad_decoder decoder;
    pthread_t keyb_thread;

    key_t sem_key;
    key_t mem_key;
    key_t frames_key;

    union semun sem_ops;
    int shm_id;
    int frames_id;
    mad_decoder_position = 0;
    output_buffer_position = 0;
    
    old_dir[0] = '\0';

    playbuf.pl = pl = new_playlist();

    if (!pl)
    {
        fprintf(stderr, "malloc failed at startup!\n");
        exit(1);
    }

    loop_remaining = 1;

    options.volume = MAD_F_ONE;

    status = MPG321_PLAYING;
    
    /* Get the command line options */
    parse_options(argc, argv, pl);

    if(options.opt & MPG321_PRINT_FFT)
	    if(!(options.opt & MPG321_REMOTE_PLAY))
	    {
		    /* printf("FFT analysis can only be used in Remote mode play.\n\n"); */
		    usage(argv[0]);			
		    exit(0);
	    }


    /* If there were no files and no playlist specified just print the usage */
    if (!playlist_file && optind == argc)
    {
        usage(argv[0]);
        exit(0);
    }

    if (playlist_file)
        load_playlist(pl, playlist_file);

    if(options.opt & MPG321_RECURSIVE_DIR)
	    add_cmdline_files_recursive_dir(pl, argv);
    else
	    add_cmdline_files(pl, argv);

    if (shuffle_play)
        shuffle_files(pl);

    if(options.opt & MPG321_ENABLE_BUFFER)
    {
	    /* Initialize semaphore and shared memeory */
	    if(access(argv[0],X_OK) == 0)
		    sem_key = ftok(argv[0],0);
	    else
		    sem_key = ftok(MPG321_PATH,0);
	    if(sem_key == -1)
	    {
		    perror("Cannot obtain resources for semaphores");
		    exit(EXIT_FAILURE);
	    }
	    semarray = semget(sem_key,3,IPC_CREAT | IPC_EXCL | S_IRWXU);
	    if(semarray == -1)
	    {
		    perror("Cannot initialize semaphores");
		    exit(EXIT_FAILURE);
	    }
	    sem_ops.val = buffer_size-1;
	    if(semctl(semarray,0,SETVAL,sem_ops) == -1)
	    {
		    perror("Error while initializing mad_decoder semaphore");
		    if(semctl(semarray,0,IPC_RMID) == -1)
			    perror("Error while destroying semaphores");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    sem_ops.val = 0;
	    if(semctl(semarray,1,SETVAL,sem_ops) == -1)
	    {
		    perror("Error while initializing mad_decoder semaphore");
		    if(semctl(semarray,0,IPC_RMID) == -1)
			    perror("Error while destroying semaphores");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    sem_ops.val = 0;
	    if(semctl(semarray,2,SETVAL,sem_ops) == -1)
	    {
		    perror("Error while initializing mad_decoder semaphore");
		    if(semctl(semarray,0,IPC_RMID) == -1)
			    perror("Error while destroying semaphores");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }

	    /* Shared Memory */
	    mem_key = ftok(argv[0],1);
	    shm_id = shmget(mem_key,buffer_size * sizeof(output_frame), IPC_CREAT | S_IREAD | S_IWRITE);
	    if(shm_id == -1)
	    {
		    perror("Cannot initialize shared buffer");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    Output_Queue = shmat(shm_id,NULL,0);
	    if(*(int *)Output_Queue == -1)
	    {
		    perror("Error while attaching shared buffer to mad_decoder");
		    if(shmctl(shm_id,IPC_RMID,NULL))
			    perror("Cannot destroy shared buffer");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    static int n;
	    for(n=0;n<buffer_size;n++)
	    {
		    memset((Output_Queue+n)->data,'\0',4608);
		    memset((Output_Queue+n)->time,'\0',80);
		    (Output_Queue+n)->length = 0;
		    (Output_Queue+n)->seconds = 0;
		    (Output_Queue+n)->num_frames = 0;
	    }
	    
	    frames_key = ftok(argv[0],2);
	    frames_id = shmget(frames_key,buffer_size * sizeof(decoded_frames), IPC_CREAT | S_IREAD | S_IWRITE);
	    if(frames_id == -1)
	    {
		    perror("Cannot initialize shared frames counter");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    Decoded_Frames = shmat(frames_id,NULL,0);
	    if(*(int *)Decoded_Frames == -1)
	    {
		    perror("Error while attaching shared frames counter to mad_decoder");
		    if(shmctl(frames_id,IPC_RMID,NULL))
			    perror("Cannot destroy shared frames counter");
		    goto out;
		    //exit(EXIT_FAILURE);
	    }
	    	
	    Decoded_Frames->is_http = 0;
	    Decoded_Frames->is_file = 0;

    }
    else {
	    ao_initialize();
	    check_default_play_device();
    }
    
    if (!(options.opt & MPG321_REMOTE_PLAY))
    {
        handle_signals(-1); /* initialize signal handler */
        remote_input_buf[0] = '\0';
    }
    
    if (!(options.opt & MPG321_QUIET_PLAY)) 
        mpg123_boilerplate();
    
    if (options.opt & MPG321_REMOTE_PLAY)
    {
        printf ("@R MPG123\n");
	if(options.opt & MPG321_ENABLE_BUFFER)
	{
#ifdef HAVE_ALSA
		init_alsa_volume_control("default"); /* For the moment use "default", it works on most of the systems. Tested in Debian,Fedora,Ubuntu,RedHat,CentOS,Gentoo */
		if(options.volume != MAD_F_ONE)
			mpg321_alsa_set_volume((long)options.volume*volume_max/100);
#endif
	}
    }

    /* Fork here. */
    if(options.opt & MPG321_ENABLE_BUFFER)
    {
	    output_pid = fork();
	    if(output_pid == -1)
	    {
		    perror("Error while forking output process");
		    goto out; /* Release shared memeory and semaphores */
		//    exit(EXIT_FAILURE);
	    }

	    if(output_pid == 0)
	    {
		    frame_buffer_p();
		    exit(EXIT_SUCCESS);
	    }
	    signal(SIGUSR1,handle_signals);
	    if(!(options.opt & MPG321_REMOTE_PLAY))
	    {
#ifdef HAVE_ALSA
		    init_alsa_volume_control("default");
		    if(options.volume != MAD_F_ONE)
			    mpg321_alsa_set_volume((long)options.volume*volume_max/100);
#endif
	    }
    }

    if( (options.volume != MAD_F_ONE) && !(options.opt & MPG321_ENABLE_BUFFER))
    {
	    options.volume = mad_f_tofixed((long)options.volume/100.0);
    }
    else{
	    options.volume = MAD_F_ONE; /* When using the buffer options.volume when decoding each frame should be equal to MAD_F_ONE */
//	    options.volume = mad_f_tofixed((long)100.0/100.0);
    }

    if (!(options.opt & MPG321_REMOTE_PLAY))
    {
	     if(options.opt & MPG321_ENABLE_BASIC)
	     {
	 	     /* Now create and detach the basic controls thread */
		     sem_init(&main_lock,0,0);
	 	     pthread_create(&keyb_thread,NULL,read_keyb,NULL);
		     pthread_detach(keyb_thread);
	     }
     }
    if(set_xterm)
    {
	    tty_control();
	    get_term_title(title);
    }else
    {
     	
	    if (!(options.opt & MPG321_REMOTE_PLAY))
	    {
	    	    if (tcgetattr(0, &terminal_settings) < 0)
	    		    perror("tcgetattr()");
	    	    memcpy(&old_terminal_settings, &terminal_settings, sizeof(struct termios));
		    /* Early thread start */
		    sem_post(&main_lock);
	    }
    }
    /* Play the mpeg files or zip it! */
    while((currentfile = get_next_file(pl, &playbuf)))
    {
        //printf("Current File: %s\n",currentfile);
	   if (quit_now) 
            break;
        
        signal(SIGINT, SIG_DFL);
        
        playbuf.buf = NULL;
        playbuf.fd = -1;
        playbuf.length = 0;
        playbuf.done = 0;
        playbuf.num_frames = 0;
        current_frame = 0;
        playbuf.max_frames = -1;
        strncpy(playbuf.filename,currentfile, PATH_MAX);
        playbuf.filename[PATH_MAX-1] = '\0';
        
        if (status == MPG321_PLAYING || status == MPG321_STOPPED) 
            file_change = 1;

        mad_timer_reset(&playbuf.duration);
        
        mad_timer_reset(&current_time);

	id3struct = NULL;

        if (!(options.opt & MPG321_QUIET_PLAY) && file_change)
        {
           /* id3struct = id3_file_open (currentfile, ID3_FILE_MODE_READONLY);*/

            if (id3struct == NULL)
		    get_id3_info(currentfile, &id3struct, &id3tag);
	    if(id3tag)
		    show_id3(id3tag);
	}

	scrobbler_time = -1;
	if(options.opt & MPG321_USE_SCROBBLER)
	{
		if(id3struct == NULL)
			get_id3_info(currentfile,&id3struct,&id3tag);
                
	    if (id3tag)
	    {
		    char emptystring[31], emptyyear[5] = "    ";
		    int i;

		    if(parse_id3(scrobbler_args, id3tag))
		    {
			    memset(emptystring, ' ', 30);
			    emptystring[30] = '\0';
	    		    if((options.opt & MPG321_VERBOSE_PLAY) && (options.opt & MPG321_USE_SCROBBLER))
			    {
				    fprintf(stderr, "\nPreparing for the AudioScrobbler:\n");
				    for(i = 0; i < 6; i++)
				    {
					    if(scrobbler_args[i] == NULL)
						    scrobbler_args[i] =
							    ( i == 3 ? emptyyear: emptystring);
					    fprintf(stderr, "- %s\n", scrobbler_args[i]);
				    }
			    }
		    }
	    }
	}
      

        if (options.opt & MPG321_REMOTE_PLAY && file_change)
        {
		if(id3struct == NULL)
			get_id3_info(currentfile, &id3struct, &id3tag);
		if(id3tag)
                {
                    if (!show_id3(id3tag))
                    {
                        /* This shouldn't be necessary, but it appears that
                           libid3tag doesn't necessarily know if there are no
                           id3 tags on a given mp3 */
                        char * basec = strdup(currentfile);
                        char * basen = basename(basec);
                        
                        char * dot = strrchr(basen, '.');
                        
                        if (dot)
                            *dot = '\0';
                        
                        printf("@I %s\n", basen);

                        free(basec);
                    }
                }
            else
            {
                char * basec = strdup(currentfile);
                char * basen = basename(basec);
                
                char * dot = strrchr(basen, '.');
                
                if (dot)
                    *dot = '\0';
                
                printf("@I %s\n", basen);

                free(basec);
            }
        }

	if(id3struct != NULL)
		id3_file_close(id3struct);

        /* Create the MPEG stream */
        /* Check if source is on the network */
        if((fd = raw_open(currentfile)) != 0 || (fd = http_open(currentfile)) != 0
            || (fd = ftp_open(currentfile)) != 0)
        {
            playbuf.fd = fd;
            playbuf.buf = malloc(BUF_SIZE);
            playbuf.length = BUF_SIZE;
	    if(options.opt & MPG321_ENABLE_BUFFER)
	    {
		    Decoded_Frames->is_http = 1;
		    Decoded_Frames->is_file = 0;
	    }
	    calc_http_length(&playbuf);

            mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
                            output, handle_error, /* message */ 0);
        }

        /* Check if we are to use stdin for input */
        else if(strcmp(currentfile, "-") == 0)
        {
            playbuf.fd = fileno(stdin);
            playbuf.buf = malloc(BUF_SIZE);
            playbuf.length = BUF_SIZE;

            mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
                            output, handle_error, /* message */ 0);
        }
            
        /* currentfile is a local file (presumably.) mmap() it */
        else
        {
            struct stat stat;
            
            if((fd = open(currentfile, O_RDONLY)) == -1)
            {
	    
                mpg321_error(currentfile);
		/* Restore TTY from keyboard reader thread */
	        if(options.opt & MPG321_ENABLE_BASIC)
			if (tcsetattr(0, TCSANOW, &old_terminal_settings) < 0)
				perror("tcsetattr ICANON");
		if(set_xterm)
	    	{
			set_tty_restore();
	    		osc_print(0,0,title);
	    		if (ctty)
	    			fclose(ctty);
	    	}
		if( options.opt & MPG321_REMOTE_PLAY)
			if(remote_restart)
			{	
				clear_remote_file(pl); /* If restart is enabled, restart remote shell when file doesn't exist*/
				continue;
			}
		if(options.opt & MPG321_ENABLE_BUFFER)
			goto out;
		else
			exit(1);
                /* mpg123 stops immediately if it can't open a file */
		/* If sth goes wrong break!!!*/
                break;
            }

	    if(options.opt & MPG321_ENABLE_BUFFER)
	    {
		    Decoded_Frames->is_http = 0;
		    Decoded_Frames->is_file = 1;
	    }
            
            if(fstat(fd, &stat) == -1)
            {
                mpg321_error(currentfile);
		close(fd);
                continue;
            }
            
            if (!S_ISREG(stat.st_mode))
            {
		    if(S_ISFIFO(stat.st_mode))
		    {
			    fallback = 1;
			    goto fall_back_to_read_from_fd;
		    }

		close(fd);    
                continue;
            }
            
            retval = calc_length(currentfile, &playbuf); //FIXME Check also if it is an mp3 file. If not break and go to the next file possible
	    if(retval < 0)
	    {
		    if(options.opt & MPG321_REMOTE_PLAY)
		    {
			    fprintf(stderr,"@E Corrupted file: %s\n",currentfile);
			    close(fd);
			    if(remote_restart)
			    {
				    clear_remote_file(pl); /* If restart is enabled, restart remote shell when file is corrupted */
				    continue;
			    }
			    break;
		    }
		    mpg321_error(currentfile);
		    close(fd);
//		    break; //FIXME Break and stop OR continue the playlist ????
		    continue;
	    }

	    if((options.opt & MPG321_VERBOSE_PLAY) && (options.opt & MPG321_USE_SCROBBLER))
		    fprintf(stderr, "Track duration: %ld seconds\n",playbuf.duration.seconds);

	    if(options.opt & MPG321_USE_SCROBBLER)
		    scrobbler_set_time(playbuf.duration.seconds);

            if ((options.maxframes != -1) && (options.maxframes <= playbuf.num_frames))
            { 
                playbuf.max_frames = options.maxframes;
            }
            
            playbuf.frames = malloc((playbuf.num_frames + 1) * sizeof(void*));
            playbuf.times = malloc((playbuf.num_frames + 1) * sizeof(mad_timer_t));
#ifdef __uClinux__
	    if((playbuf.buf = mmap(0, playbuf.length, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
#else       
 	    if((playbuf.buf = mmap(0, playbuf.length, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
#endif		    
            {
                mpg321_error(currentfile);
                continue;
            }
            
            playbuf.frames[0] = playbuf.buf;
		    
	    mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0,
            
	    		    output, handle_error, /* message */ 0);
fall_back_to_read_from_fd:	//FIXME. Reported that on some embedded systems with low memory, less than 16MB doesn't work properly.
	    if(fallback)
	    {
	    
		    playbuf.fd = fd;
		    playbuf.buf = malloc(BUF_SIZE);
		    playbuf.length = BUF_SIZE;
		    mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
				    output, handle_error, /* message */ 0);
		    fallback = 1;
	    }
        }

        if(!(options.opt & MPG321_QUIET_PLAY))/*zip it!!!*/
        {
            /* Because dirname might modify the argument */
            char * dirc = strdup(currentfile);
            char * basec = strdup(currentfile);

            char * basen = basename(basec);
            char * dirn = dirname(dirc);
            
            /* make sure that the file has a pathname; otherwise don't print out
               a Directory: listing */
            if(strchr(currentfile, '/') && strncmp(old_dir, dirn, PATH_MAX) != 0)
            {
                /* Print information about the file */
                fprintf(stderr, "\n");
                fprintf(stderr,"Directory: %s\n", dirn);
                
                strncpy(old_dir, dirn, PATH_MAX);
                old_dir[PATH_MAX-1] = '\0';
            }
            
            /* print a newline between different songs only, not after
               Directory: listing */
            else
            {
                fprintf(stderr, "\n");
            }

            fprintf(stderr,"Playing MPEG stream from %s ...\n", basen);
            
	    /* Printing xterm title */
	    if(set_xterm)
	    {
		    osc_print(0,0,basen);
	    }
	    
            free(dirc);
            free(basec);
        }    

        signal(SIGINT, handle_signals);
	signal(SIGCHLD, handle_sigchld);
        /*Give control back so that we can implement SIG's*/
	if(set_xterm)
	{
		set_tty_restore();
		if (tcgetattr(0, &terminal_settings) < 0)
			perror("tcgetattr()");
		memcpy(&old_terminal_settings, &terminal_settings, sizeof(struct termios));
		/* disable canonical mode processing in the line discipline driver */
		terminal_settings.c_lflag &= ~(ICANON | ECHO);
		/* apply our new settings */
		if (tcsetattr(0, TCSANOW, &terminal_settings) < 0)
			perror("tcsetattr ICANON");
		if(options.opt & MPG321_ENABLE_BASIC)
		{
			/* Late thread start */
			sem_post(&main_lock);
		}
	}
        /* Every time the user gets us to rewind, we exit decoding,
           reinitialize it, and re-start it */
	    
	if(options.opt & MPG321_ENABLE_BUFFER)
    	{
		Decoded_Frames->total_decoded_frames = 0;
		Decoded_Frames->done = 0;
	}
      
        while (1)
        {
            decoder.options |= MAD_OPTION_IGNORECRC;
            mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
	    if(options.opt & MPG321_ENABLE_BUFFER)
	    {
		    static struct sembuf start_sops = {2,-1,0};
		    semop(semarray,&start_sops,1);
		    mad_decoder_position = 0;
		    output_buffer_position = 0;
		    union semun sem_ops;
		    sem_ops.val = 0;
		    semctl(semarray,2,SETVAL,sem_ops);
		    Decoded_Frames->total_decoded_frames = 0;
		    Decoded_Frames->done = 0;
		    Decoded_Frames->is_http = 0;
		    Decoded_Frames->is_file = 0;
	    }
            /* if we're rewinding on an mmap()ed stream */
            if(status == MPG321_REWINDING && playbuf.fd == -1) 
            {
                mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0,
                    output, /*error*/0, /* message */ 0);
            }    
            else
                break;
        } 

        if (!(options.opt & MPG321_QUIET_PLAY))
        {
            char time_formatted[11];
            mad_timer_string(current_time, time_formatted, "%.1u:%.2u", MAD_UNITS_MINUTES,
                       MAD_UNITS_SECONDS, 0);
	    fprintf(stderr,"                                                                            \r");
	    fprintf(stderr, "\n[%s] Decoding of %s finished.\n",time_formatted, basename(currentfile)); /* Report total decoded seconds. Maybe for the frame buffer report only total played time?? */
        }
        
        if (options.opt & MPG321_REMOTE_PLAY && status == MPG321_STOPPED)
        {
            clear_remote_file(pl);
        }

        mad_decoder_finish(&decoder);

        if (playbuf.frames)
             free(playbuf.frames);

        if (playbuf.times)
            free(playbuf.times);
            
        if (playbuf.fd == -1)
        {
            munmap(playbuf.buf, playbuf.length);
            close(fd);
        }

        else
        {
            free(playbuf.buf);
            if (playbuf.fd != fileno(stdin)) 
                close(playbuf.fd);
        }
    }

    if(!(options.opt & MPG321_ENABLE_BUFFER))
    {
  	     if(playdevice)
		     ao_close(playdevice);
	     ao_shutdown();
     }

     if (!(options.opt & MPG321_REMOTE_PLAY))
     {
	     if(options.opt & MPG321_ENABLE_BASIC)
	     {
	 	     pflag = 1;
		     /* Restore TTY from keyboard reader thread */
	 	     if (tcsetattr(0, TCSANOW, &old_terminal_settings) < 0)
		 	     perror("tcsetattr ICANON");
	     }
     }
    /*Restoring TTY*/
    if(set_xterm)
    {
	    set_tty_restore();
	    osc_print(0,0,title);
	    if (ctty)
		    fclose(ctty);
    }

out:
    if(options.opt & MPG321_ENABLE_BUFFER)
    {
	    if(kill(output_pid,SIGUSR1) == -1)
		    perror("Error while stopping output process");
	    static int wstatus;
	    wait(&wstatus);
	    if(wstatus == -1)
		    perror("Error while waiting for output process to exit");
	    if(semctl(semarray,0,IPC_RMID) == -1)
		    perror("Error while destroying semaphores");
	    if(shmdt(Output_Queue) == -1)
		    perror("Error while detaching shared buffer");
	    if(shmctl(shm_id,IPC_RMID,NULL))
		    perror("Cannot destroy shared buffer");
	    if(shmctl(frames_id,IPC_RMID,NULL))
		    perror("Cannot destroy shared buffer");
    }
    return(0);
}
Exemplo n.º 6
0
/**
 * Open one or more files as a disk image.  This serves as a
 * wrapper around the specific types of disk image formats. You 
 * can specify the type or autodetection can be used.
 *
 * @param type The text a user supplied for the type of format.
 * Examples include "raw", "split", "aff", etc.
 * @param num_img The number of images that are being considered.
 * @param images The path to the files (the number of files must
 * be equal to num_img)
 *
 * @return Pointer to the Image state structure or NULL on error
 */
TSK_IMG_INFO *
tsk_img_open(const TSK_TCHAR * type, const int num_img,
    const TSK_TCHAR ** images)
{
    TSK_IMG_INFO *img_info = NULL;
    TSK_TCHAR *tp, *next;
    TSK_TCHAR type_lcl[128], *type_lcl_p;
    const TSK_TCHAR **img_tmp;
    int num_img_tmp = num_img;

    // Get rid of any old error messages laying around
    tsk_error_reset();

    if ((num_img == 0) || (images[0] == NULL)) {
        tsk_error_reset();
        tsk_errno = TSK_ERR_IMG_NOFILE;
        snprintf(tsk_errstr, TSK_ERRSTR_L, "tsk_img_open");
        tsk_errstr2[0] = '\0';
        return NULL;
    }

    if (tsk_verbose)
        TFPRINTF(stderr,
            _TSK_T("tsk_img_open: Type: %s   NumImg: %d  Img1: %s\n"),
            (type ? type : _TSK_T("n/a")), num_img, images[0]);

    // only the first in list (lowest) layer gets the files
    img_tmp = images;

    /* If no type is given, then we use the autodetection methods 
     * In case the image file matches the signatures of multiple formats,
     * we try all of the embedded formats 
     */

    if (type == NULL) {
        TSK_IMG_INFO *img_set = NULL;
#if HAVE_LIBAFFLIB || HAVE_LIBEWF
        char *set = NULL;
#endif
        struct STAT_STR stat_buf;

        /* First verify that the image file exists */
        if (TSTAT(images[0], &stat_buf) < 0) {

            // special case to handle windows objects
#if defined(TSK_WIN32)
            if ((images[0][0] == _TSK_T('\\'))
                && (images[0][1] == _TSK_T('\\'))
                && (images[0][2] == _TSK_T('.'))
                && (images[0][3] == _TSK_T('\\'))) {
                if (tsk_verbose)
                    TFPRINTF(stderr,
                        _TSK_T
                        ("tsk_img_open: Ignoring stat error because of windows object: %s\n"),
                        images[0]);
            }
#endif

            /* AFFLIB supports s3 storage on Amazon, so skip those 'file' paths */
#if HAVE_LIBAFFLIB
#if defined(TSK_WIN32)
            else
#endif
                if (((images[0][0] == _TSK_T('s'))
                    && (images[0][1] == _TSK_T('3'))
                    && (images[0][2] == _TSK_T(':'))
                    && (images[0][3] == _TSK_T('/'))
                    && (images[0][4] == _TSK_T('/'))) ||
                ((images[0][0] == _TSK_T('h'))
                    && (images[0][1] == _TSK_T('t'))
                    && (images[0][2] == _TSK_T('t'))
                    && (images[0][3] == _TSK_T('p'))
                    && (images[0][4] == _TSK_T(':'))
                    && (images[0][5] == _TSK_T('/'))
                    && (images[0][6] == _TSK_T('/')))) {
                if (tsk_verbose)
                    TFPRINTF(stderr,
                        _TSK_T
                        ("tsk_img_open: Ignoring stat error because of s3/http object: %s\n"),
                        images[0]);

            }
#endif

#if HAVE_LIBAFFLIB || defined(TSK_WIN32)
            else {
#endif
                tsk_error_reset();
                tsk_errno = TSK_ERR_IMG_STAT;
                snprintf(tsk_errstr, TSK_ERRSTR_L, "%" PRIttocTSK " : %s",
                    images[0], strerror(errno));
                return NULL;
#if HAVE_LIBAFFLIB || defined(TSK_WIN32)
            }
#endif
        }

        // we rely on tsk_errno, so make sure it is 0
        tsk_error_reset();

        /* Try the non-raw formats first */
#if HAVE_LIBAFFLIB
        if ((img_info = aff_open(images, NULL)) != NULL) {
            set = "AFF";
            img_set = img_info;
        }
        else {
            tsk_error_reset();
        }
#endif

#if HAVE_LIBEWF
        if ((img_info = ewf_open(num_img, images, NULL)) != NULL) {
            if (set == NULL) {
                set = "EWF";
                img_set = img_info;
            }
            else {
                img_set->close(img_set);
                img_info->close(img_info);
                tsk_error_reset();
                tsk_errno = TSK_ERR_IMG_UNKTYPE;
                snprintf(tsk_errstr, TSK_ERRSTR_L, "EWF or %s", set);
                return NULL;
            }
        }
        else {
            tsk_error_reset();
        }
#endif
        if (img_set != NULL)
            return img_set;

        /* We'll use the raw format */
        if (num_img == 1) {
            if ((img_info = raw_open(images, NULL)) != NULL) {
                return img_info;
            }
            else if (tsk_errno) {
                return NULL;
            }
        }
        else {
            if ((img_info = split_open(num_img, images, NULL)) != NULL) {
                return img_info;
            }
            else if (tsk_errno) {
                return NULL;
            }
        }
        tsk_errno = TSK_ERR_IMG_UNKTYPE;
        tsk_errstr[0] = '\0';
        tsk_errstr2[0] = '\0';
        return NULL;
    }

    /*
     * Type values
     * Make a local copy that we can modify the string as we parse it
     */
    TSTRNCPY(type_lcl, type, 128);
    type_lcl_p = type_lcl;

    /* We parse this and go up in the layers */
    tp = TSTRTOK(type_lcl, _TSK_T(","));
    while (tp != NULL) {
        uint8_t imgtype;

        next = TSTRTOK(NULL, _TSK_T(","));

        imgtype = tsk_img_parse_type(type);
        switch (imgtype) {
        case TSK_IMG_INFO_TYPE_RAW_SING:

            /* If we have more than one image name, and raw was the only
             * type given, then use split */
            if ((num_img > 1) && (next == NULL) && (img_tmp != NULL)) {
                img_info = split_open(num_img_tmp, img_tmp, img_info);
                num_img_tmp = 0;
            }
            else {
                img_info = raw_open(img_tmp, img_info);
            }
            img_tmp = NULL;
            break;

        case TSK_IMG_INFO_TYPE_RAW_SPLIT:

            /* If only one image file is given, and only one type was
             * given then use raw */
            if ((num_img == 1) && (next == NULL) && (img_tmp != NULL)) {
                img_info = raw_open(img_tmp, img_info);
            }
            else {
                img_info = split_open(num_img_tmp, img_tmp, img_info);
                num_img_tmp = 0;
            }

            img_tmp = NULL;
            break;

#if HAVE_LIBAFFLIB
        case TSK_IMG_INFO_TYPE_AFF_AFF:
        case TSK_IMG_INFO_TYPE_AFF_AFD:
        case TSK_IMG_INFO_TYPE_AFF_AFM:
            img_info = aff_open(img_tmp, img_info);
            break;
#endif

#if HAVE_LIBEWF
        case TSK_IMG_INFO_TYPE_EWF_EWF:
            img_info = ewf_open(num_img_tmp, img_tmp, img_info);
            break;
#endif

        default:
            tsk_error_reset();
            tsk_errno = TSK_ERR_IMG_UNSUPTYPE;
            snprintf(tsk_errstr, TSK_ERRSTR_L, "%" PRIttocTSK, tp);
            return NULL;
        }

        /* Advance the pointer */
        tp = next;
    }

    /* Return the highest layer */
    return img_info;
}
Exemplo n.º 7
0
static void __attribute__((constructor)) startup(void)
{
#else
#define RETURN_VALUE 0
static void *ignore_ud2_addr;
// scratch test code
int main(void)
{
#endif

	char *debug_level_str = getenv("TRAP_SYSCALLS_DEBUG");
	char *footprint_fd_str = getenv("TRAP_SYSCALLS_FOOTPRINT_FD");
	char *trace_fd_str = getenv("TRAP_SYSCALLS_TRACE_FD");
	char *sleep_for_seconds_str = getenv("TRAP_SYSCALLS_SLEEP_FOR_SECONDS");
	char *stop_self_str = getenv("TRAP_SYSCALLS_STOP_SELF");
	stop_self = (stop_self_str != NULL);
	footprints_spec_filename = getenv("TRAP_SYSCALLS_FOOTPRINT_SPEC_FILENAME");
	struct timespec one_second = { /* seconds */ 1, /* nanoseconds */ 0 };
	if (debug_level_str) debug_level = atoi(debug_level_str);
	if (trace_fd_str) trace_fd = atoi(trace_fd_str);
	if (footprint_fd_str) footprint_fd = atoi(footprint_fd_str);
	if (sleep_for_seconds_str) sleep_for_seconds = atoi(sleep_for_seconds_str);
	debug_printf(0, "Debug level is %s=%d.\n", debug_level_str, debug_level);
	if (stop_self) {
		self_pid = raw_getpid();
		debug_printf(0, "TRAP_SYSCALLS_STOP_SELF is set, sending SIGSTOP to self (pid %d)\n", self_pid);
		raw_kill(self_pid, SIGSTOP);
	}
	debug_printf(0, "TRAP_SYSCALLS_SLEEP_FOR_SECONDS is %s, pausing for %d seconds", sleep_for_seconds_str, sleep_for_seconds);
	for (int i = 0; i < sleep_for_seconds; i++) {
		raw_nanosleep(&one_second, NULL);
		debug_printf(0, ".");
	}
	debug_printf(0, "\n");

	/* Is fd open? If so, it's the input fd for our sanity check info
	 * from systemtap. */
	debug_printf(0, "TRAP_SYSCALLS_FOOTPRINT_FD is %s, ", footprint_fd_str);
	if (footprint_fd > 2)
	{
		struct stat buf;
		int stat_ret = raw_fstat(footprint_fd, &buf);
		if (stat_ret == 0) {
			debug_printf(0, "fd %d is open; outputting systemtap cross-check info.\n", footprint_fd);
			/* PROBLEM: ideally we'd read in the stap script's output ourselves, and process
			 * it at every system call. But by reading in stuff from stap, we're doing more
			 * copying to/from userspace, so creating a feedback loop which would blow up.
			 *
			 * Instead we write out what we think we touched, and do a diff outside the process.
			 * This also adds noise to stap's output, but without the feedback cycle: we ourselves
			 * won't read the extra output, hence won't write() more stuff in response.
			 */
			__write_footprints = 1;
			footprints_out = fdopen(footprint_fd, "a");
			if (!footprints_out)
				{
					debug_printf(0, "Could not open footprints output stream for writing!\n");
				}

			if (footprints_spec_filename) {

				 footprints = parse_footprints_from_file(footprints_spec_filename, &footprints_env);
				 
			} else {
				 debug_printf(0, "no footprints spec filename provided\n", footprints_spec_filename);
			}

			
		} else {
			debug_printf(0, "fd %d is closed; skipping systemtap cross-check info.\n", footprint_fd);
		}

	}
	else
	{
		debug_printf(0, "skipping systemtap cross-check info\n");
	}

	debug_printf(0, "TRAP_SYSCALLS_TRACE_FD is %s, ", trace_fd_str);
	if (!trace_fd_str || trace_fd == 2) {
		debug_printf(0, "dup'ing stderr, ");
		trace_fd = dup(2);
	}
	
	if (trace_fd >= 0) {
		struct stat buf;
		int stat_ret = raw_fstat(trace_fd, &buf);
		if (stat_ret == 0) {
			debug_printf(0, "fd %d is open; outputting traces there.\n", trace_fd);
			__write_traces = 1;
			traces_out = fdopen(trace_fd, "a");
			if (!traces_out)
				{
					debug_printf(0, "Could not open traces output stream for writing!\n");
				}
		} else {
			debug_printf(0, "fd %d is closed; not outputting traces.\n", trace_fd);
		}
	} else {
		debug_printf(0, "not outputting traces.\n");
	}

	int fd = raw_open("/proc/self/maps", O_RDONLY);

	if (fd != -1)
	{
		// we use a simple buffer and a read loop
		char buf[8192];
		unsigned int ret;
		char *buf_pos = &buf[0]; // the next position to fill in the buffer
		char *entry_start_pos = &buf[0]; // the position
		size_t size_requested;
		do
		{
			// read some stuff, perhaps filling up the buffer
			size_requested = sizeof buf - (buf_pos - buf);
			ret = raw_read(fd, buf_pos, size_requested);
			char *buf_limit = buf_pos + ret;
			assert(buf_limit <= &buf[sizeof buf]);

			// we have zero or more complete entries in the buffer; iterate over them
			char *seek_pos;
			while (1)
			{
				seek_pos = entry_start_pos;
				// search forward for a newline
				while (seek_pos != buf_limit && *seek_pos != '\n')
				{ ++seek_pos; }

				// did we find one?
				if (seek_pos == buf_limit)
				{
					// no!
					// but we have a partial entry in the buffer
					// between entry_start_pos and seek_pos;
					// copy it to the start, re-set and continue
					__builtin_memmove(&buf[0], entry_start_pos, seek_pos - entry_start_pos);
					buf_pos = &buf[seek_pos - entry_start_pos];
					entry_start_pos = &buf[0];
					break;
				}
				else
				{
					assert(*seek_pos == '\n');
					// we have a complete entry; read it and advance entry_start_pos
					char debug_buf1[seek_pos - entry_start_pos + 1];
					strncpy(debug_buf1, entry_start_pos, seek_pos - entry_start_pos);
					debug_buf1[sizeof debug_buf1 - 1] = '\0';
					debug_printf(1, "DEBUG: entry is: %s\n", debug_buf1);
					char debug_buf2[buf_pos - buf];
					strncpy(debug_buf2, buf, buf_pos - buf);
					debug_buf2[sizeof debug_buf2 - 1] = '\0';
					debug_printf(1, "DEBUG: buffer is: %s", debug_buf2);
					saw_mapping(entry_start_pos, seek_pos);
					entry_start_pos = seek_pos + 1;
					// if the newline was the last in the buffer, break and read more
					if (entry_start_pos == buf_pos + sizeof buf)
					{ buf_pos = entry_start_pos = &buf[0]; break; }

					// else we might have another entry; go round again
					continue;
				}
			}
		} while (ret > 0);
		raw_close(fd);
	}

	/* Install our SIGILL (was SIGTRAP, but that interferes with gdb) handler.
	 * Linux seems to require us to provide a restorer; the code is in restore_rt. */
	struct sigaction action = {
		//.sa_sigaction = &handle_sigtrap,
		.sa_handler = &handle_sigill,
		.sa_mask = 0,
		.sa_flags = /*SA_SIGINFO |*/ 0x04000000u /* SA_RESTORER */ | /*SA_RESTART |*/ SA_NODEFER,
		.sa_restorer = restore_rt
	};
	struct sigaction oldaction;
	raw_rt_sigaction(SIGILL, &action, &oldaction);

	/* Un-executablize our own code, except for the signal handler and the remainder of
	 * this function and those afterwards.
	 *
	 * For this, we need our load address. How can we get this? We've already seen it! */
	// long int len = &&exit_and_return - our_text_begin_address;
	// long int ret;
	// long int longprot = PROT_NONE;
	// long int op = SYS_mprotect;

	//	__asm__ (".align 4096");
exit_and_return:
	//__asm__ volatile ("movq %0, %%rdi      # \n\
	//		   movq %1, %%rsi      # \n\
	//		   movq %2, %%rdx      # \n\
	//		  "FIX_STACK_ALIGNMENT " \n\
	//		   movq %3, %%rax      # \n\
	//		   syscall	     # do the syscall \n\
	//		  "UNFIX_STACK_ALIGNMENT " \n"
	//  : /* no output*/ : "rm"(our_text_begin_address), "rm"(len), "rm"(longprot), "rm"(op) :  "%rax", "r12", SYSCALL_CLOBBER_LIST);

#ifdef EXECUTABLE
	// HACK for testing: do a ud2 right now!
	ignore_ud2_addr = &&ud2_addr;
ud2_addr:
	__asm__ ("ud2\n");

	// we must also exit without running any libdl exit handlers,
	// because we're an executable so our csu/startfiles include some cleanup
	// that will now cause traps (this isn't necessary in the shared library case)
	raw_exit(0);
#endif
	return RETURN_VALUE;
}

// For debug printing inside handle_sigill we have to know
// that it's our own debug printing in order to filter it
// out of the footprints, hence this noinline function
// rather than using the normal macro
__attribute__ ((noinline)) static void _handle_sigill_debug_printf(int level, const char *fmt, ...) {
	 va_list vl;
	 va_start(vl, fmt);
	 if ((level) <= debug_level) {
		  vfprintf(*p_err_stream, fmt, vl);
		  fflush(*p_err_stream);
	 }
	 va_end(vl);
}
Exemplo n.º 8
0
/**
 * \ingroup imglib
 * Opens one or more disk image files so that they can be read.  If a file format
 * type is specified, this function will call the specific routine to open the file.
 * Otherwise, it will detect the type (it will default to raw if no specific type can
 * be detected).   This function must be called before a disk image can be read from.
 * Note that the data type used to store the image paths is a TSK_TCHAR, which changes
 * depending on a Unix or Windows build.  If you will always have UTF8, then consider
 * using tsk_img_open_utf8().
 *
 * @param num_img The number of images to open (will be > 1 for split images).
 * @param images The path to the image files (the number of files must
 * be equal to num_img and they must be in a sorted order)
 * @param type The disk image type (can be autodetection)
 * @param a_ssize Size of device sector in bytes (or 0 for default)
 *
 * @return Pointer to TSK_IMG_INFO or NULL on error
 */
TSK_IMG_INFO *
tsk_img_open(int num_img,
    const TSK_TCHAR * const images[], TSK_IMG_TYPE_ENUM type,
    unsigned int a_ssize)
{
    TSK_IMG_INFO *img_info = NULL;

    // Get rid of any old error messages laying around
    tsk_error_reset();

    if ((num_img == 0) || (images[0] == NULL)) {
        tsk_error_reset();
        tsk_error_set_errno(TSK_ERR_IMG_NOFILE);
        tsk_error_set_errstr("tsk_img_open");
        return NULL;
    }

    if ((a_ssize > 0) && (a_ssize < 512)) {
        tsk_error_reset();
        tsk_error_set_errno(TSK_ERR_IMG_ARG);
        tsk_error_set_errstr("sector size is less than 512 bytes (%d)",
            a_ssize);
        return NULL;
    }

    if ((a_ssize % 512) != 0) {
        tsk_error_reset();
        tsk_error_set_errno(TSK_ERR_IMG_ARG);
        tsk_error_set_errstr("sector size is not a multiple of 512 (%d)",
            a_ssize);
        return NULL;
    }


    if (tsk_verbose)
        TFPRINTF(stderr,
            _TSK_T("tsk_img_open: Type: %d   NumImg: %d  Img1: %s\n"),
            type, num_img, images[0]);

    /* If no type is given, then we use the autodetection methods
     * In case the image file matches the signatures of multiple formats,
     * we try all of the embedded formats
     */
    if (type == TSK_IMG_TYPE_DETECT) {
        TSK_IMG_INFO *img_set = NULL;
#if HAVE_LIBAFFLIB || HAVE_LIBEWF
        char *set = NULL;
#endif

        // we rely on tsk_errno, so make sure it is 0
        tsk_error_reset();

        /* Try the non-raw formats first */
#if HAVE_LIBAFFLIB
        if ((img_info = aff_open(images, a_ssize)) != NULL) {
            /* we don't allow the "ANY" when autodetect is used because
             * we only want to detect the tested formats. */
            if (img_info->itype == TSK_IMG_TYPE_AFF_ANY) {
                img_info->close(img_info);
            }
            else {
                set = "AFF";
                img_set = img_info;
            }
        }
        else {
            // If AFF is otherwise happy except for a password, stop trying to guess
            if (tsk_error_get_errno() == TSK_ERR_IMG_PASSWD) {
                return NULL;
            }
            tsk_error_reset();
        }
#endif

#if HAVE_LIBEWF
        if ((img_info = ewf_open(num_img, images, a_ssize)) != NULL) {
            if (set == NULL) {
                set = "EWF";
                img_set = img_info;
            }
            else {
                img_set->close(img_set);
                img_info->close(img_info);
                tsk_error_reset();
                tsk_error_set_errno(TSK_ERR_IMG_UNKTYPE);
                tsk_error_set_errstr("EWF or %s", set);
                return NULL;
            }
        }
        else {
            tsk_error_reset();
        }
#endif
        
        // if any of the non-raw formats were detected, then use it.
        if (img_set != NULL)
            return img_set;

        // otherwise, try raw
        if ((img_info = raw_open(num_img, images, a_ssize)) != NULL) {
            return img_info;
        }
        else if (tsk_error_get_errno() != 0) {
            return NULL;
        }        
        
        tsk_error_reset();
        tsk_error_set_errno(TSK_ERR_IMG_UNKTYPE);
        return NULL;
    }

    /*
     * Type values
     */

    switch (type) {
    case TSK_IMG_TYPE_RAW:
            img_info = raw_open(num_img, images, a_ssize);
            break;

#if HAVE_LIBAFFLIB
        case TSK_IMG_TYPE_AFF_AFF:
        case TSK_IMG_TYPE_AFF_AFD:
        case TSK_IMG_TYPE_AFF_AFM:
        case TSK_IMG_TYPE_AFF_ANY:
            img_info = aff_open(images, a_ssize);
            break;
#endif

#if HAVE_LIBEWF
        case TSK_IMG_TYPE_EWF_EWF:
            img_info = ewf_open(num_img, images, a_ssize);
            break;
#endif

        default:
            tsk_error_reset();
            tsk_error_set_errno(TSK_ERR_IMG_UNSUPTYPE);
            tsk_error_set_errstr("%d", type);
            return NULL;
        }

        return img_info;
    }
Exemplo n.º 9
0
int main(int argc, char *argv[])
{
    int use_audio, use_video;
    int fullscreen;
    int scalesize;
    int scale_width, scale_height;
    int loop_play;
    int i, pause;
    int volume;
    Uint32 seek;
    float skip;
    int bilinear_filtering;
    SDL_Surface *screen = NULL;
    SMPEG *mpeg;
    SMPEG_Info info;
    char *basefile;
    const char *title = NULL;
    SDL_version sdlver;
    SMPEG_version smpegver;
    int fd;
    char buf[32];
    int status;

    /* Get the command line options */
    use_audio = 1;
    use_video = 1;
    fullscreen = 0;
    scalesize = 1;
    scale_width = 0;
    scale_height = 0;
    loop_play = 0;
    volume = 100;
    seek = 0;
    skip = 0;
    bilinear_filtering = 0;
    fd = 0;
    for ( i=1; argv[i] && (argv[i][0] == '-') && (argv[i][1] != 0); ++i ) {
        if ( (strcmp(argv[i], "--noaudio") == 0) ||
                (strcmp(argv[i], "--nosound") == 0) ) {
            use_audio = 0;
        } else if ( strcmp(argv[i], "--novideo") == 0 ) {
            use_video = 0;
        } else if ( strcmp(argv[i], "--fullscreen") == 0 ) {
            fullscreen = 1;
        } else if ((strcmp(argv[i], "--double") == 0)||(strcmp(argv[i], "-2") == 0)) {
            scalesize = 2;
        } else if ((strcmp(argv[i], "--loop") == 0) || (strcmp(argv[i], "-l") == 0)) {
            loop_play = 1;
        } else if ( strcmp(argv[i], "--bilinear") == 0 ) {
            bilinear_filtering = 1;
        } else if ((strcmp(argv[i], "--seek") == 0)||(strcmp(argv[i], "-S") == 0)) {
            ++i;
            if ( argv[i] ) {
                seek = atol(argv[i]);
            }
        } else if ((strcmp(argv[i], "--skip") == 0)||(strcmp(argv[i], "-k") == 0)) {
            ++i;
            if ( argv[i] ) {
                skip = (float)atof(argv[i]);
            }
        } else if ((strcmp(argv[i], "--volume") == 0)||(strcmp(argv[i], "-v") == 0)) {
            ++i;
            if (i >= argc)
            {
                fprintf(stderr, "Please specify volume when using --volume or -v\n");
                return(1);
            }
            if ( argv[i] ) {
                volume = atoi(argv[i]);
            }
            if ( ( volume < 0 ) || ( volume > 100 ) ) {
                fprintf(stderr, "Volume must be between 0 and 100\n");
                volume = 100;
            }
        } else if ((strcmp(argv[i], "--title") == 0)||(strcmp(argv[i], "-t") == 0)) {
            ++i;
            if (i >= argc)
            {
                fprintf(stderr, "Please specify title when using --title or -t\n");
                return(1);
            }
            if ( argv[i] ) {
                title = argv[i];
            }
        } else if ((strcmp(argv[i], "--version") == 0) ||
                   (strcmp(argv[i], "-V") == 0)) {
            sdlver = *SDL_Linked_Version();
            SMPEG_VERSION(&smpegver);
            printf("SDL version: %d.%d.%d\n"
                   "SMPEG version: %d.%d.%d\n",
                   sdlver.major, sdlver.minor, sdlver.patch,
                   smpegver.major, smpegver.minor, smpegver.patch);
            return(0);
        } else if ((strcmp(argv[i], "--scale") == 0)||(strcmp(argv[i], "-s") == 0)) {
            ++i;
            if ( argv[i] ) {
                sscanf(argv[i], "%dx%d", &scale_width, &scale_height);
            }
        } else if ((strcmp(argv[i], "--help") == 0) || (strcmp(argv[i], "-h") == 0)) {
            usage(argv[0]);
            return(0);
        } else {
            fprintf(stderr, "Warning: Unknown option: %s\n", argv[i]);
        }
    }
    /* If there were no arguments just print the usage */
    if (argc == 1) {
        usage(argv[0]);
        return(0);
    }

#if defined(linux) || defined(__FreeBSD__) /* Plaympeg doesn't need a mouse */
    putenv("SDL_NOMOUSE=1");
#endif

    /* Play the mpeg files! */
    status = 0;
    for ( ; argv[i]; ++i ) {
        /* Initialize SDL */
        if ( use_video ) {
            if ((SDL_Init(SDL_INIT_VIDEO) < 0) || !SDL_VideoDriverName(buf, 1)) {
                fprintf(stderr, "Warning: Couldn't init SDL video: %s\n",
                        SDL_GetError());
                fprintf(stderr, "Will ignore video stream\n");
                use_video = 0;
            }
        }

        if ( use_audio ) {
            if ((SDL_Init(SDL_INIT_AUDIO) < 0) || !SDL_AudioDriverName(buf, 1)) {
                fprintf(stderr, "Warning: Couldn't init SDL audio: %s\n",
                        SDL_GetError());
                fprintf(stderr, "Will ignore audio stream\n");
                use_audio = 0;
            }
        }

        /* Allow Ctrl-C when there's no video output */
        signal(SIGINT, next_movie);

        /* Create the MPEG stream */
#ifdef NET_SUPPORT
#ifdef RAW_SUPPORT
        /* Check if source is an IP address and port*/
        if((fd = raw_open(argv[i])) != 0)
            mpeg = SMPEG_new_descr(fd, &info, use_audio);
        else
#endif
#ifdef HTTP_SUPPORT
            /* Check if source is an http URL */
            if((fd = http_open(argv[i])) != 0)
                mpeg = SMPEG_new_descr(fd, &info, use_audio);
            else
#endif
#ifdef FTP_SUPPORT
                /* Check if source is an http URL */
                if((fd = ftp_open(argv[i])) != 0)
                    mpeg = SMPEG_new_descr(fd, &info, use_audio);
                else
#endif
#endif
#ifdef VCD_SUPPORT
                    /* Check if source is a CDROM device */
                    if((fd = vcd_open(argv[i])) != 0)
                        mpeg = SMPEG_new_descr(fd, &info, use_audio);
                    else
#endif
                    {
                        if(strcmp(argv[i], "-") == 0) /* Use stdin for input */
                            mpeg = SMPEG_new_descr(0, &info, use_audio);
                        else
                            mpeg = SMPEG_new(argv[i], &info, use_audio);
                    }

        if ( SMPEG_error(mpeg) ) {
            fprintf(stderr, "%s: %s\n", argv[i], SMPEG_error(mpeg));
            SMPEG_delete(mpeg);
            status = -1;
            continue;
        }
        SMPEG_enableaudio(mpeg, use_audio);
        SMPEG_enablevideo(mpeg, use_video);
        SMPEG_setvolume(mpeg, volume);

        /* Enable software bilinear filtering, if desired */
        if ( bilinear_filtering ) {
            SMPEG_Filter *filter;

            filter = SMPEGfilter_bilinear();
            filter = SMPEG_filter( mpeg, filter );
            filter->destroy(filter);
        }

        /* Print information about the video */
        basefile = strrchr(argv[i], '/');
        if ( basefile ) {
            ++basefile;
        } else {
            basefile = argv[i];
        }
        if ( info.has_audio && info.has_video ) {
            printf("%s: MPEG system stream (audio/video)\n", basefile);
        } else if ( info.has_audio ) {
            printf("%s: MPEG audio stream\n", basefile);
        } else if ( info.has_video ) {
            printf("%s: MPEG video stream\n", basefile);
        }
        if ( info.has_video ) {
            printf("\tVideo %dx%d resolution\n", info.width, info.height);
        }
        if ( info.has_audio ) {
            printf("\tAudio %s\n", info.audio_string);
        }
        if ( info.total_size ) {
            printf("\tSize: %d\n", info.total_size);
        }
        if ( info.total_time ) {
            printf("\tTotal time: %f\n", info.total_time);
        }

        /* Set up video display if needed */
        if ( info.has_video && use_video ) {
            const SDL_VideoInfo *video_info;
            Uint32 video_flags;
            int video_bpp;
            int width, height;

            /* Get the "native" video mode */
            video_info = SDL_GetVideoInfo();
            switch (video_info->vfmt->BitsPerPixel) {
            case 16:
            case 24:
            case 32:
                video_bpp = video_info->vfmt->BitsPerPixel;
                break;
            default:
                video_bpp = 16;
                break;
            }
            if ( scale_width ) {
                width = scale_width;
            } else {
                width = info.width;
            }
            width *= scalesize;
            if ( scale_height ) {
                height = scale_height;
            } else {
                height = info.height;
            }
            height *= scalesize;
            video_flags = SDL_SWSURFACE;
            if ( fullscreen ) {
                video_flags = SDL_FULLSCREEN|SDL_DOUBLEBUF|SDL_HWSURFACE;
            }
            video_flags |= SDL_ASYNCBLIT;
            video_flags |= SDL_RESIZABLE;
            screen = SDL_SetVideoMode(width, height, video_bpp, video_flags);
            if ( screen == NULL ) {
                fprintf(stderr, "Unable to set %dx%d video mode: %s\n",
                        width, height, SDL_GetError());
                continue;
            }
            if (title != NULL) {
                SDL_WM_SetCaption(title, title);
            } else {
                SDL_WM_SetCaption(argv[i], "plaympeg");
            }
            if ( screen->flags & SDL_FULLSCREEN ) {
                SDL_ShowCursor(0);
            }
            SMPEG_setdisplay(mpeg, screen, NULL, update);
            SMPEG_scaleXY(mpeg, screen->w, screen->h);
        } else {
            SDL_QuitSubSystem(SDL_INIT_VIDEO);
            use_video = 0;
        }

        /* Set any special playback parameters */
        if ( loop_play ) {
            SMPEG_loop(mpeg, 1);
        }

        /* Seek starting position */
        if(seek) SMPEG_seek(mpeg, seek);

        /* Skip seconds to starting position */
        if(skip) SMPEG_skip(mpeg, skip);

        /* Play it, and wait for playback to complete */
        SMPEG_play(mpeg);
        done = 0;
        pause = 0;
        while ( ! done && ( pause || (SMPEG_status(mpeg) == SMPEG_PLAYING) ) ) {
            SDL_Event event;

            while ( use_video && SDL_PollEvent(&event) ) {
                switch (event.type) {
                case SDL_VIDEORESIZE: {
                    SDL_Surface *old_screen = screen;
                    SMPEG_pause(mpeg);
                    screen = SDL_SetVideoMode(event.resize.w, event.resize.h, screen->format->BitsPerPixel, screen->flags);
                    if ( old_screen != screen ) {
                        SMPEG_setdisplay(mpeg, screen, NULL, update);
                    }
                    SMPEG_scaleXY(mpeg, screen->w, screen->h);
                    SMPEG_pause(mpeg);
                }
                break;
                case SDL_KEYDOWN:
                    if ( (event.key.keysym.sym == SDLK_ESCAPE) || (event.key.keysym.sym == SDLK_q) ) {
                        // Quit
                        done = 1;
                    } else if ( event.key.keysym.sym == SDLK_RETURN ) {
                        // toggle fullscreen
                        if ( event.key.keysym.mod & KMOD_ALT ) {
                            SDL_WM_ToggleFullScreen(screen);
                            fullscreen = (screen->flags & SDL_FULLSCREEN);
                            SDL_ShowCursor(!fullscreen);
                        }
                    } else if ( event.key.keysym.sym == SDLK_UP ) {
                        // Volume up
                        if ( volume < 100 ) {
                            if ( event.key.keysym.mod & KMOD_SHIFT ) {   // 10+
                                volume += 10;
                            } else if ( event.key.keysym.mod & KMOD_CTRL ) { // 100+
                                volume = 100;
                            } else {                                     // 1+
                                volume++;
                            }
                            if ( volume > 100 )
                                volume = 100;
                            SMPEG_setvolume(mpeg, volume);
                        }
                    } else if ( event.key.keysym.sym == SDLK_DOWN ) {
                        // Volume down
                        if ( volume > 0 ) {
                            if ( event.key.keysym.mod & KMOD_SHIFT ) {
                                volume -= 10;
                            } else if ( event.key.keysym.mod & KMOD_CTRL ) {
                                volume = 0;
                            } else {
                                volume--;
                            }
                            if ( volume < 0 )
                                volume = 0;
                            SMPEG_setvolume(mpeg, volume);
                        }
                    } else if ( event.key.keysym.sym == SDLK_PAGEUP ) {
                        // Full volume
                        volume = 100;
                        SMPEG_setvolume(mpeg, volume);
                    } else if ( event.key.keysym.sym == SDLK_PAGEDOWN ) {
                        // Volume off
                        volume = 0;
                        SMPEG_setvolume(mpeg, volume);
                    } else if ( event.key.keysym.sym == SDLK_SPACE ) {
                        // Toggle play / pause
                        if ( SMPEG_status(mpeg) == SMPEG_PLAYING ) {
                            SMPEG_pause(mpeg);
                            pause = 1;
                        } else {
                            SMPEG_play(mpeg);
                            pause = 0;
                        }
                    } else if ( event.key.keysym.sym == SDLK_RIGHT ) {
                        // Forward
                        if ( event.key.keysym.mod & KMOD_SHIFT ) {
                            SMPEG_skip(mpeg, 100);
                        } else if ( event.key.keysym.mod & KMOD_CTRL ) {
                            SMPEG_skip(mpeg, 50);
                        } else {
                            SMPEG_skip(mpeg, 5);
                        }
                    } else if ( event.key.keysym.sym == SDLK_LEFT ) {
                        // Reverse
                        if ( event.key.keysym.mod & KMOD_SHIFT ) {

                        } else if ( event.key.keysym.mod & KMOD_CTRL ) {

                        } else {

                        }
                    } else if ( event.key.keysym.sym == SDLK_KP_MINUS ) {
                        // Scale minus
                        if ( scalesize > 1 ) {
                            scalesize--;
                        }
                    } else if ( event.key.keysym.sym == SDLK_KP_PLUS ) {
                        // Scale plus
                        scalesize++;
                    } else if ( event.key.keysym.sym == SDLK_f ) {
                        // Toggle filtering on/off
                        if ( bilinear_filtering ) {
                            SMPEG_Filter *filter = SMPEGfilter_null();
                            filter = SMPEG_filter( mpeg, filter );
                            filter->destroy(filter);
                            bilinear_filtering = 0;
                        } else {
                            SMPEG_Filter *filter = SMPEGfilter_bilinear();
                            filter = SMPEG_filter( mpeg, filter );
                            filter->destroy(filter);
                            bilinear_filtering = 1;
                        }
                    }
                    break;
                case SDL_QUIT:
                    done = 1;
                    break;
                default:
                    break;
                }
            }
            SDL_Delay(1000/2);
        }
        SMPEG_delete(mpeg);
    }
    SDL_Quit();

#if defined(RAW_SUPPORT) || defined(HTTP_SUPPORT) || defined(FTP_SUPPORT) || \
    defined(VCD_SUPPORT)
    if(fd) close(fd);
#endif

    return(status);
}
Exemplo n.º 10
0
void test_thread(void * pParam) 
{	
	RAW_S32 ret;
	RAW_S32 received_bytes;
	
	int aa = 0x55;
	int bb = 0x56;
	
	vc_port_printf("passing argument is %x\n", *(RAW_U32 *)pParam);
	
	raw_page_init(test_page_mem, test_page_mem + 1024*1024);
	raw_malloc_init();
	
	fifo_init(&fifo, fifo_space, 16);
	fifo_in(&fifo, &aa, 4);
	fifo_in(&fifo, &bb, 4);

	fifo_out(&fifo, &fifo_data, 4);
	fifo_out(&fifo, &fifo_data, 4);
	fifo_in(&fifo, &bb, 4);
	fifo_in(&fifo, &bb, 4);
	fifo_in(&fifo, &bb, 4);
	fifo_out(&fifo, &fifo_data, 4);
	received_bytes = fifo_out_all(&fifo, fifo_received_data);
	fifo_data = 0;
	
	fifo_out(&fifo, &fifo_data, 4);

	rsh_register_command(&test_rsh_command, &pxNewListItem1);
	rsh_register_command(&test_rsh_command2, &pxNewListItem2);
	rsh_register_command(&three_parameters_case, &pxNewListItem3);

	rsh_register_command(&test_rsh_command3, &pxNewListItem4);
	rsh_register_command(&test_rsh_command4, &pxNewListItem5);

	do {

		ret = rsh_process_command("help", out_put_shell, 1024);
		vc_port_printf("%s\n", out_put_shell);
		
	} while (ret == 0);

	do {
		ret = rsh_process_command("tes222222", out_put_shell, 1024);
	} while (ret == 0);


	do {
		ret = rsh_process_command("bb1", out_put_shell, 1024);
		vc_port_printf("%s\n", out_put_shell);
	} while (ret == 0);
	

	do {
		ret = rsh_process_command("aa", out_put_shell, 1024);
		vc_port_printf("%s\n", out_put_shell);
	} while (ret == 0);

	do {
		ret = rsh_process_command("aaa", out_put_shell, 1024);
	} while (ret == 0);

	
	do {
		ret = rsh_process_command("echo_3_parameters 1 2 3", out_put_shell, 1024);
		vc_port_printf("%s\n", out_put_shell);
	} while (ret == 0);

	raw_open("/I2C3/", 0);
	
	pthread_create(&thread2, 0, test_thread2, 0);
	pthread_create(&thread3, 0, test_thread3, 0);
	pthread_create(&thread4, 0, test_thread4, 0);
	pthread_create(&thread5, 0, test_thread5, 0);
	pthread_create(&thread6, 0, test_thread6, 0);
	
	raw_task_delete(raw_task_identify());
	
}
Exemplo n.º 11
0
int main(int argc, char **argv)
{
    wav_io_context_t wav_io = { read_callback, seek_callback, tell_callback };
    m4af_io_callbacks_t
        m4af_io = { read_callback, write_callback, seek_callback, tell_callback };
    aacenc_param_ex_t params = { 0 };

    int result = 2;
    FILE *ifp = 0;
    FILE *ofp = 0;
    char *output_filename = 0;
#ifdef USE_LIBSNDFILE
    SNDFILE* snd = NULL;
    SF_INFO snd_info;
    pcm_sample_description_t snd_desc = { 0 };
#else
    wav_reader_t *wavf = 0;
#endif
    HANDLE_AACENCODER encoder = 0;
    AACENC_InfoStruct aacinfo = { 0 };
    m4af_ctx_t *m4af = 0;
    const pcm_sample_description_t *sample_format;
    int downsampled_timescale = 0;
    int frame_count = 0;
    struct stat stb = { 0 };

    setlocale(LC_CTYPE, "");
    setbuf(stderr, 0);

    if (parse_options(argc, argv, &params) < 0)
        return 1;

#ifdef USE_LIBSNDFILE
    if ((snd = sf_open (params.input_filename, SFM_READ, &snd_info)) == NULL) {
        fprintf(stderr, "ERROR: broken / unsupported input file\n");
        goto END;
    }
#ifdef USE_LIBSAMPLERATE
    if(params.resample) {
        snd_desc.sample_rate = params.resample;
        printf("resampling to %dhz\n", snd_desc.sample_rate);
    } else {
        snd_desc.sample_rate = snd_info.samplerate;
    }
    snd_desc.sample_type = PCM_TYPE_FLOAT; // always -- libsndfile does the conversion for us
    snd_desc.bits_per_channel = sizeof(float)*8;
#else
    snd_desc.sample_rate = snd_info.samplerate;
    snd_desc.sample_type = PCM_TYPE_SINT; // always -- libsndfile does the conversion for us
    snd_desc.bits_per_channel = sizeof(short)*8;
#endif
    snd_desc.channels_per_frame = snd_info.channels;
    snd_desc.bytes_per_frame = snd_info.channels * (snd_desc.bits_per_channel / 8);
    snd_desc.channel_mask = 0;

    sample_format = &snd_desc;
#else
    if ((ifp = aacenc_fopen(params.input_filename, "rb")) == 0) {
        aacenc_fprintf(stderr, "ERROR: %s: %s\n", params.input_filename,
                       strerror(errno));
        goto END;
    }
    
    if (fstat(fileno(ifp), &stb) == 0 && (stb.st_mode & S_IFMT) != S_IFREG) {
        wav_io.seek = 0;
        wav_io.tell = 0;
    }
    
    if (!params.is_raw) {
        if ((wavf = wav_open(&wav_io, ifp, params.ignore_length)) == 0) {
            fprintf(stderr, "ERROR: broken / unsupported input file\n");
            goto END;
        }
    } else {
        int bytes_per_channel;
        pcm_sample_description_t desc = { 0 };
        if (parse_raw_spec(params.raw_format, &desc) < 0) {
            fprintf(stderr, "ERROR: invalid raw-format spec\n");
            goto END;
        }
        desc.sample_rate = params.raw_rate;
        desc.channels_per_frame = params.raw_channels;
        bytes_per_channel = (desc.bits_per_channel + 7) / 8;
        desc.bytes_per_frame = params.raw_channels * bytes_per_channel;
        if ((wavf = raw_open(&wav_io, ifp, &desc)) == 0) {
            fprintf(stderr, "ERROR: failed to open raw input\n");
            goto END;
        }
    }

    sample_format = wav_get_format(wavf);
#endif

    if (aacenc_init(&encoder, (aacenc_param_t*)&params, sample_format,
                    &aacinfo) < 0)
        goto END;

    if (!params.output_filename) {
        const char *ext = params.transport_format ? ".aac" : ".m4a";
        output_filename = generate_output_filename(params.input_filename, ext);
        params.output_filename = output_filename;
    }

    if ((ofp = aacenc_fopen(params.output_filename, "wb+")) == 0) {
        aacenc_fprintf(stderr, "ERROR: %s: %s\n", params.output_filename,
                       strerror(errno));
        goto END;
    }
    handle_signals();
    if (!params.transport_format) {
        uint32_t scale;
        unsigned framelen = aacinfo.frameLength;
        int sbr_mode = aacenc_is_sbr_active((aacenc_param_t*)&params);
        int sig_mode = aacEncoder_GetParam(encoder, AACENC_SIGNALING_MODE);
        if (sbr_mode && !sig_mode)
            downsampled_timescale = 1;
        scale = sample_format->sample_rate >> downsampled_timescale;
        if ((m4af = m4af_create(M4AF_CODEC_MP4A, scale, &m4af_io, ofp)) < 0)
            goto END;
        m4af_set_decoder_specific_info(m4af, 0, aacinfo.confBuf,
                                       aacinfo.confSize);
        m4af_set_fixed_frame_duration(m4af, 0,
                                      framelen >> downsampled_timescale);
        m4af_set_priming_mode(m4af, params.gapless_mode + 1);
        m4af_begin_write(m4af);
    }
Exemplo n.º 12
0
Arquivo: mpg321.c Projeto: e3c/mpg321
int main(int argc, char *argv[])
{
    int fd = 0;
    char *currentfile, old_dir[PATH_MAX];
    playlist *pl = NULL;
    struct id3_file *id3struct = NULL;
    struct id3_tag *id3tag = NULL;

    buffer playbuf;
    
    struct mad_decoder decoder;

    old_dir[0] = '\0';

    playbuf.pl = pl = new_playlist();

    if (!pl)
    {
        fprintf(stderr, "malloc failed at startup!\n");
        exit(1);
    }

    options.volume = MAD_F_ONE;

    status = MPG321_PLAYING;
    
    /* Get the command line options */
    parse_options(argc, argv, pl);

    /* If there were no files and no playlist specified just print the usage */
    if (!playlist_file && optind == argc)
    {
        usage(argv[0]);
        exit(0);
    }

    if (playlist_file)
        load_playlist(pl, playlist_file);
    
    add_cmdline_files(pl, argv);

    if (shuffle_play)
        shuffle_files(pl);

    ao_initialize();

    check_default_play_device();
    
    if (!(options.opt & MPG321_REMOTE_PLAY))
    {
        handle_signals(-1); /* initialize signal handler */
     
        remote_input_buf[0] = '\0';
    }
    
    if (!(options.opt & MPG321_QUIET_PLAY)) 
        mpg123_boilerplate();
    
    if (options.opt & MPG321_REMOTE_PLAY)
    {
        printf ("@R MPG123\n");
    }
    
    /* Play the mpeg files or zip it! */
    while((currentfile = get_next_file(pl, &playbuf)))
    {
        if (quit_now) 
            break;
        
        signal(SIGINT, SIG_DFL);
        
        playbuf.buf = NULL;
        playbuf.fd = -1;
        playbuf.length = 0;
        playbuf.done = 0;
        playbuf.num_frames = 0;
        playbuf.max_frames = -1;
        strncpy(playbuf.filename,currentfile, PATH_MAX);
        playbuf.filename[PATH_MAX-1] = '\0';
        
        if (status == MPG321_PLAYING) 
            file_change = 1;

        mad_timer_reset(&playbuf.duration);
        
        mad_timer_reset(&current_time);

        if (!(options.opt & MPG321_QUIET_PLAY) && file_change)
        {
            id3struct = id3_file_open (currentfile, ID3_FILE_MODE_READONLY);

            if (id3struct)
            {
                id3tag = id3_file_tag (id3struct);
            
                if (id3tag)
                {
                    show_id3 (id3tag);
                }

                id3_file_close (id3struct);
            }
        }

        if (options.opt & MPG321_REMOTE_PLAY && file_change)
        {
            id3struct = id3_file_open (currentfile, ID3_FILE_MODE_READONLY);

            if (id3struct)
            {
                id3tag = id3_file_tag (id3struct);
            
                if (id3tag)
                {
                    if (!show_id3(id3tag))
                    {
                        /* This shouldn't be necessary, but it appears that
                           libid3tag doesn't necessarily know if there are no
                           id3 tags on a given mp3 */
                        char * basec = strdup(currentfile);
                        char * basen = basename(basec);
                        
                        char * dot = strrchr(basen, '.');
                        
                        if (dot)
                            *dot = '\0';
                        
                        printf("@I %s\n", basen);

                        free(basec);
                    }
                }
                
                else
                {
                    fprintf(stderr, "Allocation error");
                    exit(1);
                }

                id3_file_close (id3struct);
            }
            
            else
            {
                char * basec = strdup(currentfile);
                char * basen = basename(basec);
                
                char * dot = strrchr(basen, '.');
                
                if (dot)
                    *dot = '\0';
                
                printf("@I %s\n", basen);

                free(basec);
            }
        }

        /* Create the MPEG stream */
        /* Check if source is on the network */
        if((fd = raw_open(currentfile)) != 0 || (fd = http_open(currentfile)) != 0
            || (fd = ftp_open(currentfile)) != 0)
        {
            playbuf.fd = fd;
            playbuf.buf = malloc(BUF_SIZE);
            playbuf.length = BUF_SIZE;
            
            mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
                            output, /*error*/0, /* message */ 0);
        }

        /* Check if we are to use stdin for input */
        else if(strcmp(currentfile, "-") == 0)
        {
            playbuf.fd = fileno(stdin);
            playbuf.buf = malloc(BUF_SIZE);
            playbuf.length = BUF_SIZE;

            mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0,
                            output, /*error*/0, /* message */ 0);
        }
            
        /* currentfile is a local file (presumably.) mmap() it */
        else
        {
            struct stat stat;
            
            if((fd = open(currentfile, O_RDONLY)) == -1)
            {
                mpg321_error(currentfile);

                /* mpg123 stops immediately if it can't open a file */
                break;
            }
            
            if(fstat(fd, &stat) == -1)
            {
                close(fd);
                mpg321_error(currentfile);
                continue;
            }
            
            if (!S_ISREG(stat.st_mode))
            {
                close(fd);
                continue;
            }
            
            calc_length(currentfile, &playbuf);

            if ((options.maxframes != -1) && (options.maxframes <= playbuf.num_frames))
            { 
                playbuf.max_frames = options.maxframes;
            }
            
            playbuf.frames = malloc((playbuf.num_frames + 1) * sizeof(void*));
            playbuf.times = malloc((playbuf.num_frames + 1) * sizeof(mad_timer_t));
    
            if((playbuf.buf = mmap(0, playbuf.length, PROT_READ, MAP_SHARED, fd, 0))
                                == MAP_FAILED)
            {
                close(fd);
                mpg321_error(currentfile);
                continue;
            }
            
            close(fd);
            playbuf.frames[0] = playbuf.buf;
            
            mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0,
                            output, /*error*/0, /* message */ 0);
        }

        if(!(options.opt & MPG321_QUIET_PLAY))/*zip it!!!*/
        {
            /* Because dirname might modify the argument */
            char * dirc = strdup(currentfile);
            char * basec = strdup(currentfile);

            char * basen = basename(basec);
            char * dirn = dirname(dirc);
            
            /* make sure that the file has a pathname; otherwise don't print out
               a Directory: listing */
            if(strchr(currentfile, '/') && strncmp(old_dir, dirn, PATH_MAX) != 0)
            {
                /* Print information about the file */
                fprintf(stderr, "\n");
                fprintf(stderr,"Directory: %s/\n", dirn);
                
                strncpy(old_dir, dirn, PATH_MAX);
                old_dir[PATH_MAX-1] = '\0';
            }
            
            /* print a newline between different songs only, not after
               Directory: listing */
            else
            {
                fprintf(stderr, "\n");
            }

            fprintf(stderr,"Playing MPEG stream from %s ...\n", basen);
    
            free(dirc);
            free(basec);
        }    

        signal(SIGINT, handle_signals);

        /* Every time the user gets us to rewind, we exit decoding,
           reinitialize it, and re-start it */
        while (1)
        {
            mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
            
            /* if we're rewinding on an mmap()ed stream */
            if(status == MPG321_REWINDING && playbuf.fd == -1) 
            {
                mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0,
                    output, /*error*/0, /* message */ 0);
            }    
            else
                break;
        } 

        if (!(options.opt & MPG321_QUIET_PLAY))
        {
            char time_formatted[11];
            mad_timer_string(current_time, time_formatted, "%.1u:%.2u", MAD_UNITS_MINUTES,
                       MAD_UNITS_SECONDS, 0);
            fprintf(stderr, "\n[%s] Decoding of %s finished.\n",time_formatted, basename(currentfile));
        }
        
        if (options.opt & MPG321_REMOTE_PLAY && status == MPG321_STOPPED)
        {
            clear_remote_file(pl);
        }

        mad_decoder_finish(&decoder);

        if (quit_now)
            break;

        if (playbuf.frames)
             free(playbuf.frames);

        if (playbuf.times)
            free(playbuf.times);
            
        if (playbuf.fd == -1)
        {
            munmap(playbuf.buf, playbuf.length);
        }

        else
        {
            free(playbuf.buf);
            if (playbuf.fd != fileno(stdin)) 
                close(playbuf.fd);
        }
    }

    if(playdevice)
        ao_close(playdevice);

    ao_shutdown();

#if defined(RAW_SUPPORT) || defined(HTTP_SUPPORT) || defined(FTP_SUPPORT) 
    if(fd) close(fd);
#endif

    return(0);
}