Example #1
0
PRIVATE	LONG	defer_function(PIC_PARM *p, RESPONSE res)
{
	LONG	len;

	if (res == RES_GET_NEED_DATA)
		defer_status = read_file(p);
	else if (res == RES_PUT_NEED_SPACE)
	{
		/* need to empty put buffer */
		if(num_loops == 1)
			defer_status = copy_to_file(p);
		else
			defer_status = ERR_NOT_ENOUGH_BUFF_SPACE;
	}
    else if (res == RES_POKE)
    {
      /* write out remainder of put buffer, if any -- there won't
					be a poke until after pack has output everything.
					flushing here saves us having to remember the current
					file position so we can seek back for the final write */
			if ( p->Put.Rear > p->Put.Front )
			{
				len = p->Put.Rear - p->Put.Front;
				if(fwrite(p->Put.Front,sizeof(BYTE),len,des_file) != len)
					return(ERR_BAD_WRITE);
				p->Put.Front = p->Put.Rear;     /* it's empty now */
			}
			else if ( p->Put.Rear < p->Put.Front )
				{
				len = p->Put.End - p->Put.Front;
				if(fwrite(p->Put.Front,sizeof(BYTE),len,des_file) != len)
					return(ERR_BAD_WRITE);
				len = p->Put.Rear - p->Put.Start;
				if(fwrite(p->Put.Start,sizeof(BYTE),len,des_file) != len)
					return(ERR_BAD_WRITE);
				p->Put.Front = p->Put.Rear;     /* it's empty now */
				}
			/* else Rear == Front and there's nothing left to write */
			if(fseek(des_file, p->SeekInfo, SEEK_SET) != 0)
				return(ERR_BAD_SEEK);
			len = p->Put.RearEnd - p->Put.FrontEnd;
			if(fwrite(p->Put.FrontEnd,sizeof(BYTE),len,des_file) != len)
				return(ERR_BAD_WRITE);
		}
	else if (res == RES_PUT_DATA_YIELD)
	{
		if(num_loops == 1)
			defer_status = copy_to_file(p);
	}
	else if (res == RES_YIELD)
	{
		;
	}
	else
		defer_status = ERR_UNKNOWN_RESPONSE;
	if(defer_status)
		p->Status = defer_status; /* optional, just a place for App to record errors also if he chooses */
	return(defer_status);
}
Example #2
0
static int restore(int argc, char** argv) {
    const char* filename;
    int fd, tarFd;

    if (argc != 2) return usage();

    filename = argv[1];
    tarFd = adb_open(filename, O_RDONLY);
    if (tarFd < 0) {
        fprintf(stderr, "adb: unable to open file %s\n", filename);
        return -1;
    }

    fd = adb_connect("restore:");
    if (fd < 0) {
        fprintf(stderr, "adb: unable to connect for backup\n");
        adb_close(tarFd);
        return -1;
    }

    printf("Now unlock your device and confirm the restore operation.\n");
    copy_to_file(tarFd, fd);

    adb_close(fd);
    adb_close(tarFd);
    return 0;
}
Example #3
0
static int backup(int argc, char** argv) {
    char buf[4096];
    char default_name[32];
    const char* filename = strcpy(default_name, "./backup.ab");
    int fd, outFd;
    int i, j;

    /* find, extract, and use any -f argument */
    for (i = 1; i < argc; i++) {
        if (!strcmp("-f", argv[i])) {
            if (i == argc-1) {
                fprintf(stderr, "adb: -f passed with no filename\n");
                return usage();
            }
            filename = argv[i+1];
            for (j = i+2; j <= argc; ) {
                argv[i++] = argv[j++];
            }
            argc -= 2;
            argv[argc] = NULL;
        }
    }

    /* bare "adb backup" or "adb backup -f filename" are not valid invocations */
    if (argc < 2) return usage();

    adb_unlink(filename);
    mkdirs((char *)filename);
    outFd = adb_creat(filename, 0640);
    if (outFd < 0) {
        fprintf(stderr, "adb: unable to open file %s\n", filename);
        return -1;
    }

    snprintf(buf, sizeof(buf), "backup");
    for (argc--, argv++; argc; argc--, argv++) {
        strncat(buf, ":", sizeof(buf) - strlen(buf) - 1);
        strncat(buf, argv[0], sizeof(buf) - strlen(buf) - 1);
    }

    D("backup. filename=%s buf=%s\n", filename, buf);
    fd = adb_connect(buf);
    if (fd < 0) {
        fprintf(stderr, "adb: unable to connect for backup\n");
        adb_close(outFd);
        return -1;
    }

    printf("Now unlock your device and confirm the backup operation.\n");
    copy_to_file(fd, outFd);

    adb_close(fd);
    adb_close(outFd);
    return 0;
}
Example #4
0
bool zmq::swap_t::store (zmq_msg_t *msg_)
{
    size_t msg_size = zmq_msg_size (msg_);

    //  Check buffer space availability.
    //  NOTE: We always keep one byte open.
    if (buffer_space () <= (int64_t) (sizeof msg_size + 1 + msg_size))
        return false;

    //  Don't store the ZMQ_MSG_SHARED flag.
    uint8_t msg_flags = msg_->flags & ~ZMQ_MSG_SHARED;

    //  Write message length, flags, and message body.
    copy_to_file (&msg_size, sizeof msg_size);
    copy_to_file (&msg_flags, sizeof msg_flags);
    copy_to_file (zmq_msg_data (msg_), msg_size);

    zmq_msg_close (msg_);

    return true;
}
Example #5
0
int main(int argc,char* argv[])
{
	if(argc!=3)
	{
		printf("inout format must be error an example can be like this:./cp pathname1 pathname2");
	}
	else
	{
		copy_to_file(open_from_file(argv[1],open_to_file(argv[2])));
		printf("copy finished\n");
	}
	return 0;
}
Example #6
0
int main(int argc, char **argv)
{
	struct arguments args;
	char *homedir = getenv("HOME");
	char *channel = NULL;
	int lnb = -1, idx = -1;
	int vpid = -1, apid = -1, sid = -1;
	int pmtpid = 0;
	int pat_fd = -1, pmt_fd = -1;
	int audio_fd = 0, video_fd = 0;
	int dvr_fd, file_fd;
	struct dvb_v5_fe_parms *parms;
	const struct argp argp = {
		.options = options,
		.parser = parse_opt,
		.doc = "DVB zap utility",
		.args_doc = "<initial file>",
	};

	memset(&args, 0, sizeof(args));
	args.sat_number = -1;

	argp_parse(&argp, argc, argv, 0, &idx, &args);

	if (idx < argc)
		channel = argv[idx];

	if (!channel) {
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}

	if (args.input_format == FILE_UNKNOWN) {
		fprintf(stderr, "ERROR: Please specify a valid format\n");
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}

	if (args.lnb_name) {
		lnb = search_lnb(args.lnb_name);
		if (lnb < 0) {
			printf("Please select one of the LNBf's below:\n");
			print_all_lnb();
			exit(1);
		} else {
			printf("Using LNBf ");
			print_lnb(lnb);
		}
	}

	asprintf(&args.demux_dev,
		 "/dev/dvb/adapter%i/demux%i", args.adapter, args.demux);

	asprintf(&args.dvr_dev,
		 "/dev/dvb/adapter%i/dvr%i", args.adapter, args.demux);

	if (args.silent < 2)
		fprintf(stderr, "using demux '%s'\n", args.demux_dev);

	if (!args.confname) {
		if (!homedir)
			ERROR("$HOME not set");
		asprintf(&args.confname, "%s/.tzap/%i/%s",
			 homedir, args.adapter, CHANNEL_FILE);
		if (access(args.confname, R_OK))
			asprintf(&args.confname, "%s/.tzap/%s",
				homedir, CHANNEL_FILE);
	}
	printf("reading channels from file '%s'\n", args.confname);

	parms = dvb_fe_open(args.adapter, args.frontend, 0, 0);
	if (!parms)
		return -1;
	if (lnb)
		parms->lnb = get_lnb(lnb);
	if (args.sat_number > 0)
		parms->sat_number = args.sat_number % 3;
	parms->diseqc_wait = args.diseqc_wait;
	parms->freq_bpf = args.freq_bpf;

	if (parse(&args, parms, channel, &vpid, &apid, &sid))
		return -1;

	if (setup_frontend(&args, parms) < 0)
		return -1;

	if (args.frontend_only) {
		check_frontend(&args, parms);
		dvb_fe_close(parms);
		return 0;
	}

	if (args.rec_psi) {
		if (sid < 0) {
			fprintf(stderr, "Service id 0x%04x was not specified at the file\n",
				sid);
			return -1;
		}
		pmtpid = get_pmt_pid(args.demux_dev, sid);
		if (pmtpid <= 0) {
			fprintf(stderr, "couldn't find pmt-pid for sid %04x\n",
				sid);
			return -1;
		}

		if ((pat_fd = open(args.demux_dev, O_RDWR)) < 0) {
			perror("opening pat demux failed");
			return -1;
		}
		if (set_pesfilter(pat_fd, 0, DMX_PES_OTHER, args.dvr) < 0)
			return -1;

		if ((pmt_fd = open(args.demux_dev, O_RDWR)) < 0) {
			perror("opening pmt demux failed");
			return -1;
		}
		if (set_pesfilter(pmt_fd, pmtpid, DMX_PES_OTHER, args.dvr) < 0)
			return -1;
	}

	if (vpid >= 0) {
		if (args.silent < 2)
			fprintf(stderr, "video pid %d\n", vpid);
		if ((video_fd = open(args.demux_dev, O_RDWR)) < 0) {
			PERROR("failed opening '%s'", args.demux_dev);
			return -1;
		}
		if (set_pesfilter(video_fd, vpid, DMX_PES_VIDEO, args.dvr) < 0)
			return -1;
	}

	if (apid >= 0) {
		if (args.silent < 2)
			fprintf(stderr, "audio pid %d\n", apid);
		if ((audio_fd = open(args.demux_dev, O_RDWR)) < 0) {
			PERROR("failed opening '%s'", args.demux_dev);
			return -1;
		}

		if (set_pesfilter(audio_fd, apid, DMX_PES_AUDIO, args.dvr) < 0)
			return -1;
	}

	signal(SIGALRM, do_timeout);
	if (args.timeout > 0)
		alarm(args.timeout);

	if (args.record) {
		if (args.filename != NULL) {
			if (strcmp(args.filename, "-") != 0) {
				file_fd =
				    open(args.filename,
					 O_WRONLY | O_LARGEFILE | O_CREAT,
					 0644);
				if (file_fd < 0) {
					PERROR("open of '%s' failed",
					       args.filename);
					return -1;
				}
			} else {
				file_fd = 1;
			}
		} else {
			PERROR("Record mode but no filename!");
			return -1;
		}

		if ((dvr_fd = open(args.dvr_dev, O_RDONLY)) < 0) {
			PERROR("failed opening '%s'", args.dvr_dev);
			return -1;
		}
		if (args.silent < 2)
			print_frontend_stats(parms, args.human_readable);

		copy_to_file(dvr_fd, file_fd, args.timeout, args.silent);

		if (args.silent < 2)
			print_frontend_stats(parms, args.human_readable);
	} else {
		check_frontend(&args, parms);
	}

	close(pat_fd);
	close(pmt_fd);
	close(audio_fd);
	close(video_fd);
	dvb_fe_close(parms);

	return 0;
}
/*-------------------------------------------------------------------------
 * Function:    main
 *
 * Purpose:     HDF5 user block unjammer
 *
 * Return:      Success:    0
 *              Failure:    1
 *
 * Programmer:
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
int
main(int argc, const char *argv[])
{
    void               *edata;
    H5E_auto2_t         func;
    hid_t               ifile = -1;
    hid_t               plist = -1;
    off_t               fsize;
    hsize_t             usize;
    htri_t              testval;
    herr_t              status;
    int                 res;
    h5_stat_t           sbuf;

    h5tools_setprogname(PROGRAMNAME);
    h5tools_setstatus(EXIT_SUCCESS);

    /* Disable error reporting  */
    H5Eget_auto2(H5E_DEFAULT, &func, &edata);
    H5Eset_auto2(H5E_DEFAULT, NULL, NULL);

    /* Initialize h5tools lib  */
    h5tools_init();

    if(EXIT_FAILURE == parse_command_line(argc, argv))
        goto done;

    if (input_file == NULL) {
        /* no user block  */
        error_msg("missing arguemnt for HDF5 file input.\n");
        help_ref_msg(stderr);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }
  
    testval = H5Fis_hdf5(input_file);

    if (testval <= 0) {
        error_msg("Input HDF5 file \"%s\" is not HDF\n", input_file);
        help_ref_msg (stderr);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    ifile = H5Fopen(input_file, H5F_ACC_RDONLY , H5P_DEFAULT);

    if (ifile < 0) {
        error_msg("Can't open input HDF5 file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    plist = H5Fget_create_plist(ifile);
    if (plist < 0) {
        error_msg("Can't get file creation plist for file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    status = H5Pget_userblock(plist, & usize);
    if (status < 0) {
        error_msg("Can't get user block for file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    status = H5Pclose(plist);
    HDassert(status >= 0);
    status = H5Fclose(ifile);
    HDassert(status >= 0);

    if (usize == 0) {
  /* no user block to remove: message? */
        error_msg("\"%s\" has no user block: no change to file\n", input_file);
        h5tools_setstatus(EXIT_SUCCESS);
        goto done;
    }

    res = HDfstat(HDfileno(rawinstream), &sbuf);
    if(res < 0) {
        error_msg("Can't stat file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    fsize = sbuf.st_size;

    if (do_delete && (ub_file != NULL)) {
        error_msg("??\"%s\"\n", ub_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    if (output_file == NULL) {
            error_msg("unable to open output HDF5 file \"%s\"\n", input_file);
            h5tools_setstatus(EXIT_FAILURE);
            goto done;
    } 

    /* copy from 0 to 'usize - 1' into ufid  */
    if (!do_delete) {
        if(copy_to_file(rawinstream, rawoutstream, 0, (ssize_t) usize) < 0) {
            error_msg("unable to copy user block to output file \"%s\"\n", ub_file);
            h5tools_setstatus(EXIT_FAILURE);
            goto done;
        }
    }

    /* copy from usize to end of file into h5fid,
     * starting at end of user block if present */
   if(copy_to_file(rawinstream, rawdatastream, (ssize_t) usize, (ssize_t)(fsize - (ssize_t)usize)) < 0) {
        error_msg("unable to copy hdf5 data to output file \"%s\"\n", output_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }
 
done:
    if(input_file)
        HDfree(input_file);
		
    if(output_file)
        HDfree(output_file);
		
    if(ub_file) {
        HDfree(ub_file);
    }
	   
    h5tools_close();

    return h5tools_getstatus();
}
Example #8
0
/*  �����������������������������������������������������������������������ͼ */
PRIVATE LONG  expand (void)
{
	PIC_PARM  p;
	RESPONSE    res;
	LONG	len;
	LONG	ct;
	LONG	local_status;
	LONG	join_offset = 0;
	LONG	k, region_x,region_y,region_endx,region_endy, region_w,region_h;
	BYTE	*bptr;
	BYTE	*region_info_ptr;
	REGION_INFO	*region_info;

		/****/

	src_file = src_file_join = des_file = NULL;
	join_offset = 0;

	memset(&p, 0, sizeof(PIC_PARM));    /* important: set all default values 0 */
		/* ALSO important -- following must be set even for PegasusQuery */
		/* beginning version 13 */
	p.ParmSize = sizeof(PIC_PARM);
	p.ParmVer = CURRENT_PARMVER;
	p.ParmVerMinor = 1;
#if NOCO
	defer_status = 0;
	p.DeferFn = &defer_function;
#endif

	if(src_name_join != NULL)
		if(check1(!orient && !requant && !crop_flg,"Can't reorient, requant or crop while joining")) goto quit;


	/*  Open the JPEG file */
	src_file = fopen(src_name, "rb");
	if(check1(src_file != NULL, "Could not open %s", src_name)) goto quit;
	printf("Opened file %s.\n", src_name);


	/*  Open other JPEG file if joining */
	if(src_name_join != NULL)
	{
		src_file_join = fopen(src_name_join, "rb");
		if(check1(src_file_join != NULL, "Could not open %s", src_name_join)) goto quit;
		printf("Opened file %s.\n", src_name_join);
	}

	/*  Allocate GetBuff and place into it the information to be queried */
	if(num_loops > 1)
	{ /* allocate a full_size buffer  */
		get_buff_size = file_size(src_file) + 2;
		if(put_buff_size < get_buff_size << 1)
			put_buff_size = get_buff_size << 1;
	}
	if(src_name_join != NULL)
	{
		join_offset = file_size(src_file_join);
		get_buff_size += join_offset;
	}
	p.Get.Start = (BYTE *) malloc(get_buff_size);
	if(check1(p.Get.Start != NULL, "Out of memory for get buffer")) goto quit;
	p.Get.End = p.Get.Start + get_buff_size;

	/* read in first file if joining */
	if(src_name_join != NULL)
	{
		len = fread(p.Get.Start, sizeof(BYTE), get_buff_size, src_file_join);
		if(check1(ferror(src_file_join) == 0, "Error reading join file")) goto quit;
		if(check1(len == join_offset, "Error reading join file")) goto quit;
	}

	/*  read in header data, at least (of second file if joining) */
	len = fread(p.Get.Start + join_offset, sizeof(BYTE), get_buff_size - join_offset, src_file);
	if(check1(ferror(src_file) == 0, "Error reading input file")) goto quit;
	if(len < get_buff_size - join_offset)
		p.Get.QFlags |= Q_EOF;

	/*  setup output buff */
	p.Put.Start = (BYTE  *) malloc(put_buff_size);
	if(check1(p.Put.Start != NULL, "Out of memory for put buff")) goto quit;
	p.Put.End = p.Put.Start + put_buff_size;

	/* setup output file */
#if PC_WATCOM
	des_file = _fsopen(des_name, "wb", SH_DENYWR);
					/* ^ use _fsopen in watcom so we can make sure the input file
						isn't the same file as the output file.  If it is the same,
						_fsopen will fail with a sharing violation error */
#else
	des_file = fopen(des_name, "wb");
#endif
	if(check1(des_file != NULL,"Could not create %s", des_name)) goto quit;

	p.u.ROR.RegionInfo = NULL;
for(ct = 0;ct < num_loops;++ct)
{
	p.Get.Rear = p.Get.Start + len + join_offset;
	p.Get.Front = p.Get.Start;
	p.Put.Front = p.Put.Rear = p.Put.Start;

#if USE_PEG_QRY
	/* note: PegasusQuery is not ANSI */
	p.u.QRY.BitFlagsReq = QBIT_BICOMPRESSION;
	if(check1(PegasusQuery(&p), "Invalid PegasusQuery")) goto quit;
	memset(&p.u.QRY, 0, sizeof(p.u.QRY));
	if(check1(p.Head.biCompression == BI_PICJ ||
#if PIC2_IN
				p.Head.biCompression == BI_PC2J	||
#endif
#if ELS_CODER_IN
				p.Head.biCompression == BI_JPGE	||
#if PIC2_IN
				p.Head.biCompression == BI_PC2E	||
#endif
#endif
				p.Head.biCompression == BI_JPEG, "Unsupported file type")) goto quit;
#endif

	/*  Set up the output image characteristics. */

	p.ParmSize = sizeof(PIC_PARM);
	p.ParmVer = CURRENT_PARMVER;   p.ParmVerMinor = 1;
#if ELS_CODER_OUT
	p.Op = OP_RORE;
#else
	p.Op = OP_ROR;
#endif
	p.u.ROR.PicFlags = 0;
	p.VisualOrient = orient;
	p.u.ROR.PicFlags = 0;
	if(num_loops == 1)
		p.u.ROR.PicFlags |= PF_YieldPut;
	p.u.ROR.Pad = pad;
	p.u.ROR.KeepColors = keep_colors;
#if ELS_CODER_OUT
	if(els_coder_out)
		p.u.ROR.PicFlags |= PF_ElsCoder;
#endif
	p.u.ROR.JpegType = JT_RAW;
#if PIC2_OUT
	if(pic2_out)
		p.u.ROR.JpegType = JT_PIC2;
#endif
	memcpy(p.KeyField, key, 8);
		memcpy(p.u.ROR.OutputKeyField, outputkey, 8);
	if(requant || ((src_name_join != NULL) && (join_use_requested_quantization)))
	{
		p.u.ROR.Requantize = requant;
		if (QTableName[0] != '\0')
			p.u.ROR.QTableReq = (BYTE PICHUGE *) qtable;
		else
		{
			p.u.ROR.LumFactorReq = lum_opt;
			p.u.ROR.ChromFactorReq =  chrom_opt;
		}
	}
	p.u.ROR.AppsToKeep = apps_to_keep;
	p.u.ROR.RemoveComments = remove_comments;

	if(src_name_join != NULL)
	{
		p.u.ROR.JoinFlags |= JF_DoJoin;
		p.u.ROR.JoinOffset = join_offset;
		if(join_use_requested_quantization)
			p.u.ROR.JoinFlags |= JF_UseRequestedQuantization;
		if(join_left_right)
			p.u.ROR.JoinFlags |= JF_LeftRight;
		if(join_insert)
		{
			p.u.ROR.JoinFlags |= JF_Insert;
			p.u.ROR.InsertTransparencyLum = insert_transparency_lum;
			p.u.ROR.InsertTransparencyChrom = insert_transparency_chrom;
		}
		if(join_second_on_top_left)
			p.u.ROR.JoinFlags |= JF_SecondOnTopLeftInsert;
		if(join_subsampling_from_second)
			p.u.ROR.JoinFlags |= JF_UseSecondSubsampling;
		if(join_quantization_from_second)
			p.u.ROR.JoinFlags |= JF_UseSecondQuantization;
	}
#if(USE_PEG_QRY)
	if(p.Head.biHeight < 1)
	{
		p.Head.biHeight = -p.Head.biHeight;
		/* from now on,p.Head.biHeight is positive. */
	}
	if(regions)
	{
		p.u.ROR.NumRegions = 2;
		p.u.ROR.RegionMapWidth = (p.Head.biWidth + 7) >> 3;
		p.u.ROR.RegionMapHeight = (p.Head.biHeight + 7) >> 3;
		region_x = crop_x >> 3;
		region_y = crop_y >> 3;
		region_endx = (crop_x + crop_w + 7) >> 3;
		region_endy = (crop_y + crop_h + 7) >> 3;
		if(check1(region_x < p.u.ROR.RegionMapWidth &&
							region_y < p.u.ROR.RegionMapHeight &&
							region_endx <= p.u.ROR.RegionMapWidth &&
							region_endy <= p.u.ROR.RegionMapHeight,
			 "Bad region rectangle")) goto quit;
		region_w = region_endx - region_x;
		region_h = region_endy - region_y;
		p.u.ROR.RegionInfo = malloc(8*p.u.ROR.NumRegions + 128*num_tables +
				p.u.ROR.RegionMapWidth * p.u.ROR.RegionMapHeight );
		if(check1(p.u.ROR.RegionInfo != NULL, "Out of memory for RegionInfo")) goto quit;
		region_info_ptr = p.u.ROR.RegionInfo;
		region_info = (REGION_INFO *)region_info_ptr;
		region_info->NumTbls = 255; /* indicates to use qtables from input jpeg for region 0 */
		region_info_ptr += 8; /* word for Lum.,word for Chrom, dword for NumTbls */
		region_info = (REGION_INFO *)region_info_ptr;
		region_info->LumFactor = lum_opt;
		region_info->ChromFactor = chrom_opt;
		region_info->NumTbls = num_tables;
		if (num_tables != 0)
			memcpy(&(region_info->QTbls[0]),region_qtable,num_tables*128);
		p.u.ROR.RegionMapOffset = 8*p.u.ROR.NumRegions + 128*num_tables;
		bptr = p.u.ROR.RegionInfo + p.u.ROR.RegionMapOffset;
		memset(bptr,1,p.u.ROR.RegionMapWidth * p.u.ROR.RegionMapHeight); /* background has index 1 */
		bptr += (region_y * p.u.ROR.RegionMapWidth) + region_x;
		for(k = 0;k < region_h;++k)
		{
			memset(bptr,0,region_w); /* rectangle of interest has index 0 */
			bptr += p.u.ROR.RegionMapWidth;
		}
	}
#endif



/*p.Head.biBitCount = 24; // temp, while not using PegasusQuery */



	if(crop_flg)
	{
		p.Flags |= F_Crop;
		if(crop_w == 0)
			crop_w = 65535; /* init will cut this back to full width */
		if(crop_h == 0)
			crop_h = 65535;
		p.CropWidth = crop_w;
		p.CropHeight = crop_h;
	}
	p.CropXoff = crop_x; /* used also for inserting */
	p.CropYoff = crop_y;


#if	NOCO
	/*  Initialize Jpeg decompression */
	res = Pegasus(&p, REQ_INIT);
	if(check1(defer_status >= 0, "Error %d in DeferFn.", defer_status)) goto quit;
	if(check1(res != RES_ERR, "Error number %d in Pegasus.",p.Status)) goto quit;
	if(check1(p.Status >= 0, "Error %d in Pegasus.", p.Status)) goto quit;
	if (p.Status > 0)  printf("Status %d in Pegasus Init.\n", p.Status);
	if(p.Status == ERR_JUNK_BYTES_IN_HEADER)
		printf("Junk bytes found in header were skipped over.\n");

	/*  Decompress the file. */
	res = Pegasus(&p, REQ_EXEC);
/*	if(check1(defer_status >= 0, "Error %d in DeferFn.", defer_status)) goto quit; */
/*	check1(res != RES_ERR, "Error number %d in Pegasus.",p.Status); output what you can */

	/* Let Pegasus close things(in seq. jpeg, everything is already closed, */
	/* but this would not necessarily be true for progressive) */
	/* res = Pegasus(&p,REQ_TERM); // This can only return RES_DONE, and */
	/* does not change p->Status. Not needed in seq. */

	if (p.Status)  printf("Status %d in Pegasus.\n", p.Status);

#else

	/*  Initialize Jpeg decompression */
	local_status = 0;
	res = Pegasus(&p, REQ_INIT);
	while (res != RES_DONE)
	{
		if (res == RES_GET_NEED_DATA) {
			local_status = read_file(&p);
		} else if (res == RES_PUT_DATA_YIELD) {
			if(num_loops == 1)
				local_status = copy_to_file(&p);
		} else if (res == RES_PUT_NEED_SPACE) {
			if(check1(num_loops == 1,"output buffer too small to do loops")) goto quit;
			local_status = copy_to_file(&p);
		} else if (res == RES_ERR) {
			if(check1(FALSE, "Error number %d ",p.Status)) goto quit;
		} else {
			if(check1(FALSE, "Unexpected or unknown response %d ", res)) goto quit;
		}
		if(check1(p.Status >= 0, "Error %d in Pegasus", p.Status)) goto quit;
		if(check1(local_status >= 0, "Error %d in Pegasus", local_status)) goto quit;
		if (p.Status > 0)  printf("Status %d in Pegasus.\n", p.Status);
		res = Pegasus(&p, REQ_CONT);
	}
	if(check1(p.Status >= 0, "Error %d in Pegasus", p.Status)) goto quit;
	if (p.Status > 0)
		printf("Status %d in Pegasus Init.\n", p.Status);
	if(p.Status == ERR_JUNK_BYTES_IN_HEADER)
		printf("Junk bytes found in header were skipped over.\n");


	/*  Convert the file. */
	res = Pegasus(&p, REQ_EXEC);
	while (res != RES_DONE)
	{
		if (res == RES_GET_NEED_DATA)
			local_status = read_file(&p);
		else if (res == RES_PUT_NEED_SPACE)
		{
			if(check1(num_loops == 1,"output buffer too small to do loops")) goto quit;
			local_status = copy_to_file(&p);
		}
		else if (res == RES_PUT_DATA_YIELD)
		{
			if(num_loops == 1)
				local_status = copy_to_file(&p);
		}
		else if (res == RES_POKE)
		{
			/* write out remainder of put buffer, if any -- there won't
					be a poke until after pack has output everything.
					flushing here saves us having to remember the current
					file position so we can seek back for the final write */
			if ( p.Put.Rear > p.Put.Front )
			{
				len = p.Put.Rear - p.Put.Front;
				if(check1(fwrite(p.Put.Front,sizeof(BYTE),len,des_file) == len,
						"output file write error")) goto quit;
				p.Put.Front = p.Put.Rear;     /* it's empty now */
			}
			else if ( p.Put.Rear < p.Put.Front )
				{
				len = p.Put.End - p.Put.Front;
				if(check1(fwrite(p.Put.Front,sizeof(BYTE),len,des_file) == len,
						"output file write error")) goto quit;
				len = p.Put.Rear - p.Put.Start;
				if(check1(fwrite(p.Put.Start,sizeof(BYTE),len,des_file) == len,
						"output file write error")) goto quit;
        p.Put.Front = p.Put.Rear;     /* it's empty now */
        }
      /* else Rear == Front and there's nothing left to write */
			if(check1(fseek(des_file, p.SeekInfo, SEEK_SET) == 0,
					"output file seek error")) goto quit;
			len = p.Put.RearEnd - p.Put.FrontEnd;
			if(check1(fwrite(p.Put.FrontEnd, sizeof(BYTE), len, des_file) == len,
					"output file write error")) goto quit;
		}
		else if (res == RES_YIELD)
			;
		else if (res == RES_ERR)
			break; /* output what you can. check(FALSE, "Error number %d ",p.Status); */
		else
			if(check1(FALSE, "Unexpected or unknown response %d ", res)) goto quit;
		if(local_status < 0)
    	break;
		res = Pegasus(&p, REQ_CONT);
	}
	if (p.Status)  printf("Status %d in Pegasus.\n", p.Status);
	Pegasus(&p, REQ_TERM);
#endif

	if(p.u.ROR.RegionInfo != NULL)
	{
		free(p.u.ROR.RegionInfo);
		p.u.ROR.RegionInfo = NULL;
	}
}
	if(p.Status == ERR_JUNK_BYTES_IN_HEADER)
		printf("Junk bytes found in header were skipped over.\n");
	if(p.Status == ERR_JUNK_BYTES_BEFORE_RESTART)
		printf("Junk bytes found before restart marker(s) were skipped over.\n");
	if(p.Status == ERR_RESTART_ATTEMPT_AFTER_BAD_DATA)
		printf("Bad data or unexpected end of data in entropy segment, restart attempted.\n");
#if NOCO
	if (defer_status)  printf("defer status %d in Pegasus.\n", defer_status);
#else
	if (local_status)  printf("local status %d in Pegasus.\n", local_status);
#endif
#if REQUANT
	if(p.u.ROR.Requantize && !p.u.ROR.RequantizationDone)
		printf("\nFile was not requantized.\n");
#endif

	/*  copy output buffer to file (if not already done) */
	/* We are not wrapping queue, so Rear >= Front always. */

	if( (len = p.Put.Rear - p.Put.Front) > 0)
		if (fwrite(p.Put.Front, sizeof(BYTE), len, des_file) < len)
			if(check1(FALSE, "error writing output file")) goto quit;

	printf("Converted file %s to %s.\n", src_name, des_name);

	/*  Close files, free memory. */
quit:
	if (src_file != NULL)
		fclose(src_file);
	if (src_file_join != NULL)
		fclose(src_file_join);
	if (des_file != NULL)
		fclose(des_file);

	if(p.Put.Start != NULL)
	{
		free(p.Put.Start);
		p.Put.Start = NULL;
	}
	if(p.Get.Start != NULL)
	{
		free(p.Get.Start);
		p.Get.Start = NULL;
	}
	if(p.u.ROR.RegionInfo != NULL)
	{
		free(p.u.ROR.RegionInfo);
		p.u.ROR.RegionInfo = NULL;
	}
	return (p.Status);
}
Example #9
0
int main(int argc, char **argv)
{
	struct dvb_frontend_parameters frontend_param;
	char *homedir = getenv("HOME");
	char *confname = NULL;
	char *channel = NULL;
	int adapter = 0, frontend = 0, demux = 0, dvr = 0;
	int vpid, apid, sid, pmtpid = 0;
	int pat_fd, pmt_fd;
	int frontend_fd, audio_fd = 0, video_fd = 0, dvr_fd, file_fd;
	int opt;
	int record = 0;
	int frontend_only = 0;
	char *filename = NULL;
	int human_readable = 0, rec_psi = 0;

	while ((opt = getopt(argc, argv, "H?hrpxRsFSn:a:f:d:c:t:o:")) != -1) {
		switch (opt) {
		case 'a':
			adapter = strtoul(optarg, NULL, 0);
			break;
		case 'f':
			frontend = strtoul(optarg, NULL, 0);
			break;
		case 'd':
			demux = strtoul(optarg, NULL, 0);
			break;
		case 't':
			timeout = strtoul(optarg, NULL, 0);
			break;
		case 'o':
			filename = strdup(optarg);
			record=1;
			/* fall through */
		case 'r':
			dvr = 1;
			break;
		case 'p':
			rec_psi = 1;
			break;
		case 'x':
			exit_after_tuning = 1;
			break;
		case 'c':
			confname = optarg;
			break;
		case 's':
			silent = 1;
			break;
		case 'S':
			silent = 2;
			break;
		case 'F':
			frontend_only = 1;
			break;
		case 'H':
			human_readable = 1;
			break;
		case '?':
		case 'h':
		default:
			fprintf (stderr, usage, argv[0]);
			return -1;
		};
	}

	if (optind < argc)
		channel = argv[optind];

	if (!channel) {
		fprintf (stderr, usage, argv[0]);
		return -1;
	}
#if defined(ANDROID)
	snprintf(FRONTEND_DEV,
		 sizeof(FRONTEND_DEV),
		 "/dev/dvb%i.frontend%i",
	  	 adapter,
	  	 frontend);

	snprintf(DEMUX_DEV,
		 sizeof(DEMUX_DEV),
		 "/dev/dvb%i.demux%i",
	  	 adapter,
	  	 demux);

	snprintf(DVR_DEV,
		 sizeof(DVR_DEV),
		 "/dev/dvb%i.dvr%i",
	  	 adapter,
	  	 demux);
#else
	snprintf(FRONTEND_DEV,
		 sizeof(FRONTEND_DEV),
		 "/dev/dvb/adapter%i/frontend%i",
	  	 adapter,
	  	 frontend);

	snprintf(DEMUX_DEV,
		 sizeof(DEMUX_DEV),
		 "/dev/dvb/adapter%i/demux%i",
	  	 adapter,
	  	 demux);

	snprintf(DVR_DEV,
		 sizeof(DVR_DEV),
		 "/dev/dvb/adapter%i/dvr%i",
	  	 adapter,
	  	 demux);
#endif
	if (silent < 2)
		fprintf (stderr,"using '%s' and '%s'\n", FRONTEND_DEV, DEMUX_DEV);

	if (!confname) {
		int len = strlen(homedir) + strlen(CHANNEL_FILE) + 18;
		if (!homedir)
			ERROR ("$HOME not set");
		confname = malloc (len);
		snprintf(confname, len, "%s/.tzap/%i/%s", homedir, adapter, CHANNEL_FILE);
		if (access (confname, R_OK))
			snprintf(confname, len, "%s/.tzap/%s", homedir, CHANNEL_FILE);
	}
	printf("reading channels from file '%s'\n", confname);
	memset(&frontend_param, 0, sizeof(struct dvb_frontend_parameters));

	if (parse (confname, channel, &frontend_param, &vpid, &apid, &sid))
		return -1;

	if ((frontend_fd = open(FRONTEND_DEV, O_RDWR | O_NONBLOCK)) < 0) {
		PERROR ("failed opening '%s'", FRONTEND_DEV);
		return -1;
	}

	if (setup_frontend (frontend_fd, &frontend_param) < 0)
		return -1;

	if (frontend_only)
		goto just_the_frontend_dude;

	if (rec_psi) {
	    	pmtpid = get_pmt_pid(DEMUX_DEV, sid);
	    	if (pmtpid <= 0) {
			fprintf(stderr,"couldn't find pmt-pid for sid %04x\n",sid);
			return -1;
	    	}

	    	if ((pat_fd = open(DEMUX_DEV, O_RDWR)) < 0) {
			perror("opening pat demux failed");
			return -1;
	    	}
	    	if (set_pesfilter(pat_fd, 0, DMX_PES_OTHER, dvr) < 0)
			return -1;

	    	if ((pmt_fd = open(DEMUX_DEV, O_RDWR)) < 0) {
			perror("opening pmt demux failed");
			return -1;
	    	}
	    	if (set_pesfilter(pmt_fd, pmtpid, DMX_PES_OTHER, dvr) < 0)
			return -1;
	}

	if ((video_fd = open(DEMUX_DEV, O_RDWR)) < 0) {
		PERROR("failed opening '%s'", DEMUX_DEV);
		return -1;
	}

	if (silent<2)
		fprintf(stderr,"video pid 0x%04x, audio pid 0x%04x\n", vpid, apid);

	if (set_pesfilter(video_fd, vpid, DMX_PES_VIDEO, dvr) < 0)
		return -1;

	if ((audio_fd = open(DEMUX_DEV, O_RDWR)) < 0) {
		PERROR("failed opening '%s'", DEMUX_DEV);
		return -1;
	}

	if (set_pesfilter(audio_fd, apid, DMX_PES_AUDIO, dvr) < 0)
		return -1;

	signal(SIGALRM,do_timeout);
	if (timeout > 0)
		alarm(timeout);

	if (record) {
		if (filename!=NULL) {
			if (strcmp(filename,"-")!=0) {
				file_fd = open(filename,O_WRONLY|O_LARGEFILE|O_CREAT,0644);
				if (file_fd<0) {
					PERROR("open of '%s' failed",filename);
					return -1;
				}
			} else {
				file_fd=1;
			}
		} else {
			PERROR("Record mode but no filename!");
			return -1;
		}

		if ((dvr_fd = open(DVR_DEV, O_RDONLY)) < 0) {
	                PERROR("failed opening '%s'", DVR_DEV);
	                return -1;
	        }
		if (silent<2)
			print_frontend_stats(frontend_fd, human_readable);

		copy_to_file(dvr_fd,file_fd);

		if (silent<2)
			print_frontend_stats(frontend_fd, human_readable);
	} else {
just_the_frontend_dude:
		monitor_frontend(frontend_fd, human_readable);
	}

	close(pat_fd);
	close(pmt_fd);
	close(audio_fd);
	close(video_fd);
	close(frontend_fd);
	return 0;
}
Example #10
0
int main(int argc, char **argv)
{
	struct arguments args;
	char *homedir = getenv("HOME");
	char *channel = NULL;
	int lnb = -1, idx = -1;
	int vpid = -1, apid = -1, sid = -1;
	int pmtpid = 0;
	int pat_fd = -1, pmt_fd = -1, sid_fd = -1;
	int audio_fd = -1, video_fd = -1;
	int dvr_fd = -1, file_fd = -1;
	int err = -1;
	int r;
	struct dvb_v5_fe_parms *parms = NULL;
	const struct argp argp = {
		.options = options,
		.parser = parse_opt,
		.doc = N_("DVB zap utility"),
		.args_doc = N_("<channel name> [or <frequency> if in monitor mode]"),
	};

#ifdef ENABLE_NLS
	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);
#endif

	memset(&args, 0, sizeof(args));
	args.sat_number = -1;
	args.lna = LNA_AUTO;
	args.input_format = FILE_DVBV5;

	argp_parse(&argp, argc, argv, ARGP_NO_HELP | ARGP_NO_EXIT, &idx, &args);

	if (idx < argc)
		channel = argv[idx];

	if (!channel) {
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}

	if (args.input_format == FILE_UNKNOWN) {
		fprintf(stderr, _("ERROR: Please specify a valid format\n"));
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}

	if (!args.traffic_monitor && args.search) {
		fprintf(stderr, _("ERROR: search string can be used only on monitor mode\n"));
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}

	if (args.lnb_name) {
		lnb = dvb_sat_search_lnb(args.lnb_name);
		if (lnb < 0) {
			printf(_("Please select one of the LNBf's below:\n"));
			dvb_print_all_lnb();
			exit(1);
		} else {
			printf(_("Using LNBf "));
			dvb_print_lnb(lnb);
		}
	}

	r = asprintf(&args.demux_dev,
		 "/dev/dvb/adapter%i/demux%i", args.adapter, args.demux);
	if (r < 0) {
		fprintf(stderr, _("asprintf error\n"));
		return -1;
	}

	r = asprintf(&args.dvr_dev,
		 "/dev/dvb/adapter%i/dvr%i", args.adapter, args.demux);
	if (r < 0) {
		fprintf(stderr, _("asprintf error\n"));
		return -1;
	}

	if (args.silent < 2)
		fprintf(stderr, _("using demux '%s'\n"), args.demux_dev);

	if (!args.confname) {
		if (!homedir)
			ERROR(_("$HOME not set"));
		r = asprintf(&args.confname, "%s/.tzap/%i/%s",
			 homedir, args.adapter, CHANNEL_FILE);
		if (access(args.confname, R_OK)) {
			free(args.confname);
			r = asprintf(&args.confname, "%s/.tzap/%s",
				homedir, CHANNEL_FILE);
		}
	}
	fprintf(stderr, _("reading channels from file '%s'\n"), args.confname);

	parms = dvb_fe_open(args.adapter, args.frontend, args.verbose, args.force_dvbv3);
	if (!parms)
		goto err;
	if (lnb >= 0)
		parms->lnb = dvb_sat_get_lnb(lnb);
	if (args.sat_number > 0)
		parms->sat_number = args.sat_number % 3;
	parms->diseqc_wait = args.diseqc_wait;
	parms->freq_bpf = args.freq_bpf;
	parms->lna = args.lna;

	r = dvb_fe_set_default_country(parms, args.cc);
	if (r < 0)
		fprintf(stderr, _("Failed to set the country code:%s\n"), args.cc);

	if (parse(&args, parms, channel, &vpid, &apid, &sid))
		goto err;

	if (setup_frontend(&args, parms) < 0)
		goto err;

	if (args.exit_after_tuning) {
		err = 0;
		check_frontend(&args, parms);
		goto err;
	}

	if (args.traffic_monitor) {
		signal(SIGTERM, do_timeout);
		signal(SIGINT, do_timeout);
		if (args.timeout > 0) {
			signal(SIGINT, do_timeout);
			alarm(args.timeout);
		}

		err = do_traffic_monitor(&args, parms);
		goto err;
	}

	if (args.rec_psi) {
		if (sid < 0) {
			fprintf(stderr, _("Service id 0x%04x was not specified at the file\n"),
				sid);
			goto err;
		}

		sid_fd = dvb_dmx_open(args.adapter, args.demux);
		if (sid_fd < 0) {
			perror(_("opening pat demux failed"));
			return -1;
		}
		pmtpid = dvb_get_pmt_pid(sid_fd, sid);
		dvb_dmx_close(sid_fd);
		if (pmtpid <= 0) {
			fprintf(stderr, _("couldn't find pmt-pid for sid %04x\n"),
				sid);

			goto err;
		}

		if ((pat_fd = open(args.demux_dev, O_RDWR)) < 0) {
			perror(_("opening pat demux failed"));
			goto err;
		}
		if (dvb_set_pesfilter(pat_fd, 0, DMX_PES_OTHER,
				args.dvr ? DMX_OUT_TS_TAP : DMX_OUT_DECODER,
				args.dvr ? 64 * 1024 : 0) < 0)
			goto err;

		if ((pmt_fd = open(args.demux_dev, O_RDWR)) < 0) {
			perror(_("opening pmt demux failed"));
			goto err;
		}
		if (dvb_set_pesfilter(pmt_fd, pmtpid, DMX_PES_OTHER,
				args.dvr ? DMX_OUT_TS_TAP : DMX_OUT_DECODER,
				args.dvr ? 64 * 1024 : 0) < 0)
			goto err;
	}

	if (args.all_pids++) {
		vpid = 0x2000;
		apid = 0;
	}
	if (vpid >= 0) {
		if (args.silent < 2) {
			if (vpid == 0x2000)
				fprintf(stderr, _("pass all PID's to TS\n"));
			else
				fprintf(stderr, _("video pid %d\n"), vpid);
		}
		if ((video_fd = open(args.demux_dev, O_RDWR)) < 0) {
			PERROR(_("failed opening '%s'"), args.demux_dev);
			goto err;
		}

		if (args.silent < 2)
			fprintf(stderr, _("  dvb_set_pesfilter %d\n"), vpid);
		if (vpid == 0x2000) {
			if (ioctl(video_fd, DMX_SET_BUFFER_SIZE, 1024 * 1024) == -1)
				perror(_("DMX_SET_BUFFER_SIZE failed"));
			if (dvb_set_pesfilter(video_fd, vpid, DMX_PES_OTHER,
					      DMX_OUT_TS_TAP, 0) < 0)
				goto err;
		} else {
			if (dvb_set_pesfilter(video_fd, vpid, DMX_PES_VIDEO,
				args.dvr ? DMX_OUT_TS_TAP : DMX_OUT_DECODER,
				args.dvr ? 64 * 1024 : 0) < 0)
				goto err;
		}
	}

	if (apid > 0) {
		if (args.silent < 2)
			fprintf(stderr, _("audio pid %d\n"), apid);
		if ((audio_fd = open(args.demux_dev, O_RDWR)) < 0) {
			PERROR(_("failed opening '%s'"), args.demux_dev);
			goto err;
		}
		if (args.silent < 2)
			fprintf(stderr, _("  dvb_set_pesfilter %d\n"), apid);
		if (dvb_set_pesfilter(audio_fd, apid, DMX_PES_AUDIO,
				args.dvr ? DMX_OUT_TS_TAP : DMX_OUT_DECODER,
				args.dvr ? 64 * 1024 : 0) < 0)
			goto err;
	}

	signal(SIGALRM, do_timeout);
	signal(SIGTERM, do_timeout);
	if (args.timeout > 0) {
		signal(SIGINT, do_timeout);
		alarm(args.timeout);
	}

	if (!check_frontend(&args, parms)) {
		err = 1;
		fprintf(stderr, _("frontend doesn't lock\n"));
		goto err;
	}

	if (args.dvr) {
		if (args.filename) {
			file_fd = STDOUT_FILENO;

			if (strcmp(args.filename, "-") != 0) {
				file_fd = open(args.filename,
#ifdef O_LARGEFILE
					 O_LARGEFILE |
#endif
					 O_WRONLY | O_CREAT,
					 0644);
				if (file_fd < 0) {
					PERROR(_("open of '%s' failed"),
					       args.filename);
					return -1;
				}
			}
		}

		if (args.silent < 2)
			get_show_stats(&args, parms, 0);

		if (file_fd >= 0) {
			if ((dvr_fd = open(args.dvr_dev, O_RDONLY)) < 0) {
				PERROR(_("failed opening '%s'"), args.dvr_dev);
				goto err;
			}
			if (!timeout_flag)
				fprintf(stderr, _("Record to file '%s' started\n"), args.filename);
			copy_to_file(dvr_fd, file_fd, args.timeout, args.silent);
		} else {
			if (!timeout_flag)
				fprintf(stderr, _("DVR interface '%s' can now be opened\n"), args.dvr_dev);

			get_show_stats(&args, parms, 1);
		}
		if (args.silent < 2)
			get_show_stats(&args, parms, 0);
	}
	err = 0;

err:
	if (file_fd > 0)
		close(file_fd);
	if (dvr_fd > 0)
		close(dvr_fd);
	if (pat_fd > 0)
		close(pat_fd);
	if (pmt_fd > 0)
		close(pmt_fd);
	if (audio_fd > 0)
		close(audio_fd);
	if (video_fd > 0)
		close(video_fd);
	if (parms)
		dvb_fe_close(parms);
	if (args.confname)
		free(args.confname);
	if (args.demux_dev)
		free(args.demux_dev);
	if (args.dvr_dev)
		free(args.dvr_dev);

	return err;
}
Example #11
0
int main(void)
{
	// Shared memory. shm1 used for circular buffer, shm2 used for metadata
	int shmid, shmid2;
	void *shared_memory1 = (void *)0;
	void *shared_memory2 = (void *)0;
 	struct buffer_block *shared_buffer;
 	struct metadata *shared_metadata;
 	int buffer_index;
  
  // Semaphores. S: mutual exclusion. N: synch producer before consumer. E: buffer space
  int sem_S_id, sem_N_id, sem_E_id;

  // Output file
  int file_out;
  int nWrite_file; 	// Num bytes written to file

	
	/* Creating shared memory (circular buffer) */
	if (init_shm_circularBuffer(SHM_KEY, &shmid, &shared_memory1) == -1) {
		exit(EXIT_FAILURE);
	}
	printf("[C] Shared Memory (circular buffer) attached at: %p. shmid: %d\n", (int*)shared_memory1, shmid);	
	shared_buffer = (struct buffer_block*) shared_memory1;			// Assigns shared_memory segment to shared_buffer
	buffer_index = 0;

	/* Creating shared memory (metadata) */
	if (init_shm_metadata(SHM2_KEY, &shmid2, &shared_memory2) == -1) {
		exit(EXIT_FAILURE);
	}
	printf("[C] Shared Memory (metadata) attached at %p, shmid: %d\n", (int*)shared_memory2, shmid2);
	shared_metadata = (struct metadata*) shared_memory2;						// Assigns shared_memory2 segment to shared_metadata

	printf(" - - - - - - - - - - - - - - - - - - - - - - \n");
	
	/* Creating semaphores */
	sem_S_id = semget((key_t)SEM_S_KEY, 1, 0666 | IPC_CREAT);
	sem_N_id = semget((key_t)SEM_N_KEY, 1, 0666 | IPC_CREAT);
	sem_E_id = semget((key_t)SEM_E_KEY, 1, 0666 | IPC_CREAT);

  // Open file for writing
  open_file_write(&file_out);
  // Wait for producer first so that the number of bytes read from file is known
  printf("[C] Waiting for producer to get input file size...\n");
  semaphore_wait(sem_N_id);
  printf("[C] File size information from producer: %d bytes\n", shared_metadata->file_byte_count);

  /* Start time difference. For Bonus */
  struct timeval start_time, end_time;
  gettimeofday(&start_time, NULL);


  /* Copy contents from shared memory to the output file */
  printf("[C] Reading from shared memory and writing to file...\n");
  nWrite_file = 0;
	while (nWrite_file < shared_metadata->file_byte_count) {
		semaphore_wait(sem_N_id);
		semaphore_wait(sem_S_id);
		nWrite_file += copy_to_file(file_out, shared_buffer, &buffer_index);
		semaphore_signal(sem_S_id);
		semaphore_signal(sem_E_id);
		printf("[C]	Bytes written to file: %d\n", nWrite_file);
	}

	printf(" - - - - - - - - - - - - - - - - - - - - - - \n");
	printf("[C] Total Bytes written to '%s': %d\n", FILE_OUT, nWrite_file);

	/* Calculate time difference. For Bonus */
	gettimeofday(&end_time, NULL);
	printf(">> %ld microseconds\n", ((end_time.tv_sec * MICRO_SEC_IN_SEC + end_time.tv_usec) - (start_time.tv_sec * MICRO_SEC_IN_SEC + start_time.tv_usec)));

	/* Cleanup */
	// Close file
	if (close(file_out) == -1) {
		fprintf(stderr, "[C] File close failed\n");
	}
	// Shared memory is detached and deleted
  if (shmdt(shared_memory1) == -1) {
    fprintf(stderr, "[C] shmdt failed\n");
    exit(EXIT_FAILURE);
  }
  if (shmctl(shmid, IPC_RMID, 0) == -1) {
    fprintf(stderr, "[C] shmctl(IPC_RMID) failed\n");
    exit(EXIT_FAILURE);
  }
  if (shmdt(shared_memory2) == -1) {
    fprintf(stderr, "[C] shmdt failed\n");
    exit(EXIT_FAILURE);
  }
  if (shmctl(shmid2, IPC_RMID, 0) == -1) {
    fprintf(stderr, "[C] shmctl(IPC_RMID) failed\n");
    exit(EXIT_FAILURE);
  }

  // Delete Semaphores
  del_semvalue(sem_S_id);
  del_semvalue(sem_N_id);
  del_semvalue(sem_E_id);

	exit(EXIT_SUCCESS);
}