Exemplo n.º 1
0
/**
 * \brief Read data from a file.
 * \param[in] priv   pointer to module private data
 * \param[out] data  pointer to a memory block in which data is to be stored
 * \param[out] size  pointer to a memory block in which size of read data is to be stored
 * \param[in] timeout   NOT USED IN THIS INTERFACE
 * \return 0 on success (TRAP_E_OK), TRAP_E_IO_ERROR if error occurs during reading, TRAP_E_TERMINATED if interface was terminated.
 */
int file_recv(void *priv, void *data, uint32_t *size, int timeout)
{
   size_t loaded;
   char *next_file = NULL;
   /* header of message inside the buffer */
   uint16_t *m_head = data;
   uint32_t data_size = 0;

   file_private_t *config = (file_private_t*) priv;

   if (config->is_terminated) {
      return trap_error(config->ctx, TRAP_E_TERMINATED);
   }

   /* Check whether the file stream is opened */
   if (config->fd == NULL) {
      return trap_error(config->ctx, TRAP_E_NOT_INITIALIZED);
   }

#ifdef ENABLE_NEGOTIATION
neg_start:
   if (config->neg_initialized == 0) {
      switch(input_ifc_negotiation((void *) config, TRAP_IFC_TYPE_FILE)) {
      case NEG_RES_FMT_UNKNOWN:
         VERBOSE(CL_VERBOSE_LIBRARY, "Input_ifc_negotiation result: failed (unknown data format of the output interface).");
         return TRAP_E_FORMAT_MISMATCH;

      case NEG_RES_CONT:
         VERBOSE(CL_VERBOSE_LIBRARY, "Input_ifc_negotiation result: success.");
         config->neg_initialized = 1;
         break;

      case NEG_RES_RECEIVER_FMT_SUBSET:
         VERBOSE(CL_VERBOSE_LIBRARY, "Input_ifc_negotiation result: success (data specifier of the input interface is subset of the output interface data specifier).");
         config->neg_initialized = 1;
         break;

      case NEG_RES_SENDER_FMT_SUBSET:
         VERBOSE(CL_VERBOSE_LIBRARY, "Input_ifc_negotiation result: success (new data specifier of the output interface is subset of the old one; it was not first negotiation).");
         config->neg_initialized = 1;
         break;

      case NEG_RES_FAILED:
         VERBOSE(CL_VERBOSE_LIBRARY, "Input_ifc_negotiation result: failed (error while receiving hello message from output interface).");
         return TRAP_E_FORMAT_MISMATCH;

      case NEG_RES_FMT_MISMATCH:
         VERBOSE(CL_VERBOSE_LIBRARY, "Input_ifc_negotiation result: failed (data format or data specifier mismatch).");
         return TRAP_E_FORMAT_MISMATCH;

      default:
         VERBOSE(CL_VERBOSE_LIBRARY, "Input_ifc_negotiation result: default case");
         break;
      }
   }
#endif

   /* Reads 4 bytes from the file, determining the length of bytes to be read to @param[out] data */
   loaded = fread(&data_size, sizeof(uint32_t), 1, config->fd);
   if (loaded != 1) {
      if (feof(config->fd)) {
         next_file = get_next_file(priv);
         if (!next_file) {
            /* set size of buffer to the size of 1 message (including its header) */
            (*size) = 2;
            /* set the header of message to 0B */
            *m_head = 0;

            return TRAP_E_OK;
         } else {
            if (open_next_file(config, next_file) == 0) {
#ifdef ENABLE_NEGOTIATION
               goto neg_start;
#endif
            } else {
               return trap_errorf(config->ctx, TRAP_E_IO_ERROR, "INPUT FILE IFC[%d]: unable to open next file.", config->ifc_idx);
            }
         }
      } else {
         VERBOSE(CL_ERROR, "INPUT FILE IFC: read error occurred in file: %s", config->filename);
         return trap_errorf(config->ctx, TRAP_E_IO_ERROR, "INPUT FILE IFC: unable to read");
      }
   }

   *size = ntohl(data_size);
   /* Reads (*size) bytes from the file */
   loaded = fread(data, 1, (*size), config->fd);
   if (loaded != (*size)) {
         VERBOSE(CL_ERROR, "INPUT FILE IFC: read incorrect number of bytes from file: %s. Attempted to read %d bytes, but the actual count of bytes read was %zu.", config->filename, (*size), loaded);
   }

   return TRAP_E_OK;
}
Exemplo n.º 2
0
/* -------------------------------------------------------------------------- */
int main(int argc, char *argv[])
{
	FILE *fout = NULL;

	opj_dparameters_t parameters;			/* Decompression parameters */
	opj_image_t* image = NULL;					/* Image structure */
	opj_codec_t* l_codec = NULL;				/* Handle to a decompressor */
	opj_stream_t *l_stream = NULL;				/* Stream */
	opj_codestream_info_v2_t* cstr_info = NULL;
	opj_codestream_index_t* cstr_index = NULL;

	OPJ_INT32 num_images, imageno;
	img_fol_t img_fol;
	dircnt_t *dirptr = NULL;

#ifdef MSD
	OPJ_BOOL l_go_on = OPJ_TRUE;
	OPJ_UINT32 l_max_data_size = 1000;
	OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000);
#endif

	/* Set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* Initialize img_fol */
	memset(&img_fol,0,sizeof(img_fol_t));

	/* Parse input and get user encoding parameters */
	if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {
		return EXIT_FAILURE;
	}

	/* Initialize reading of directory */
	if(img_fol.set_imgdir==1){	
		int it_image;
		num_images=get_num_images(img_fol.imgdirpath);

		dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
		if(dirptr){
			dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));	/* Stores at max 10 image file names*/
			dirptr->filename = (char**) malloc(num_images*sizeof(char*));

			if(!dirptr->filename_buf){
				return EXIT_FAILURE;
			}

			for(it_image=0;it_image<num_images;it_image++){
				dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
			}
		}
		if(load_images(dirptr,img_fol.imgdirpath)==1){
			return EXIT_FAILURE;
		}

		if (num_images==0){
			fprintf(stdout,"Folder is empty\n");
			return EXIT_FAILURE;
		}
	}else{
		num_images=1;
	}

	/* Try to open for writing the output file if necessary */
	if (parameters.outfile[0] != 0){
		fout = fopen(parameters.outfile,"w");
		if (!fout){
			fprintf(stderr, "ERROR -> failed to open %s for writing\n", parameters.outfile);
			return EXIT_FAILURE;
		}
	}
	else
		fout = stdout;

	/* Read the header of each image one by one */
	for(imageno = 0; imageno < num_images ; imageno++){

		fprintf(stderr,"\n");

		if(img_fol.set_imgdir==1){
			if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
				fprintf(stderr,"skipping file...\n");
				continue;
			}
		}

		/* Read the input file and put it in memory */
		/* ---------------------------------------- */

		l_stream = opj_stream_create_default_file_stream_v3(parameters.infile,1);
		if (!l_stream){
			fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n",parameters.infile);
			return EXIT_FAILURE;
		}

		/* Read the JPEG2000 stream */
		/* ------------------------ */

		switch(parameters.decod_format) {
			case J2K_CFMT:	/* JPEG-2000 codestream */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_J2K);
				break;
			}
			case JP2_CFMT:	/* JPEG 2000 compressed image data */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JP2);
				break;
			}
			case JPT_CFMT:	/* JPEG 2000, JPIP */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JPT);
				break;
			}
			default:
				fprintf(stderr, "skipping file..\n");
				opj_stream_destroy_v3(l_stream);
				continue;
		}

		/* catch events using our callbacks and give a local context */		
		opj_set_info_handler(l_codec, info_callback,00);
		opj_set_warning_handler(l_codec, warning_callback,00);
		opj_set_error_handler(l_codec, error_callback,00);

		/* Setup the decoder decoding parameters using user parameters */
		if ( !opj_setup_decoder(l_codec, &parameters) ){
			fprintf(stderr, "ERROR -> opj_dump: failed to setup the decoder\n");
			opj_stream_destroy_v3(l_stream);
			opj_destroy_codec(l_codec);
			fclose(fout);
			return EXIT_FAILURE;
		}

		/* Read the main header of the codestream and if necessary the JP2 boxes*/
		if(! opj_read_header(l_stream, l_codec, &image)){
			fprintf(stderr, "ERROR -> opj_dump: failed to read the header\n");
			opj_stream_destroy_v3(l_stream);
			opj_destroy_codec(l_codec);
			opj_image_destroy(image);
			fclose(fout);
			return EXIT_FAILURE;
		}

		opj_dump_codec(l_codec, OPJ_IMG_INFO | OPJ_J2K_MH_INFO | OPJ_J2K_MH_IND, fout );

		cstr_info = opj_get_cstr_info(l_codec);

		cstr_index = opj_get_cstr_index(l_codec);

		/* close the byte stream */
		opj_stream_destroy_v3(l_stream);

		/* free remaining structures */
		if (l_codec) {
			opj_destroy_codec(l_codec);
		}

		/* destroy the image header */
		opj_image_destroy(image);

		/* destroy the codestream index */
		opj_destroy_cstr_index(&cstr_index);

		/* destroy the codestream info */
		opj_destroy_cstr_info(&cstr_info);

	}

	/* Close the output file */
	fclose(fout);

  return EXIT_SUCCESS;
}
Exemplo n.º 3
0
int main(int sys_argc, char ** sys_argv)
{
	int result;
	char end_of_files = FALSE;
	long parr;
	char *fname;
	int libpar = 0;
	mpg123_pars *mp;
#if !defined(WIN32) && !defined(GENERIC)
	struct timeval start_time;
#endif
	aux_out = stdout; /* Need to initialize here because stdout is not a constant?! */
#if defined (WANT_WIN32_UNICODE)
	if(win32_cmdline_utf8(&argc, &argv) != 0)
	{
		error("Cannot convert command line to UTF8!");
		safe_exit(76);
	}
#else
	argv = sys_argv;
	argc = sys_argc;
#endif
#if defined (WANT_WIN32_SOCKETS)
	win32_net_init();
#endif

	/* Extract binary and path, take stuff before/after last / or \ . */
	if((prgName = strrchr(argv[0], '/')) || (prgName = strrchr(argv[0], '\\')))
	{
		/* There is some explicit path. */
		prgName[0] = 0; /* End byte for path. */
		prgName++;
		binpath = argv[0];
	}
	else
	{
		prgName = argv[0]; /* No path separators there. */
		binpath = NULL; /* No path at all. */
	}

	/* Need to initialize mpg123 lib here for default parameter values. */

	result = mpg123_init();
	if(result != MPG123_OK)
	{
		error1("Cannot initialize mpg123 library: %s", mpg123_plain_strerror(result));
		safe_exit(77);
	}
	cleanup_mpg123 = TRUE;

	mp = mpg123_new_pars(&result); /* This may get leaked on premature exit(), which is mainly a cosmetic issue... */
	if(mp == NULL)
	{
		error1("Crap! Cannot get mpg123 parameters: %s", mpg123_plain_strerror(result));
		safe_exit(78);
	}

	/* get default values */
	mpg123_getpar(mp, MPG123_DOWN_SAMPLE, &parr, NULL);
	param.down_sample = (int) parr;
	mpg123_getpar(mp, MPG123_RVA, &param.rva, NULL);
	mpg123_getpar(mp, MPG123_DOWNSPEED, &param.halfspeed, NULL);
	mpg123_getpar(mp, MPG123_UPSPEED, &param.doublespeed, NULL);
	mpg123_getpar(mp, MPG123_OUTSCALE, &param.outscale, NULL);
	mpg123_getpar(mp, MPG123_FLAGS, &parr, NULL);
	mpg123_getpar(mp, MPG123_INDEX_SIZE, &param.index_size, NULL);
	param.flags = (int) parr;
	param.flags |= MPG123_SEEKBUFFER; /* Default on, for HTTP streams. */
	mpg123_getpar(mp, MPG123_RESYNC_LIMIT, &param.resync_limit, NULL);
	mpg123_getpar(mp, MPG123_PREFRAMES, &param.preframes, NULL);

#ifdef OS2
        _wildcard(&argc,&argv);
#endif

	while ((result = getlopt(argc, argv, opts)))
	switch (result) {
		case GLO_UNKNOWN:
			fprintf (stderr, "%s: Unknown option \"%s\".\n", 
				prgName, loptarg);
			usage(1);
		case GLO_NOARG:
			fprintf (stderr, "%s: Missing argument for option \"%s\".\n",
				prgName, loptarg);
			usage(1);
	}
	/* Do this _after_ parameter parsing. */
	check_locale(); /* Check/set locale; store if it uses UTF-8. */

	if(param.list_cpu)
	{
		const char **all_dec = mpg123_decoders();
		printf("Builtin decoders:");
		while(*all_dec != NULL){ printf(" %s", *all_dec); ++all_dec; }
		printf("\n");
		mpg123_delete_pars(mp);
		return 0;
	}
	if(param.test_cpu)
	{
		const char **all_dec = mpg123_supported_decoders();
		printf("Supported decoders:");
		while(*all_dec != NULL){ printf(" %s", *all_dec); ++all_dec; }
		printf("\n");
		mpg123_delete_pars(mp);
		return 0;
	}
	if(param.gain != -1)
	{
	    warning("The parameter -g is deprecated and may be removed in the future.");
	}

	if (loptind >= argc && !param.listname && !param.remote) usage(1);
	/* Init audio as early as possible.
	   If there is the buffer process to be spawned, it shouldn't carry the mpg123_handle with it. */
	bufferblock = mpg123_safe_buffer(); /* Can call that before mpg123_init(), it's stateless. */
	if(init_output(&ao) < 0)
	{
		error("Failed to initialize output, goodbye.");
		mpg123_delete_pars(mp);
		return 99; /* It's safe here... nothing nasty happened yet. */
	}
	have_output = TRUE;

	/* ========================================================================================================= */
	/* Enterning the leaking zone... we start messing with stuff here that should be taken care of when leaving. */
	/* Don't just exit() or return out...                                                                        */
	/* ========================================================================================================= */

	httpdata_init(&htd);

#if !defined(WIN32) && !defined(GENERIC)
	if (param.remote)
	{
		param.verbose = 0;
		param.quiet = 1;
		param.flags |= MPG123_QUIET;
	}
#endif

	/* Set the frame parameters from command line options */
	if(param.quiet) param.flags |= MPG123_QUIET;

#ifdef OPT_3DNOW
	if(dnow != 0) param.cpu = (dnow == SET_3DNOW) ? "3dnow" : "i586";
#endif
	if(param.cpu != NULL && (!strcmp(param.cpu, "auto") || !strcmp(param.cpu, ""))) param.cpu = NULL;
	if(!(  MPG123_OK == (result = mpg123_par(mp, MPG123_VERBOSE, param.verbose, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_FLAGS, param.flags, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_DOWN_SAMPLE, param.down_sample, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_RVA, param.rva, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_FORCE_RATE, param.force_rate, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_DOWNSPEED, param.halfspeed, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_UPSPEED, param.doublespeed, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_ICY_INTERVAL, 0, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_RESYNC_LIMIT, param.resync_limit, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_TIMEOUT, param.timeout, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_OUTSCALE, param.outscale, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_PREFRAMES, param.preframes, 0))
			))
	{
		error2("Cannot set library parameter %i: %s", libpar, mpg123_plain_strerror(result));
		safe_exit(45);
	}
	if (!(param.listentry < 0) && !param.quiet) print_title(stderr); /* do not pollute stdout! */

	{
		long default_index;
		mpg123_getpar(mp, MPG123_INDEX_SIZE, &default_index, NULL);
		if( param.index_size != default_index && (result = mpg123_par(mp, MPG123_INDEX_SIZE, param.index_size, 0.)) != MPG123_OK )
		error1("Setting of frame index size failed: %s", mpg123_plain_strerror(result));
	}

	if(param.force_rate && param.down_sample)
	{
		error("Down sampling and fixed rate options not allowed together!");
		safe_exit(1);
	}

	/* Now actually get an mpg123_handle. */
	mh = mpg123_parnew(mp, param.cpu, &result);
	if(mh == NULL)
	{
		error1("Crap! Cannot get a mpg123 handle: %s", mpg123_plain_strerror(result));
		safe_exit(77);
	}
	mpg123_delete_pars(mp); /* Don't need the parameters anymore ,they're in the handle now. */

	/* Prepare stream dumping, possibly replacing mpg123 reader. */
	if(dump_open(mh) != 0) safe_exit(78);

	/* Now either check caps myself or query buffer for that. */
	audio_capabilities(ao, mh);

	load_equalizer(mh);

#ifdef HAVE_SETPRIORITY
	if(param.aggressive) { /* tst */
		int mypid = getpid();
		setpriority(PRIO_PROCESS,mypid,-20);
	}
#endif

#if defined (HAVE_SCHED_SETSCHEDULER) && !defined (__CYGWIN__) && !defined (HAVE_WINDOWS_H)
/* Cygwin --realtime seems to fail when accessing network, using win32 set priority instead */
/* MinGW may have pthread installed, we prefer win32API */
	if (param.realtime) {  /* Get real-time priority */
	  struct sched_param sp;
	  fprintf(stderr,"Getting real-time priority\n");
	  memset(&sp, 0, sizeof(struct sched_param));
	  sp.sched_priority = sched_get_priority_min(SCHED_FIFO);
	  if (sched_setscheduler(0, SCHED_RR, &sp) == -1)
	    fprintf(stderr,"Can't get real-time priority\n");
	}
#endif

#ifdef HAVE_WINDOWS_H
	/* argument "3" is equivalent to realtime priority class */
	win32_set_priority( param.realtime ? 3 : param.w32_priority);
#endif

	if(!param.remote) prepare_playlist(argc, argv);

#if !defined(WIN32) && !defined(GENERIC)
	/* Remote mode is special... but normal console and terminal-controlled operation needs to catch the SIGINT.
	   For one it serves for track skip when not in terminal control mode.
	   The more important use being a graceful exit, including telling the buffer process what's going on. */
	if(!param.remote) catchsignal (SIGINT, catch_interrupt);
#endif

	if(param.remote) {
		int ret;
		ret = control_generic(mh);
		safe_exit(ret);
	}
#ifdef HAVE_TERMIOS
		debug1("param.term_ctrl: %i", param.term_ctrl);
		if(param.term_ctrl)
			term_init();
#endif
	if(APPFLAG(MPG123APP_CONTINUE)) frames_left = param.frame_number;

	while ((fname = get_next_file()))
	{
		char *dirname, *filename;
		int newdir;
		/* skip_tracks includes the previous one. */
		if(skip_tracks) --skip_tracks;
		if(skip_tracks)
		{
			debug("Skipping this track.");
			continue;
		}
		if(param.delay > 0)
		{
			/* One should enable terminal control during that sleeping phase! */
			if(param.verbose > 2) fprintf(stderr, "Note: pausing %i seconds before next track.\n", param.delay);
			output_pause(ao);
#ifdef WIN32
			Sleep(param.delay*1000);
#else
			sleep(param.delay);
#endif
			output_unpause(ao);
		}
		if(!APPFLAG(MPG123APP_CONTINUE)) frames_left = param.frame_number;

		debug1("Going to play %s", strcmp(fname, "-") ? fname : "standard input");

		if(intflag || !open_track(fname))
		{
#ifdef HAVE_TERMIOS
			/* We need the opportunity to cancel in case of --loop -1 . */
			if(param.term_ctrl) term_control(mh, ao);
#endif
			/* No wait for a second interrupt before we started playing. */
			if(intflag) break;

			continue;
		}

		if(!param.quiet) fprintf(stderr, "\n");
		if(param.index)
		{
			if(param.verbose) fprintf(stderr, "indexing...\r");
			mpg123_scan(mh);
		}
		/*
			Only trigger a seek if we do not want to start with the first frame.
			Rationale: Because of libmpg123 sample accuracy, this could cause an unnecessary backwards seek, that even may fail on non-seekable streams.
			For start frame of 0, we are already at the correct position!
		*/
		framenum = 0;
		if(param.start_frame > 0)
		framenum = mpg123_seek_frame(mh, param.start_frame, SEEK_SET);

		if(APPFLAG(MPG123APP_CONTINUE)) param.start_frame = 0;

		if(framenum < 0)
		{
			error1("Initial seek failed: %s", mpg123_strerror(mh));
			if(mpg123_errcode(mh) == MPG123_BAD_OUTFORMAT)
			{
				fprintf(stderr, "%s", "So, you have trouble getting an output format... this is the matrix of currently possible formats:\n");
				print_capabilities(ao, mh);
				fprintf(stderr, "%s", "Somehow the input data and your choices don't allow one of these.\n");
			}
			mpg123_close(mh);
			continue;
		}

		/* Prinout and xterm title need this, possibly independently. */
		newdir = split_dir_file(fname ? fname : "standard input", &dirname, &filename);

		if (!param.quiet)
		{
			if(newdir) fprintf(stderr, "Directory: %s\n", dirname);

#ifdef HAVE_TERMIOS
		/* Reminder about terminal usage. */
		if(param.term_ctrl) term_hint();
#endif


			fprintf(stderr, "Playing MPEG stream %lu of %lu: %s ...\n", (unsigned long)pl.pos, (unsigned long)pl.fill, filename);
			if(htd.icy_name.fill) fprintf(stderr, "ICY-NAME: %s\n", htd.icy_name.p);
			if(htd.icy_url.fill)  fprintf(stderr, "ICY-URL: %s\n",  htd.icy_url.p);
		}
#if !defined(GENERIC)
{
	const char *term_type;
	term_type = getenv("TERM");
	if(term_type && param.xterm_title)
	{
		if(!strncmp(term_type,"xterm",5) || !strncmp(term_type,"rxvt",4))
		fprintf(stderr, "\033]0;%s\007", filename);
		else if(!strncmp(term_type,"screen",6))
		fprintf(stderr, "\033k%s\033\\", filename);
		else if(!strncmp(term_type,"iris-ansi",9))
		fprintf(stderr, "\033P1.y %s\033\\\033P3.y%s\033\\", filename, filename);

		fflush(stderr); /* Paranoia: will the buffer buffer the escapes? */
	}
}
#endif

/* Rethink that SIGINT logic... */
#if !defined(WIN32) && !defined(GENERIC)
#ifdef HAVE_TERMIOS
		if(!param.term_ctrl)
#endif
			gettimeofday (&start_time, NULL);
#endif

		while(!intflag)
		{
			int meta;
			if(param.frame_number > -1)
			{
				debug1("frames left: %li", (long) frames_left);
				if(!frames_left)
				{
					if(APPFLAG(MPG123APP_CONTINUE)) end_of_files = TRUE;

					break;
				}
			}
			if(!play_frame()) break;
			if(!param.quiet)
			{
				meta = mpg123_meta_check(mh);
				if(meta & (MPG123_NEW_ID3|MPG123_NEW_ICY))
				{
					if(meta & MPG123_NEW_ID3) print_id3_tag(mh, param.long_id3, stderr);
					if(meta & MPG123_NEW_ICY) print_icy(mh, stderr);

					mpg123_meta_free(mh); /* Do not waste memory after delivering. */
				}
			}
			if(!fresh && param.verbose)
			{
#ifndef NOXFERMEM
				if (param.verbose > 1 || !(framenum & 0x7))
					print_stat(mh,0,xfermem_get_usedspace(buffermem)); 
#else
				if(param.verbose > 1 || !(framenum & 0x7))	print_stat(mh,0,0);
#endif
			}
#ifdef HAVE_TERMIOS
			if(!param.term_ctrl) continue;
			else term_control(mh, ao);
#endif
		}

	if(!param.smooth && param.usebuffer) buffer_drain();
	if(param.verbose) print_stat(mh,0,xfermem_get_usedspace(buffermem)); 

	if(!param.quiet)
	{
		double secs;
		long frank;
		fprintf(stderr, "\n");
		if(mpg123_getstate(mh, MPG123_FRANKENSTEIN, &frank, NULL) == MPG123_OK && frank)
		fprintf(stderr, "This was a Frankenstein track.\n");

		mpg123_position(mh, 0, 0, NULL, NULL, &secs, NULL);
		fprintf(stderr,"[%d:%02d] Decoding of %s finished.\n", (int)(secs / 60), ((int)secs) % 60, filename);
	}
	else if(param.verbose) fprintf(stderr, "\n");

	mpg123_close(mh);

	if (intflag)
	{
		if(!skip_or_die(&start_time)) break;

        intflag = FALSE;

#ifndef NOXFERMEM
        if(!param.smooth && param.usebuffer) buffer_resync();
#endif
	}

		if(end_of_files) break;
	} /* end of loop over input files */

	/* Ensure we played everything. */
	if(param.smooth && param.usebuffer)
	{
		buffer_drain();
		buffer_resync();
	}

	if(APPFLAG(MPG123APP_CONTINUE))
	{
		continue_msg("CONTINUE");
	}

	/* Free up memory used by playlist */    
	if(!param.remote) free_playlist();

	safe_exit(0); /* That closes output and restores terminal, too. */
	return 0;
}
Exemplo n.º 4
0
Arquivo: build.c Projeto: LinuxCSA/CSA
/*
 * =========================== Build_file() ============================
 */
static	int
Build_file()
{
	int 	fd;		/* file desc */
	int	lastfile;	/* last fileindex opened sucessfully */

	Total_crecs = Total_frecs = 0;

	/*
	 *	Open first account file if it does not exist no problem.
	 *	UNLESS it is pacct then exit.....
	 */
	if (db_flag > 0) {
		Ndebug("Build_file(1): called.\n");
	}
	/*	This 'for' loop is necessary for the case where the file with
	 *	suffix 0 cannot be opened, i.e., doesn't exist.  The 'for'
	 *	loop makes sure that we do try to open the file with suffix 1.
	 */
	Last_upTime = upind = 0;
	for(lastfile = File_Index = 0; File_Index < 2; File_Index++) {
		while((fd = get_next_file(pacct, File_Index, F_OPEN)) >= 0) {
			/*	Save info about this file. */
			lastfile = File_Index;
			mark = File_index;
			Build_segment(fd);

			/*	Move to next file if it exists. */
			get_next_file(pacct, File_Index, F_CLOSED);
			File_Index++;
		} 
	} 

	/*  Did we get any of these files open? */
	if (lastfile == 0) {
		char		string[40];
		if (db_flag > 0) {
			Ndebug("Build_file(1): Could not open first "
				"'%s' file.\n", pacct);
		}

		sprintf(string, "%s%d", pacct, lastfile+1);
		acct_err(ACCT_ABORT,
		       _("Could not open the first pacct file '%s'."),
			string);
	}

	/*  Did we get to the last uptime?  */
	if (uptime[upind+1].up_stop != 0) {
		if (db_flag > 0) {
			Ndebug("Build_file(1): Ran out of %s files before "
				"out of uptimes(%d).\n", pacct, upind);
		}
	}

	if (db_flag > 0) {
		Ndebug("Build_file(1): Total file records this pass = %d.\n",
			Total_frecs);
	}

	return(0);
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
	opj_dparameters_t parameters;	/* decompression parameters */
	img_fol_t img_fol;
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *image = NULL;
	FILE *fsrc = NULL;
	unsigned char *src = NULL;
	int file_length;
	int num_images;
	int i,imageno;
	dircnt_t *dirptr = NULL;
	opj_dinfo_t* dinfo = NULL;	/* handle to a decompressor */
	opj_cio_t *cio = NULL;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */
	char indexfilename[OPJ_PATH_LEN];	/* index file name */

	/* configure the event callbacks (not required) */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = error_callback;
	event_mgr.warning_handler = warning_callback;
	event_mgr.info_handler = info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* Initialize indexfilename and img_fol */
	*indexfilename = 0;
	memset(&img_fol,0,sizeof(img_fol_t));

	/* parse input and get user encoding parameters */
	if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
		return 1;
	}

	/* Initialize reading of directory */
	if(img_fol.set_imgdir==1){	
		num_images=get_num_images(img_fol.imgdirpath);

		dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
		if(dirptr){
			dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));	// Stores at max 10 image file names
			dirptr->filename = (char**) malloc(num_images*sizeof(char*));

			if(!dirptr->filename_buf){
				return 1;
			}
			for(i=0;i<num_images;i++){
				dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
			}
		}
		if(load_images(dirptr,img_fol.imgdirpath)==1){
			return 1;
		}
		if (num_images==0){
			fprintf(stdout,"Folder is empty\n");
			return 1;
		}
	}else{
		num_images=1;
	}

	/*Encoding image one by one*/
	for(imageno = 0; imageno < num_images ; imageno++)
  {
		image = NULL;
		fprintf(stderr,"\n");

		if(img_fol.set_imgdir==1){
			if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
				fprintf(stderr,"skipping file...\n");
				continue;
			}
		}

		/* read the input file and put it in memory */
		/* ---------------------------------------- */
		fsrc = fopen(parameters.infile, "rb");
		if (!fsrc) {
			fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
			return 1;
		}
		fseek(fsrc, 0, SEEK_END);
		file_length = ftell(fsrc);
		fseek(fsrc, 0, SEEK_SET);
		src = (unsigned char *) malloc(file_length);
		fread(src, 1, file_length, fsrc);
		fclose(fsrc);

		/* decode the code-stream */
		/* ---------------------- */

		switch(parameters.decod_format) {
		case J2K_CFMT:
		{
			/* JPEG-2000 codestream */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_J2K);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				// If need to extract codestream information
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				return 1;
			}
			/* dump image */
      j2k_dump_image(stdout, image);

			/* dump cp */
      j2k_dump_cp(stdout, image, ((opj_j2k_t*)dinfo->j2k_handle)->cp);

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				char bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JP2_CFMT:
		{
			/* JPEG 2000 compressed image data */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JP2);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using the current image and user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				// If need to extract codestream information
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);			
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				return 1;
			}
			/* dump image */
      j2k_dump_image(stdout, image);

			/* dump cp */
      j2k_dump_cp(stdout, image, ((opj_jp2_t*)dinfo->jp2_handle)->j2k->cp);

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				char bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JPT_CFMT:
		{
			/* JPEG 2000, JPIP */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JPT);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				// If need to extract codestream information
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				char bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		default:
			fprintf(stderr, "skipping file..\n");
			continue;
	}

		/* free the memory containing the code-stream */
		free(src);
		src = NULL;

		/* free remaining structures */
		if(dinfo) {
			opj_destroy_decompress(dinfo);
		}
		/* free codestream information structure */
		if (*indexfilename)	
			opj_destroy_cstr_info(&cstr_info);
		/* free image data structure */
		opj_image_destroy(image);

	}

  return EXIT_SUCCESS;
}
Exemplo n.º 6
0
int main(int argc, char **argv) {
	opj_dparameters_t parameters;	/* decompression parameters */
	img_fol_t img_fol;
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *image = NULL;
	FILE *fsrc = NULL;
	unsigned char *src = NULL;
	int file_length;
	int num_images;
	int i,imageno;
	dircnt_t *dirptr;
	opj_dinfo_t* dinfo = NULL;	/* handle to a decompressor */
	opj_cio_t *cio = NULL;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */
	char indexfilename[OPJ_PATH_LEN];	/* index file name */

	/* configure the event callbacks (not required) */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = error_callback;
	event_mgr.warning_handler = warning_callback;
	event_mgr.info_handler = info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* Initialize indexfilename and img_fol */
	*indexfilename = 0;
	memset(&img_fol,0,sizeof(img_fol_t));

	/* parse input and get user encoding parameters */
	if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
		return 1;
	}

	/* Initialize reading of directory */
	if(img_fol.set_imgdir==1){	
		num_images=get_num_images(img_fol.imgdirpath);

		dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
		if(dirptr){
			dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));	// Stores at max 10 image file names
			dirptr->filename = (char**) malloc(num_images*sizeof(char*));

			if(!dirptr->filename_buf){
				return 1;
			}
			for(i=0;i<num_images;i++){
				dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
			}
		}
		if(load_images(dirptr,img_fol.imgdirpath)==1){
			return 1;
		}
		if (num_images==0){
			fprintf(stdout,"Folder is empty\n");
			return 1;
		}
	}else{
		num_images=1;
	}

	/*Encoding image one by one*/
	for(imageno = 0; imageno < num_images ; imageno++)	{
		image = NULL;
		fprintf(stderr,"\n");

		if(img_fol.set_imgdir==1){
			if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
				fprintf(stderr,"skipping file...\n");
				continue;
			}
		}

		/* read the input file and put it in memory */
		/* ---------------------------------------- */
		fsrc = fopen(parameters.infile, "rb");
		if (!fsrc) {
			fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
			return 1;
		}
		fseek(fsrc, 0, SEEK_END);
		file_length = ftell(fsrc);
		fseek(fsrc, 0, SEEK_SET);
		src = (unsigned char *) malloc(file_length);
		fread(src, 1, file_length, fsrc);
		fclose(fsrc);

		/* decode the code-stream */
		/* ---------------------- */

		switch(parameters.decod_format) {
		case J2K_CFMT:
		{
			/* JPEG-2000 codestream */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_J2K);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				// If need to extract codestream information
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				char bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JP2_CFMT:
		{
			/* JPEG 2000 compressed image data */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JP2);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using the current image and user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				// If need to extract codestream information
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);			
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				char bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JPT_CFMT:
		{
			/* JPEG 2000, JPIP */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JPT);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				// If need to extract codestream information
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				char bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		default:
			fprintf(stderr, "skipping file..\n");
			continue;
	}

		/* free the memory containing the code-stream */
		free(src);
		src = NULL;

	if(image->color_space == CLRSPC_SYCC)
   {
	color_sycc_to_rgb(image);
   }

	if(image->icc_profile_buf)
   {
#if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2)
	color_apply_icc_profile(image);
#endif

	free(image->icc_profile_buf);
	image->icc_profile_buf = NULL; image->icc_profile_len = 0;
   }

		/* create output image */
		/* ------------------- */
		switch (parameters.cod_format) {
		case PXM_DFMT:			/* PNM PGM PPM */
			if (imagetopnm(image, parameters.outfile)) {
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case PGX_DFMT:			/* PGX */
			if(imagetopgx(image, parameters.outfile)){
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case BMP_DFMT:			/* BMP */
			if(imagetobmp(image, parameters.outfile)){
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;
#ifdef HAVE_LIBTIFF
		case TIF_DFMT:			/* TIFF */
			if(imagetotif(image, parameters.outfile)){
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;
#endif /* HAVE_LIBTIFF */
		case RAW_DFMT:			/* RAW */
			if(imagetoraw(image, parameters.outfile)){
				fprintf(stdout,"Error generating raw file. Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
			}
			break;

		case TGA_DFMT:			/* TGA */
			if(imagetotga(image, parameters.outfile)){
				fprintf(stdout,"Error generating tga file. Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
			}
			break;
#ifdef HAVE_LIBPNG
		case PNG_DFMT:			/* PNG */
			if(imagetopng(image, parameters.outfile)){
				fprintf(stdout,"Error generating png file. Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
			}
			break;
#endif /* HAVE_LIBPNG */
/* Can happen if output file is TIFF or PNG
 * and HAVE_LIBTIF or HAVE_LIBPNG is undefined
*/
			default:
				fprintf(stderr,"Outfile %s not generated\n",parameters.outfile);
		}

		/* free remaining structures */
		if(dinfo) {
			opj_destroy_decompress(dinfo);
		}
		/* free codestream information structure */
		if (*indexfilename)	
			opj_destroy_cstr_info(&cstr_info);
		/* free image data structure */
		opj_image_destroy(image);

	}
	return 0;
}
Exemplo n.º 7
0
Glib::ustring FileManager::get_next_file()
	{
	if( !initialised )
		return GT( "No file to load." );

	std::list<Glib::ustring>::iterator end = filenames.end();
	std::list<Glib::ustring>::iterator begin = filenames.begin();

	// no next/prev operations carried out yet, load the second image
	if( !last_op_next && !last_op_previous && file_iterator == begin )
		{
		last_op_next = true;
		last_op_previous = false;
		file_iterator++;
		if( file_iterator == end ) // if we have only one file open, this will prevent segfault
			file_iterator = begin;
		return *file_iterator;
		}

	// we've hit the end() marker going forwards, end() is invalid so let's jump
	// back to the beginning
	if( last_op_next && file_iterator == end )
		{
		last_op_next = true;
		last_op_previous = false;
		file_iterator = begin;
		return *file_iterator;
		}

	// we're going backwards in the pictures and we reach the first pictures
	// the iterator is automatically set to end() by previous and if we now click
	// next we'd show the first image twice, so show the second one instead
	if( last_op_previous && file_iterator == end )
		{
		last_op_next = true;
		last_op_previous = false;
		file_iterator = begin;
		file_iterator++;
		return *file_iterator;
		}

	// we pass past the first picture going backwards to the last picture
	// if we increment now as below (else) we'll be at end(), get_next_file() will
	// be called again and we skip the first picture, to prevent that we'll
	// just show the first picture now
	if( last_op_previous && file_iterator != end )
		{
		last_op_next = true;
		last_op_previous = false;
		file_iterator++;
		if( file_iterator == end )
			{
			file_iterator = begin;
			return *file_iterator;
			}
		else
			return *file_iterator;
		}
		
	else
		{
		last_op_next = true;
		last_op_previous = false;
		file_iterator++;
		// safeguard against end() errors
		if( file_iterator == end )
			get_next_file(); // when we're at the end, recurse
		return *file_iterator;
		}

	}
Exemplo n.º 8
0
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
	opj_decompress_parameters parameters;			/* decompression parameters */
	opj_image_t* image = NULL;
	opj_stream_t *l_stream = NULL;				/* Stream */
	opj_codec_t* l_codec = NULL;				/* Handle to a decompressor */
	opj_codestream_index_t* cstr_index = NULL;

	OPJ_INT32 num_images, imageno;
	img_fol_t img_fol;
	dircnt_t *dirptr = NULL;
  int failed = 0;
  OPJ_FLOAT64 t, tCumulative = 0;
  OPJ_UINT32 numDecompressedImages = 0;

	/* set decoding parameters to default values */
	set_default_parameters(&parameters);

	/* Initialize img_fol */
	memset(&img_fol,0,sizeof(img_fol_t));

	/* parse input and get user encoding parameters */
	if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {
		destroy_parameters(&parameters);
		return EXIT_FAILURE;
	}

	/* Initialize reading of directory */
	if(img_fol.set_imgdir==1){	
		int it_image;
		num_images=get_num_images(img_fol.imgdirpath);

		dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
		if(dirptr){
			dirptr->filename_buf = (char*)malloc((size_t)num_images*OPJ_PATH_LEN*sizeof(char));	/* Stores at max 10 image file names*/
			dirptr->filename = (char**) malloc((size_t)num_images*sizeof(char*));

			if(!dirptr->filename_buf){
				destroy_parameters(&parameters);
				return EXIT_FAILURE;
			}
			for(it_image=0;it_image<num_images;it_image++){
				dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
			}
		}
		if(load_images(dirptr,img_fol.imgdirpath)==1){
			destroy_parameters(&parameters);
			return EXIT_FAILURE;
		}
		if (num_images==0){
			fprintf(stdout,"Folder is empty\n");
			destroy_parameters(&parameters);
			return EXIT_FAILURE;
		}
	}else{
		num_images=1;
	}

	/*Decoding image one by one*/
	for(imageno = 0; imageno < num_images ; imageno++)	{

		fprintf(stderr,"\n");

		if(img_fol.set_imgdir==1){
			if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
				fprintf(stderr,"skipping file...\n");
				destroy_parameters(&parameters);
				continue;
			}
		}

		/* read the input file and put it in memory */
		/* ---------------------------------------- */

		l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
		if (!l_stream){
			fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n", parameters.infile);
			destroy_parameters(&parameters);
			return EXIT_FAILURE;
		}

		/* decode the JPEG2000 stream */
		/* ---------------------- */

		switch(parameters.decod_format) {
			case J2K_CFMT:	/* JPEG-2000 codestream */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_J2K);
				break;
			}
			case JP2_CFMT:	/* JPEG 2000 compressed image data */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JP2);
				break;
			}
			case JPT_CFMT:	/* JPEG 2000, JPIP */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JPT);
				break;
			}
			default:
				fprintf(stderr, "skipping file..\n");
				destroy_parameters(&parameters);
				opj_stream_destroy(l_stream);
				continue;
		}

		/* catch events using our callbacks and give a local context */		
		opj_set_info_handler(l_codec, info_callback,00);
		opj_set_warning_handler(l_codec, warning_callback,00);
		opj_set_error_handler(l_codec, error_callback,00);

		t = opj_clock();

		/* Setup the decoder decoding parameters using user parameters */
		if ( !opj_setup_decoder(l_codec, &(parameters.core)) ){
			fprintf(stderr, "ERROR -> opj_decompress: failed to setup the decoder\n");
			destroy_parameters(&parameters);
			opj_stream_destroy(l_stream);
			opj_destroy_codec(l_codec);
			return EXIT_FAILURE;
		}


		/* Read the main header of the codestream and if necessary the JP2 boxes*/
		if(! opj_read_header(l_stream, l_codec, &image)){
			fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
			destroy_parameters(&parameters);
			opj_stream_destroy(l_stream);
			opj_destroy_codec(l_codec);
			opj_image_destroy(image);
			return EXIT_FAILURE;
		}

		if (!parameters.nb_tile_to_decode) {
			/* Optional if you want decode the entire image */
			if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
					(OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1, (OPJ_INT32)parameters.DA_y1)){
				fprintf(stderr,	"ERROR -> opj_decompress: failed to set the decoded area\n");
				destroy_parameters(&parameters);
				opj_stream_destroy(l_stream);
				opj_destroy_codec(l_codec);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}

			/* Get the decoded image */
			if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec,	l_stream))) {
				fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}
		}
		else {

			/* It is just here to illustrate how to use the resolution after set parameters */
			/*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}*/

			if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}
			fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
		}

		tCumulative += opj_clock() - t;
		numDecompressedImages++;

		/* Close the byte stream */
		opj_stream_destroy(l_stream);

		if( image->color_space != OPJ_CLRSPC_SYCC 
			&& image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
			&& image->comps[1].dx != 1 )
			image->color_space = OPJ_CLRSPC_SYCC;
		else if (image->numcomps <= 2)
			image->color_space = OPJ_CLRSPC_GRAY;

		if(image->color_space == OPJ_CLRSPC_SYCC){
			color_sycc_to_rgb(image);
		}
		else if((image->color_space == OPJ_CLRSPC_CMYK) && (parameters.cod_format != TIF_DFMT)){
			color_cmyk_to_rgb(image);
		}
		else if(image->color_space == OPJ_CLRSPC_EYCC){
			color_esycc_to_rgb(image);
		}
		
		if(image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
			if(image->icc_profile_len)
			 color_apply_icc_profile(image);
			else
			 color_cielab_to_rgb(image);
#endif
			free(image->icc_profile_buf);
			image->icc_profile_buf = NULL; image->icc_profile_len = 0;
		}
		
		/* Force output precision */
		/* ---------------------- */
		if (parameters.precision != NULL)
		{
			OPJ_UINT32 compno;
			for (compno = 0; compno < image->numcomps; ++compno)
			{
				OPJ_UINT32 precno = compno;
				OPJ_UINT32 prec;
				
				if (precno >= parameters.nb_precision) {
					precno = parameters.nb_precision - 1U;
				}
				
				prec = parameters.precision[precno].prec;
				if (prec == 0) {
					prec = image->comps[compno].prec;
				}
				
				switch (parameters.precision[precno].mode) {
					case OPJ_PREC_MODE_CLIP:
						clip_component(&(image->comps[compno]), prec);
						break;
					case OPJ_PREC_MODE_SCALE:
						scale_component(&(image->comps[compno]), prec);
						break;
					default:
						break;
				}
				
			}
		}
		
		/* Upsample components */
		/* ------------------- */
		if (parameters.upsample)
		{
			image = upsample_image_components(image);
			if (image == NULL) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to upsample image components!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				return EXIT_FAILURE;
			}
		}
		
		/* Force RGB output */
		/* ---------------- */
		if (parameters.force_rgb)
		{
			switch (image->color_space) {
				case OPJ_CLRSPC_SRGB:
					break;
				case OPJ_CLRSPC_GRAY:
					image = convert_gray_to_rgb(image);
					break;
				default:
					fprintf(stderr, "ERROR -> opj_decompress: don't know how to convert image to RGB colorspace!\n");
					opj_image_destroy(image);
					image = NULL;
					break;
			}
			if (image == NULL) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to convert to RGB image!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				return EXIT_FAILURE;
			}
		}

		/* create output image */
		/* ------------------- */
		switch (parameters.cod_format) {
		case PXM_DFMT:			/* PNM PGM PPM */
			if (imagetopnm(image, parameters.outfile, parameters.split_pnm)) {
                fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case PGX_DFMT:			/* PGX */
			if(imagetopgx(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case BMP_DFMT:			/* BMP */
			if(imagetobmp(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;
#ifdef OPJ_HAVE_LIBTIFF
		case TIF_DFMT:			/* TIFF */
			if(imagetotif(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;
#endif /* OPJ_HAVE_LIBTIFF */
		case RAW_DFMT:			/* RAW */
			if(imagetoraw(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Error generating raw file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case RAWL_DFMT:			/* RAWL */
			if(imagetorawl(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Error generating rawl file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case TGA_DFMT:			/* TGA */
			if(imagetotga(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Error generating tga file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;
#ifdef OPJ_HAVE_LIBPNG
		case PNG_DFMT:			/* PNG */
			if(imagetopng(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Error generating png file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;
#endif /* OPJ_HAVE_LIBPNG */
/* Can happen if output file is TIFF or PNG
 * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
*/
			default:
                fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
        failed = 1;
		}

		/* free remaining structures */
		if (l_codec) {
			opj_destroy_codec(l_codec);
		}


		/* free image data structure */
		opj_image_destroy(image);

		/* destroy the codestream index */
		opj_destroy_cstr_index(&cstr_index);

		if(failed) (void)remove(parameters.outfile); /* ignore return value */
	}
	destroy_parameters(&parameters);
	if (numDecompressedImages) {
		fprintf(stdout, "decode time: %d ms\n", (int)( (tCumulative * 1000.0) / (OPJ_FLOAT64)numDecompressedImages));
	}
	return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemplo n.º 9
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);
}