コード例 #1
0
ファイル: wall.c プロジェクト: azat-archive/util-linux
static char *makemsg(char *fname, char **mvec, int mvecsz,
		     size_t *mbufsize, int print_banner)
{
	register int ch, cnt;
	struct stat sbuf;
	FILE *fp;
	char *p, *lbuf, *tmpname, *mbuf;
	long line_max;

	line_max = sysconf(_SC_LINE_MAX);
	lbuf = xmalloc(line_max);

	if ((fp = xfmkstemp(&tmpname, NULL)) == NULL)
		err(EXIT_FAILURE, _("can't open temporary file"));
	unlink(tmpname);
	free(tmpname);

	if (print_banner == TRUE) {
		char *hostname = xgethostname();
		char *whom, *where, *date;
		struct passwd *pw;
		time_t now;

		if (!(whom = getlogin()) || !*whom)
			whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
		if (!whom) {
			whom = "someone";
			warn(_("cannot get passwd uid"));
		}
		where = ttyname(STDOUT_FILENO);
		if (!where) {
			where = "somewhere";
			warn(_("cannot get tty name"));
		} else if (strncmp(where, "/dev/", 5) == 0)
			where += 5;

		time(&now);
		date = xstrdup(ctime(&now));
		date[strlen(date) - 1] = '\0';

		/*
		 * all this stuff is to blank out a square for the message;
		 * we wrap message lines at column 79, not 80, because some
		 * terminals wrap after 79, some do not, and we can't tell.
		 * Which means that we may leave a non-blank character
		 * in column 80, but that can't be helped.
		 */
		/* snprintf is not always available, but the sprintf's here
		   will not overflow as long as %d takes at most 100 chars */
		fprintf(fp, "\r%79s\r\n", " ");
		sprintf(lbuf, _("Broadcast message from %s@%s (%s) (%s):"),
			      whom, hostname, where, date);
		fprintf(fp, "%-79.79s\007\007\r\n", lbuf);
		free(hostname);
		free(date);
	}
	fprintf(fp, "%79s\r\n", " ");

	 if (mvec) {
		/*
		 * Read message from argv[]
		 */
		int i;

		for (i = 0; i < mvecsz; i++) {
			fputs(mvec[i], fp);
			if (i < mvecsz - 1)
				fputc(' ', fp);
		}
		fputc('\r', fp);
		fputc('\n', fp);

	} else {
		/*
		 * read message from <file>
		 */
		if (fname) {
			/*
			 * When we are not root, but suid or sgid, refuse to read files
			 * (e.g. device files) that the user may not have access to.
			 * After all, our invoker can easily do "wall < file"
			 * instead of "wall file".
			 */
			uid_t uid = getuid();
			if (uid && (uid != geteuid() || getgid() != getegid()))
				errx(EXIT_FAILURE, _("will not read %s - use stdin."),
				     fname);

			if (!freopen(fname, "r", stdin))
				err(EXIT_FAILURE, _("cannot open %s"), fname);

		}

		/*
		 * Read message from stdin.
		 */
		while (fgets(lbuf, line_max, stdin)) {
			for (cnt = 0, p = lbuf; (ch = *p) != '\0'; ++p, ++cnt) {
				if (cnt == 79 || ch == '\n') {
					for (; cnt < 79; ++cnt)
						putc(' ', fp);
					putc('\r', fp);
					putc('\n', fp);
					cnt = 0;
				}
				if (ch == '\t')
					cnt += (7 - (cnt % 8));
				if (ch != '\n')
					fputc_careful(ch, fp, '^');
			}
		}
	}
	fprintf(fp, "%79s\r\n", " ");

	free(lbuf);
	rewind(fp);

	if (fstat(fileno(fp), &sbuf))
		err(EXIT_FAILURE, _("stat failed"));

	*mbufsize = (size_t) sbuf.st_size;
	mbuf = xmalloc(*mbufsize);

	if (fread(mbuf, 1, *mbufsize, fp) != *mbufsize)
		err(EXIT_FAILURE, _("fread failed"));

	if (close_stream(fp) != 0)
		errx(EXIT_FAILURE, _("write error"));
	return mbuf;
}
コード例 #2
0
ファイル: output.c プロジェクト: jing-git/dhcpd-pools
/*! \brief The json output formats.
 * FIXME: This function should return void.
 */
int output_json(void)
{
	unsigned int i = 0;
	struct range_t *range_p;
	double range_size;
	struct shared_network_t *shared_p;
	int ret;
	FILE *outfile;
	unsigned int sep;

	if (config.output_file[0]) {
		outfile = fopen(config.output_file, "w+");
		if (outfile == NULL) {
			err(EXIT_FAILURE, "output_json: %s",
			    config.output_file);
		}
	} else {
		outfile = stdout;
	}

	range_p = ranges;
	range_size = get_range_size(range_p);
	shared_p = shared_networks;
	sep = 0;

	fprintf(outfile, "{\n");

	if (config.output_format[0] == 'X' || config.output_format[0] == 'J') {
		struct leases_t *l;
		fprintf(outfile, "   \"active_leases\": [");
		for (l = leases; l != NULL; l = l->hh.next) {
			if (l->type == ACTIVE) {
				if (i == 0) {
					i = 1;
				} else {
					fputc(',', outfile);
				}
				fputs("\n         { \"ip\":\"", outfile);
				fputs(ntop_ipaddr(&l->ip), outfile);
				fputs("\", \"macaddress\":\"", outfile);
				if (l->ethernet != NULL) {
					fputs(l->ethernet, outfile);
				}
				fputs("\" }", outfile);
			}
		}
		fprintf(outfile, "\n   ]");	/* end of active_leases */
		sep++;
	}

	if (config.output_limit[1] & BIT1) {
		if (sep) {
			fprintf(outfile, ",\n");
		}
		fprintf(outfile, "   \"subnets\": [\n");
		for (i = 0; i < num_ranges; i++) {
			fprintf(outfile, "         ");
			fprintf(outfile, "{ ");
			if (range_p->shared_net) {
				fprintf(outfile,
					"\"location\":\"%s\", ",
					range_p->shared_net->name);
			} else {
				fprintf(outfile, "\"location\":\"\", ");
			}

			fprintf(outfile, "\"range\":\"%s",
				ntop_ipaddr(&range_p->first_ip));
			fprintf(outfile, " - %s\", ",
				ntop_ipaddr(&range_p->last_ip));
			fprintf(outfile, "\"defined\":%g, ", range_size);
			fprintf(outfile, "\"used\":%g, ", range_p->count);
			fprintf(outfile, "\"free\":%g ",
				range_size - range_p->count);
			range_p++;
			range_size = get_range_size(range_p);
			if (i + 1 < num_ranges)
				fprintf(outfile, "},\n");
			else
				fprintf(outfile, "}\n");
		}
		fprintf(outfile, "   ]");	/* end of subnets */
		sep++;
	}

	if (config.output_limit[1] & BIT2) {
		if (sep) {
			fprintf(outfile, ",\n");
		}
		fprintf(outfile, "   \"shared-networks\": [\n");
		for (i = 0; i < num_shared_networks; i++) {
			fprintf(outfile, "         ");
			shared_p++;
			fprintf(outfile, "{ ");
			fprintf(outfile, "\"location\":\"%s\", ",
				shared_p->name);
			fprintf(outfile, "\"defined\":%g, ",
				shared_p->available);
			fprintf(outfile, "\"used\":%g, ", shared_p->used);
			fprintf(outfile, "\"free\":%g ",
				shared_p->available - shared_p->used);
			if (i + 1 < num_shared_networks)
				fprintf(outfile, "},\n");
			else
				fprintf(outfile, "}\n");
		}
		fprintf(outfile, "   ]");	/* end of shared-networks */
		sep++;
	}

	if (config.output_limit[0] & BIT3) {
		if (sep) {
			fprintf(outfile, ",\n");
		}
		fprintf(outfile, "   \"summary\": {\n");
		fprintf(outfile, "         \"location\":\"%s\",\n",
			shared_networks->name);
		fprintf(outfile, "         \"defined\":%g,\n",
			shared_networks->available);
		fprintf(outfile, "         \"used\":%g,\n",
			shared_networks->used);
		fprintf(outfile, "         \"free\":%g\n",
			shared_networks->available - shared_networks->used);
		fprintf(outfile, "   }");	/* end of summary */
		sep++;
	}

	fprintf(outfile, "\n}\n");
	if (outfile == stdout) {
		ret = fflush(stdout);
		if (ret) {
			warn("output_json: fflush");
		}
	} else {
		ret = close_stream(outfile);
		if (ret) {
			warn("output_json: fclose");
		}
	}

	return 0;
}
コード例 #3
0
ファイル: minisatip.c プロジェクト: TheTroll/minisatip
int
read_rtsp (sockets * s)
{
	char *arg[50];
	int cseq, la, i, rlen;
	char *proto, *transport = NULL, *useragent = NULL;
	int sess_id = 0;
	char buf[2000];
	streams *sid = get_sid(s->sid);

	if(s->buf[0]==0x24 && s->buf[1]<2)
	{
		if(sid)
			sid->rtime = s->rtime;

		int rtsp_len = s->buf[2]*256+s->buf[3];
		LOG("Received RTSP over tcp packet (sock_id %d, stream %d, rlen %d) packet len: %d, type %02X %02X discarding %s...", 
			s->id, s->sid, s->rlen, rtsp_len , s->buf[4], s->buf[5], (s->rlen == rtsp_len+4)?"complete":"fragment" );		
		if(s->rlen == rtsp_len+4){ // we did not receive the entire packet
			s->rlen = 0;			
			return 0;
		}
	}
	
	if (s->rlen < 4 || !end_of_header(s->buf + s->rlen - 4))
	{
		if( s->rlen > RBUF - 10 )
		{
			LOG("Discarding %d bytes from the socket buffer, request > %d, consider increasing  RBUF", s->rlen, RBUF);
			s->rlen = 0;
		}
		LOG("read_rtsp: read %d bytes from handle %d, sock_id %d, flags %d not ending with \\r\\n\\r\\n", s->rlen, s->sock, s->id, s->flags);
		if ( s->flags & 1 ) 
			return 0;		
		unsigned char *new_alloc = malloc1 (RBUF);
		memcpy(new_alloc, s->buf, s->rlen);
		s->buf = new_alloc;
		s->flags = s->flags | 1;
		return 0;
	}

	rlen = s->rlen;
	s->rlen = 0;

	LOG ("read RTSP (from handle %d sock_id %d, len: %d, sid %d):\n%s", s->sock, s->id, s->rlen, s->sid, s->buf);

	if( (s->type != TYPE_HTTP ) && (strncasecmp(s->buf, "GET", 3) == 0))
	{
		http_response (s , 404, NULL, NULL, 0, 0);
		return 0;
	}
	
	la = split (arg, s->buf, 50, ' ');
	cseq = 0;	
	if (la<2)
		LOG_AND_RETURN(0, "Most likely not an RTSP packet sock_id: %d sid: %d rlen: %d, dropping ....", s->id, s->sid, rlen); 
	
	if(s->sid<0)
		for (i = 0; i < la; i++)	
			if (strncasecmp ("Session:", arg[i], 8) == 0)
			{
				sess_id = map_int(header_parameter(arg, i), NULL);
				s->sid = find_session_id(sess_id);		
			}

	if(strstr(arg[1], "freq") || strstr(arg[1], "pids"))
	{
		int old_sid = s->sid;
		sid = (streams *) setup_stream (arg[1], s);
	}
	sid = get_sid(s->sid);
	if(sid)
		sid->rtime = s->rtime;

	if (sess_id)    
			set_session_id(s->sid, sess_id);
		
	
	for (i = 0; i < la; i++)
		if (strncasecmp ("CSeq:", arg[i], 5) == 0)
			cseq = map_int (header_parameter(arg, i), NULL);
		else if (strncasecmp ("Transport:", arg[i], 9) == 0){
			transport = header_parameter(arg, i);

			if( -1 == decode_transport (s, transport, opts.rrtp, opts.start_rtp))
			{
				http_response (s, 400, NULL, NULL, cseq, 0);
				return 0;
			}
		}
		else if (strstr (arg[i], "LIVE555"))
		{
			if(sid) sid->timeout = 0;
		}
		else if (strstr (arg[i], "Lavf"))
		{
			if(sid) sid->timeout = 0;
		}
		else if (strncasecmp ("User-Agent:", arg[i], 10) == 0)
			useragent = header_parameter(arg, i);
	
	if((strncasecmp (arg[0], "PLAY", 4) == 0) || (strncasecmp (arg[0], "GET", 3) == 0) || (strncasecmp (arg[0], "SETUP", 5) == 0)) 
	{
		char ra[100];
		int rv;
			
		if (!( sid = get_sid(s->sid)))
		{
			http_response (s, 454, NULL, NULL, cseq, 0);
			return 0;
		}

		if (useragent)
			strncpy(sid->useragent, useragent, 127);

		if ((strncasecmp (arg[0], "PLAY", 3) == 0) || (strncasecmp (arg[0], "GET", 3) == 0))
			if ((rv = start_play (sid, s)) < 0)
			{
				http_response (s, -rv , NULL, NULL, cseq, 0);
				return 0;
			}
		strcpy(ra, inet_ntoa (sid->sa.sin_addr));
		buf[0] = 0;
		if(transport)
		{
			int s_timeout = (sid->timeout ? sid->timeout : opts.timeout_sec) / 1000;
			switch (sid->type)
			{
				case STREAM_RTSP_UDP:
					if (atoi (ra) < 239)
						snprintf (buf, sizeof(buf), "Transport: RTP/AVP;unicast;destination=%s;source=%s;client_port=%d-%d;server_port=%d-%d\r\nSession: %010d;timeout=%d\r\ncom.ses.streamID: %d",
							ra, get_sock_host (s->sock), ntohs (sid->sa.sin_port), ntohs (sid->sa.sin_port) + 1,
//							opts.start_rtp, opts.start_rtp + 1, 
							get_sock_port(sid->rsock), get_sock_port(sid->rtcp),
							get_session_id (s->sid), s_timeout, sid->sid + 1);
					else
						snprintf (buf, sizeof(buf), "Transport: RTP/AVP;multicast;destination=%s;port=%d-%d\r\nSession: %010d;timeout=%d\r\ncom.ses.streamID: %d",
							ra, ntohs (sid->sa.sin_port), ntohs (sid->sa.sin_port) + 1,
							get_session_id (s->sid), s_timeout , sid->sid + 1);
					break;
				case STREAM_RTSP_TCP:
					snprintf(buf, sizeof(buf), "Transport: RTP/AVP/TCP;interleaved=0-1\r\nSession: %010d;timeout=%d\r\ncom.ses.streamID: %d", 
						get_session_id (s->sid), s_timeout, sid->sid + 1);
					break;
			}
		}
		
		if (strncasecmp(arg[0], "PLAY", 4) == 0)
		{
			char *qm = strchr(arg[1], '?');
			if(qm)
				*qm = 0;
			if(buf[0])
				strcat(buf, "\r\n");
			
			snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf) - 1,  "RTP-Info: url=%s;seq=%d;rtptime=%lld\r\nRange: npt=0.000-", arg[1], getTick(),(long long int)(getTickUs()/1000000));
		}
		if(buf[0]==0 && sid->type == STREAM_HTTP)
				snprintf(buf, sizeof(buf), "Content-Type: video/mp2t");
		http_response (s, 200, buf, NULL, cseq, 0);
	}
	else if (strncmp (arg[0], "TEARDOWN", 8) == 0)
	{
		streams *sid;
		buf[0] = 0;
		if(get_sid(s->sid))
			sprintf(buf, "Session: %010d", get_session_id(s->sid));
		close_stream (s->sid);		
		http_response (s, 200, buf, NULL, cseq, 0);
	}
	else
	{
		if (strncmp (arg[0], "DESCRIBE", 8) == 0)
		{
			char sbuf[1000];
			char *rv = NULL;
			rv = describe_streams(s, arg[1], sbuf, sizeof(sbuf));
			if (! rv)
			{
				http_response (s, 404, NULL, NULL, cseq, 0);
				return 0;
			}	
			snprintf(buf, sizeof(buf), "Content-type: application/sdp\r\nContent-Base: rtsp://%s/", get_sock_host(s->sock));
			http_response (s, 200, buf, sbuf, cseq, 0);
				
		}
		else if (strncmp (arg[0], "OPTIONS", 8) == 0)
		{
			http_response (s, 200, public, NULL, cseq, 0);
		}
	}
コード例 #4
0
ファイル: muxing.c プロジェクト: KuMiMusic/FFmpeg
int main(int argc, char **argv)
{
    OutputStream video_st = { 0 }, audio_st = { 0 };
    const char *filename;
    AVOutputFormat *fmt;
    AVFormatContext *oc;
    AVCodec *audio_codec, *video_codec;
    int ret;
    int have_video = 0, have_audio = 0;
    int encode_video = 0, encode_audio = 0;
    AVDictionary *opt = NULL;

    /* Initialize libavcodec, and register all codecs and formats. */
    av_register_all();

    if (argc < 2) {
        printf("usage: %s output_file\n"
               "API example program to output a media file with libavformat.\n"
               "This program generates a synthetic audio and video stream, encodes and\n"
               "muxes them into a file named output_file.\n"
               "The output format is automatically guessed according to the file extension.\n"
               "Raw images can also be output by using '%%d' in the filename.\n"
               "\n", argv[0]);
        return 1;
    }

    filename = argv[1];
    if (argc > 3 && !strcmp(argv[2], "-flags")) {
        av_dict_set(&opt, argv[2]+1, argv[3], 0);
    }

    /* allocate the output media context */
    avformat_alloc_output_context2(&oc, NULL, NULL, filename);
    if (!oc) {
        printf("Could not deduce output format from file extension: using MPEG.\n");
        avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
    }
    if (!oc)
        return 1;

    fmt = oc->oformat;

    /* Add the audio and video streams using the default format codecs
     * and initialize the codecs. */
    if (fmt->video_codec != AV_CODEC_ID_NONE) {
        add_stream(&video_st, oc, &video_codec, fmt->video_codec);
        have_video = 1;
        encode_video = 1;
    }
    if (fmt->audio_codec != AV_CODEC_ID_NONE) {
        add_stream(&audio_st, oc, &audio_codec, fmt->audio_codec);
        have_audio = 1;
        encode_audio = 1;
    }

    /* Now that all the parameters are set, we can open the audio and
     * video codecs and allocate the necessary encode buffers. */
    if (have_video)
        open_video(oc, video_codec, &video_st, opt);

    if (have_audio)
        open_audio(oc, audio_codec, &audio_st, opt);

    av_dump_format(oc, 0, filename, 1);

    /* open the output file, if needed */
    if (!(fmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
        if (ret < 0) {
            fprintf(stderr, "Could not open '%s': %s\n", filename,
                    av_err2str(ret));
            return 1;
        }
    }

    /* Write the stream header, if any. */
    ret = avformat_write_header(oc, &opt);
    if (ret < 0) {
        fprintf(stderr, "Error occurred when opening output file: %s\n",
                av_err2str(ret));
        return 1;
    }

    while (encode_video || encode_audio) {
        /* select the stream to encode */
        if (encode_video &&
                (!encode_audio || av_compare_ts(video_st.next_pts, video_st.st->codec->time_base,
                                                audio_st.next_pts, audio_st.st->codec->time_base) <= 0)) {
            encode_video = !write_video_frame(oc, &video_st);
        } else {
            encode_audio = !write_audio_frame(oc, &audio_st);
        }
    }

    /* Write the trailer, if any. The trailer must be written before you
     * close the CodecContexts open when you wrote the header; otherwise
     * av_write_trailer() may try to use memory that was freed on
     * av_codec_close(). */
    av_write_trailer(oc);

    /* Close each codec. */
    if (have_video)
        close_stream(oc, &video_st);
    if (have_audio)
        close_stream(oc, &audio_st);

    if (!(fmt->flags & AVFMT_NOFILE))
        /* Close the output file. */
        avio_close(oc->pb);

    /* free the stream */
    avformat_free_context(oc);

    return 0;
}
コード例 #5
0
ファイル: sgen-grep-binprot.c プロジェクト: AphasiaRepo/mono
int
main (int argc, char *argv[])
{
	int type;
	void *data = g_malloc0 (MAX_ENTRY_SIZE);
	int num_args = argc - 1;
	int num_nums = 0;
	int num_vtables = 0;
	int i;
	long nums [num_args];
	long vtables [num_args];
	gboolean dump_all = FALSE;
	gboolean pause_times = FALSE;
	gboolean pause_times_stopped = FALSE;
	gboolean pause_times_concurrent = FALSE;
	gboolean pause_times_finish = FALSE;
	gboolean color_output = FALSE;
	long long pause_times_ts = 0;
	const char *input_path = NULL;
	int input_file;
	EntryStream stream;
	unsigned long long entry_index;
	unsigned long long first_entry_to_consider = 0;

	for (i = 0; i < num_args; ++i) {
		char *arg = argv [i + 1];
		char *next_arg = argv [i + 2];
		if (!strcmp (arg, "--all")) {
			dump_all = TRUE;
		} else if (!strcmp (arg, "--pause-times")) {
			pause_times = TRUE;
		} else if (!strcmp (arg, "-v") || !strcmp (arg, "--vtable")) {
			vtables [num_vtables++] = strtoul (next_arg, NULL, 16);
			++i;
		} else if (!strcmp (arg, "-s") || !strcmp (arg, "--start-at")) {
			first_entry_to_consider = strtoull (next_arg, NULL, 10);
			++i;
		} else if (!strcmp (arg, "-c") || !strcmp (arg, "--color")) {
			color_output = TRUE;
		} else if (!strcmp (arg, "-i") || !strcmp (arg, "--input")) {
			input_path = next_arg;
			++i;
		} else {
			nums [num_nums++] = strtoul (arg, NULL, 16);
		}
	}

	if (dump_all)
		assert (!pause_times);
	if (pause_times)
		assert (!dump_all);

	input_file = input_path ? open (input_path, O_RDONLY) : STDIN_FILENO;
	init_stream (&stream, input_file);
	entry_index = 0;
	while ((type = read_entry (&stream, data)) != SGEN_PROTOCOL_EOF) {
		if (entry_index < first_entry_to_consider)
			goto next_entry;
		if (pause_times) {
			switch (type) {
			case PROTOCOL_ID (binary_protocol_world_stopping): {
				PROTOCOL_STRUCT (binary_protocol_world_stopping) *entry = data;
				assert (!pause_times_stopped);
				pause_times_concurrent = FALSE;
				pause_times_finish = FALSE;
				pause_times_ts = entry->timestamp;
				pause_times_stopped = TRUE;
				break;
			}
			case PROTOCOL_ID (binary_protocol_concurrent_finish):
				pause_times_finish = TRUE;
			case PROTOCOL_ID (binary_protocol_concurrent_start):
			case PROTOCOL_ID (binary_protocol_concurrent_update):
				pause_times_concurrent = TRUE;
				break;
			case PROTOCOL_ID (binary_protocol_world_restarted): {
				PROTOCOL_STRUCT (binary_protocol_world_restarted) *entry = data;
				assert (pause_times_stopped);
				printf ("pause-time %d %d %d %lld %lld\n",
						entry->generation,
						pause_times_concurrent,
						pause_times_finish,
						entry->timestamp - pause_times_ts,
						pause_times_ts);
				pause_times_stopped = FALSE;
				break;
			}
			}
		} else {
			int match_indices [num_nums + 1];
			gboolean match = is_always_match (type);
			match_indices [num_nums] = num_nums == 0 ? match_index (NULL, type, data) : BINARY_PROTOCOL_NO_MATCH;
			match = match_indices [num_nums] != BINARY_PROTOCOL_NO_MATCH;
			for (i = 0; i < num_nums; ++i) {
				match_indices [i] = match_index ((gpointer) nums [i], type, data);
				match = match || match_indices [i] != BINARY_PROTOCOL_NO_MATCH;
			}
			if (!match) {
				for (i = 0; i < num_vtables; ++i) {
					if (is_vtable_match ((gpointer) vtables [i], type, data)) {
						match = TRUE;
						break;
					}
				}
			}
			if (match || dump_all)
				printf ("%12lld ", entry_index);
			if (dump_all)
				printf (match ? "* " : "  ");
			if (match || dump_all)
				print_entry (type, data, num_nums, match_indices, color_output);
		}
	next_entry:
		++entry_index;
	}
	close_stream (&stream);
	if (input_path)
		close (input_file);
	g_free (data);

	return 0;
}
コード例 #6
0
ファイル: sample1.cpp プロジェクト: david74chou/fMP4
int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("usage: %s output_file\n"
                       "API example program to output a media file with libavformat.\n"
                       "This program generates a synthetic video stream, encodes and\n"
                       "muxes them into a file named output_file.\n"
                       "The output format is automatically guessed according to the file extension.\n"
                       "Raw images can also be output by using '%%d' in the filename.\n"
                       "\n", argv[0]);
        return 1;
    }

    /* Initialize libavcodec, and register all codecs and formats. */
    av_register_all();

    std::string filename = argv[1];

    /* allocate the output media context */
    AVFormatContext *oc = NULL;
    avformat_alloc_output_context2(&oc, NULL, "mp4", NULL);
    if (!oc) {
        printf("fail to generate mp4 format context");
        return 1;
    }

    /* Add the video streams using the default format codecs and initialize the codecs. */
    OutputStream video_st = {0};
    AVCodec *video_codec = NULL;
    if (oc->oformat->video_codec != AV_CODEC_ID_NONE) {
        add_stream(&video_st, oc, &video_codec, oc->oformat->video_codec);
    }

    /* Now that all the parameters are set, we can open the
     * video codecs and allocate the necessary encode buffers. */
    AVDictionary *opt = NULL;
    if (video_codec != NULL)
        open_video(oc, video_codec, &video_st, opt);

    av_dump_format(oc, 0, filename.c_str(), 1);

    /* open the output file, if needed */
    int ret = 0;
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
        if ((ret = avio_open(&oc->pb, filename.c_str(), AVIO_FLAG_WRITE)) < 0) {
            fprintf(stderr, "Could not open '%s': %s\n", filename.c_str(), av_err2str(ret));
            return 1;
        }
    }

    /* Write the stream header, if any. */
    AVDictionary *movflags = NULL;
    av_dict_set(&movflags, "movflags", "empty_moov+default_base_moof+frag_keyframe", 0);
    if ((ret = avformat_write_header(oc, &movflags)) < 0) {
        fprintf(stderr, "Error occurred when opening output file: %s\n", av_err2str(ret));
        return 1;
    }
    av_dict_free(&movflags);

    // Generate raw video frame, encode them and mux into container
    bool encode_video = true;
    while (encode_video) {
        encode_video = write_video_frame(oc, &video_st);
    }

    /* Write the trailer, if any. The trailer must be written before you
     * close the CodecContexts open when you wrote the header; otherwise
     * av_write_trailer() may try to use memory that was freed on
     * av_codec_close(). */
    av_write_trailer(oc);

    /* Close each codec. */
    if (video_codec != NULL)
        close_stream(oc, &video_st);

    if (!(oc->oformat->flags & AVFMT_NOFILE))
        /* Close the output file. */
        avio_closep(&oc->pb);

    /* free the stream */
    avformat_free_context(oc);

    return 0;
}
コード例 #7
0
ファイル: detok.c プロジェクト: mwilbur/openbios
int main(int argc, char **argv)
{
	int c;
	const char *optstring = "vhanof:?";
	int linenumbers = 0;
	bool add_vfcodes = FALSE;
	char *vfc_filnam = NULL;

	while (1) {
#ifdef __GLIBC__
		int option_index = 0;
		static struct option long_options[] = {
			{"verbose", 0, 0, 'v'},
			{"help", 0, 0, 'h'},
			{"all", 0, 0, 'a'},
			{"linenumbers", 0, 0, 'n'},
			{"offsets", 0, 0, 'o'},
			{"fcodes", 1, 0, 'f'},
			{0, 0, 0, 0}
		};

		c = getopt_long(argc, argv, optstring,
				long_options, &option_index);
#else
		c = getopt(argc, argv, optstring);
#endif
		if (c == -1)
			break;

		switch (c) {
		case 'v':
			verbose = TRUE;
			break;
		case 'a':
			decode_all = TRUE;
			break;
		case 'n':
			linenumbers |= 1;
			show_linenumbers = TRUE;
			break;
		case 'o':
			linenumbers |= 2;
			show_linenumbers = TRUE;
			show_offsets = TRUE;
			break;
		case 'f':
			add_vfcodes = TRUE;
			vfc_filnam = optarg;
			break;
		case 'h':
		case '?':
			print_copyright(TRUE);
			usage(argv[0]);
			return 0;
		default:
			print_copyright(TRUE);
			printf("%s: unknown option.\n", argv[0]);
			usage(argv[0]);
			return 1;
		}
	}

	if (verbose)
		print_copyright(FALSE);

	if (linenumbers > 2)
		printremark
		    ("Line numbers will be disabled in favour of offsets.\n");

	if (optind >= argc) {
		print_copyright(TRUE);
		printf("%s: filename missing.\n", argv[0]);
		usage(argv[0]);
		return 1;
	}

	init_dictionary();

	if (add_vfcodes) {
		if (add_fcodes_from_list(vfc_filnam)) {
			freeze_dictionary();
		}
	}

	while (optind < argc) {

		if (init_stream(argv[optind])) {
			printf("Could not open file \"%s\".\n", argv[optind]);
			optind++;
			continue;
		}
		detokenize();
		close_stream();

		optind++;
		reset_dictionary();
	}

	printf("\n");

	return 0;
}
コード例 #8
0
ファイル: script.c プロジェクト: rseabra/util-linux
void
dooutput(FILE *timingfd) {
	ssize_t cc;
	time_t tvec;
	char obuf[BUFSIZ];
	struct timeval tv;
	double oldtime=time(NULL), newtime;
	int flgs = 0;
	ssize_t wrt;
	ssize_t fwrt;

	close(STDIN_FILENO);
#ifdef HAVE_LIBUTIL
	close(slave);
#endif
	tvec = time((time_t *)NULL);
	my_strftime(obuf, sizeof obuf, "%c\n", localtime(&tvec));
	fprintf(fscript, _("Script started on %s"), obuf);

	do {
		if (die && flgs == 0) {
			/* ..child is dead, but it doesn't mean that there is
			 * nothing in buffers.
			 */
			flgs = fcntl(master, F_GETFL, 0);
			if (fcntl(master, F_SETFL, (flgs | O_NONBLOCK)) == -1)
				break;
		}
		if (tflg)
			gettimeofday(&tv, NULL);

		errno = 0;
		cc = read(master, obuf, sizeof (obuf));

		if (die && errno == EINTR && cc <= 0)
			/* read() has been interrupted by SIGCHLD, try it again
			 * with O_NONBLOCK
			 */
			continue;
		if (cc <= 0)
			break;
		if (tflg) {
			newtime = tv.tv_sec + (double) tv.tv_usec / 1000000;
			fprintf(timingfd, "%f %zd\n", newtime - oldtime, cc);
			oldtime = newtime;
		}
		wrt = write(STDOUT_FILENO, obuf, cc);
		if (wrt < 0) {
			warn (_("write failed"));
			fail();
		}
		fwrt = fwrite(obuf, 1, cc, fscript);
		if (fwrt < cc) {
			warn (_("cannot write script file"));
			fail();
		}
		if (fflg)
			fflush(fscript);
	} while(1);

	if (flgs)
		fcntl(master, F_SETFL, flgs);
	if (close_stream(timingfd) != 0)
		errx(EXIT_FAILURE, _("write error"));
	done();
}
コード例 #9
0
ファイル: wall.c プロジェクト: dankamongmen/util-linux
char *
makemsg(char *fname, size_t *mbufsize, int print_banner)
{
	register int ch, cnt;
	struct tm *lt;
	struct passwd *pw;
	struct stat sbuf;
	time_t now;
	FILE *fp;
	char *p, *whom, *where, *hostname, *lbuf, *tmpname, *mbuf;
	long line_max;

	hostname = xmalloc(sysconf(_SC_HOST_NAME_MAX) + 1);
	line_max = sysconf(_SC_LINE_MAX);
	lbuf = xmalloc(line_max);

	if ((fp = xfmkstemp(&tmpname, NULL)) == NULL)
		err(EXIT_FAILURE, _("can't open temporary file"));
	unlink(tmpname);
	free(tmpname);

	if (print_banner == TRUE) {
		if (!(whom = getlogin()) || !*whom)
			whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
		if (!whom) {
			whom = "someone";
			warn(_("cannot get passwd uid"));
		}
		where = ttyname(STDOUT_FILENO);
		if (!where) {
			where = "somewhere";
			warn(_("cannot get tty name"));
		}
		gethostname(hostname, sizeof(hostname));
		time(&now);
		lt = localtime(&now);

		/*
		 * all this stuff is to blank out a square for the message;
		 * we wrap message lines at column 79, not 80, because some
		 * terminals wrap after 79, some do not, and we can't tell.
		 * Which means that we may leave a non-blank character
		 * in column 80, but that can't be helped.
		 */
		/* snprintf is not always available, but the sprintf's here
		   will not overflow as long as %d takes at most 100 chars */
		fprintf(fp, "\r%79s\r\n", " ");
		sprintf(lbuf, _("Broadcast Message from %s@%s"),
			      whom, hostname);
		fprintf(fp, "%-79.79s\007\007\r\n", lbuf);
		sprintf(lbuf, "        (%s) at %d:%02d ...",
			      where, lt->tm_hour, lt->tm_min);
		fprintf(fp, "%-79.79s\r\n", lbuf);
	}
	fprintf(fp, "%79s\r\n", " ");

	free(hostname);

	if (fname) {
		/*
		 * When we are not root, but suid or sgid, refuse to read files
		 * (e.g. device files) that the user may not have access to.
		 * After all, our invoker can easily do "wall < file"
		 * instead of "wall file".
		 */
		uid_t uid = getuid();
		if (uid && (uid != geteuid() || getgid() != getegid()))
			errx(EXIT_FAILURE, _("will not read %s - use stdin."),
			     fname);

		if (!freopen(fname, "r", stdin))
			err(EXIT_FAILURE, _("cannot open file %s"), fname);
	}

	while (fgets(lbuf, line_max, stdin)) {
		for (cnt = 0, p = lbuf; (ch = *p) != '\0'; ++p, ++cnt) {
			if (cnt == 79 || ch == '\n') {
				for (; cnt < 79; ++cnt)
					putc(' ', fp);
				putc('\r', fp);
				putc('\n', fp);
				cnt = 0;
			}
			if (ch != '\n')
				carefulputc(ch, fp);
		}
	}
	fprintf(fp, "%79s\r\n", " ");

	free(lbuf);
	rewind(fp);

	if (fstat(fileno(fp), &sbuf))
		err(EXIT_FAILURE, _("fstat failed"));

	*mbufsize = (size_t) sbuf.st_size;
	mbuf = xmalloc(*mbufsize);

	if (fread(mbuf, 1, *mbufsize, fp) != *mbufsize)
		err(EXIT_FAILURE, _("fread failed"));

	if (close_stream(fp) != 0)
		errx(EXIT_FAILURE, _("write error"));
	return mbuf;
}
コード例 #10
0
ファイル: bvh_stream.cpp プロジェクト: scholli/lamure
bvh_stream::
~bvh_stream() {
    close_stream(false);
}
コード例 #11
0
ファイル: bvh_stream.cpp プロジェクト: scholli/lamure
void bvh_stream::
write_bvh(const std::string& filename, bvh& bvh, const bool intermediate) {

   open_stream(filename, bvh_stream_type::BVH_STREAM_OUT);

   if (type_ != BVH_STREAM_OUT) {
       throw std::runtime_error(
           "PLOD: bvh_stream::Failed to append tree to: " + filename_);
   }
   if (!file_.is_open()) {
       throw std::runtime_error(
           "PLOD: bvh_stream::Failed to append tree to: " + filename_);
   }
   
   file_.seekp(0, std::ios::beg);

   bvh_file_seg seg;
   seg.major_version_ = 1;
   seg.minor_version_ = 1;
   seg.reserved_ = 0;

   write(seg);

   //Note: This is the preprocessing library version of the file writer!

   bvh_tree_seg tree;
   tree.segment_id_ = num_segments_++;
   tree.depth_ = bvh.depth();
   tree.num_nodes_ = bvh.nodes().size();
   tree.fan_factor_ = bvh.fan_factor();
   tree.max_surfels_per_node_ = bvh.max_surfels_per_node();
   tree.serialized_surfel_size_ = serialized_surfel::get_size();
   tree.reserved_0_ = 0;
   tree.state_ = (bvh_stream::bvh_tree_state)bvh.state();
   tree.reserved_1_ = 0;
   tree.reserved_2_ = 0;
   tree.translation_.x_ = bvh.translation().x;
   tree.translation_.y_ = bvh.translation().y;
   tree.translation_.z_ = bvh.translation().z;
   tree.reserved_3_ = 0;

   write(tree);

   const auto& bvh_nodes = bvh.nodes();
   for (uint32_t i = 0; i < bvh_nodes.size(); ++i) {
       const auto& bvh_node = bvh_nodes[i];
       bvh_node_seg node;
       node.segment_id_ = num_segments_++;
       node.node_id_ = i;
       node.centroid_.x_ = bvh_node.centroid().x;
       node.centroid_.y_ = bvh_node.centroid().y;
       node.centroid_.z_ = bvh_node.centroid().z;
       node.depth_ = bvh_node.depth();
       node.reduction_error_ = bvh_node.reduction_error();
       node.avg_surfel_radius_ = bvh_node.avg_surfel_radius();
       node.visibility_ = (bvh_node_visibility)bvh_node.visibility();
       node.max_surfel_radius_deviation_ = bvh_node.max_surfel_radius_deviation();
       node.bounding_box_.min_.x_ = bvh_node.get_bounding_box().min().x;
       node.bounding_box_.min_.y_ = bvh_node.get_bounding_box().min().y;
       node.bounding_box_.min_.z_ = bvh_node.get_bounding_box().min().z;
       node.bounding_box_.max_.x_ = bvh_node.get_bounding_box().max().x;
       node.bounding_box_.max_.y_ = bvh_node.get_bounding_box().max().y;
       node.bounding_box_.max_.z_ = bvh_node.get_bounding_box().max().z;

       write(node);
   }

   if (intermediate) {
       bvh_tree_extension_seg tree_ext;
       tree_ext.segment_id_ = num_segments_++;
       tree_ext.working_directory_.string_ = "DEADBEEF";
       tree_ext.working_directory_.length_ = tree_ext.working_directory_.string_.length();
       tree_ext.filename_.string_ = bvh.base_path().string();
       tree_ext.filename_.length_ = tree_ext.filename_.string_.length();
       tree_ext.num_disk_accesses_ = 0;

       for (uint32_t i = 0; i < bvh_nodes.size(); ++i) {
           const auto& bvh_node = bvh_nodes[i];
           bvh_node_extension_seg node_ext;
           node_ext.segment_id_ = num_segments_++;
           node_ext.node_id_ = bvh_node.node_id();
           node_ext.empty_ = 1;
           node_ext.reserved_ = 0;
           node_ext.disk_array_.disk_access_ref_ = 0;
           node_ext.disk_array_.reserved_ = 0;
           node_ext.disk_array_.offset_ = 0;
           node_ext.disk_array_.length_ = 0;

           //only OOC nodes are saved, IC nodes are considered empty

           if (bvh_node.is_out_of_core()) {
               node_ext.empty_ = 0;

               bool disk_access_found = false;
               for (uint32_t k = 0; k < tree_ext.num_disk_accesses_; ++k) {
                   if (tree_ext.disk_accesses_.size() < k) {
                       throw std::runtime_error(
                           "PLOD: bvh_stream::Stream corrupt");
                   }
                   if (tree_ext.disk_accesses_[k].string_ == bvh_node.disk_array().file()->file_name()) {
                       node_ext.disk_array_.disk_access_ref_ = k;
                       disk_access_found = true;
                       break;
                   }
               }
               
               if (!disk_access_found) {
                  bvh_string disk_access;
                  disk_access.string_ = bvh_node.disk_array().file()->file_name();
                  disk_access.length_ = disk_access.string_.length();
                  tree_ext.disk_accesses_.push_back(disk_access);
                  node_ext.disk_array_.disk_access_ref_ = tree_ext.num_disk_accesses_;
                  ++tree_ext.num_disk_accesses_;
               }

               node_ext.disk_array_.offset_ = bvh_node.disk_array().offset();
               node_ext.disk_array_.length_ = bvh_node.disk_array().length();
               
           }

           write(node_ext);
       }

       write(tree_ext);
   }

   close_stream(false);

}
コード例 #12
0
ファイル: bvh_stream.cpp プロジェクト: scholli/lamure
void bvh_stream::
read_bvh(const std::string& filename, bvh& bvh) {
 
    open_stream(filename, bvh_stream_type::BVH_STREAM_IN);

    if (type_ != BVH_STREAM_IN) {
        throw std::runtime_error(
            "PLOD: bvh_stream::Failed to read bvh from: " + filename_);
    }
    if (!file_.is_open()) {
         throw std::runtime_error(
            "PLOD: bvh_stream::Failed to read bvh from: " + filename_);
    }
   
    //scan stream
    file_.seekg(0, std::ios::end);
    size_t filesize = (size_t)file_.tellg();
    file_.seekg(0, std::ios::beg);

    num_segments_ = 0;

    bvh_tree_seg tree;
    bvh_tree_extension_seg tree_ext;
    std::vector<bvh_node_seg> nodes;
    std::vector<bvh_node_extension_seg> nodes_ext;
    uint32_t tree_id = 0;
    uint32_t tree_ext_id = 0;
    uint32_t node_id = 0;
    uint32_t node_ext_id = 0;


    //go through entire stream and fetch the segments
    while (true) {
        bvh_sig sig;
        sig.deserialize(file_);
        if (sig.signature_[0] != 'B' ||
            sig.signature_[1] != 'V' ||
            sig.signature_[2] != 'H' ||
            sig.signature_[3] != 'X') {
             throw std::runtime_error(
                 "PLOD: bvh_stream::Invalid magic encountered: " + filename_);
        }
            
        size_t anchor = (size_t)file_.tellg();

        switch (sig.signature_[4]) {

            case 'F': { //"BVHXFILE"
                bvh_file_seg seg;
                seg.deserialize(file_);
                break;
            }
            case 'T': { 
                switch (sig.signature_[5]) {
                    case 'R': { //"BVHXTREE"
                        tree.deserialize(file_);
                        ++tree_id;
                        break;
                    }
                    case 'E': { //"BVHXTEXT"
                        tree_ext.deserialize(file_);
                        ++tree_ext_id;
                        break;                     
                    }
                    default: {
                        throw std::runtime_error(
                            "PLOD: bvh_stream::Stream corrupt -- Invalid segment encountered");
                        break;
                    }
                }
                break;
            }
            case 'N': { 
                switch (sig.signature_[5]) {
                    case 'O': { //"BVHXNODE"
                        bvh_node_seg node;
                        node.deserialize(file_);
                        nodes.push_back(node);
                        if (node_id != node.node_id_) {
                            throw std::runtime_error(
                                "PLOD: bvh_stream::Stream corrupt -- Invalid node order");
                        }
                        ++node_id;
                        break;
                    }
                    case 'E': { //"BVHXNEXT"
                        bvh_node_extension_seg node_ext;
                        node_ext.deserialize(file_);
                        nodes_ext.push_back(node_ext);
                        if (node_ext_id != node_ext.node_id_) {
                            throw std::runtime_error(
                                "PLOD: bvh_stream::Stream corrupt -- Invalid node extension order");
                        }
                        ++node_ext_id;
                        break;
                    }
                    default: {
                        throw std::runtime_error(
                            "PLOD: bvh_stream::Stream corrupt -- Invalid segment encountered");
                        break;
                    }
                }
                break;
            }
            default: {
                throw std::runtime_error(
                    "PLOD: bvh_stream::file corrupt -- Invalid segment encountered");
                break;
            }
        }

        if (anchor + sig.allocated_size_ < filesize) {
            file_.seekg(anchor + sig.allocated_size_, std::ios::beg);
        }
        else {
            break;
        }

    }

    close_stream(false);

    if (tree_id != 1) {
       throw std::runtime_error(
           "PLOD: bvh_stream::Stream corrupt -- Invalid number of bvh segments");
    }   

    if (tree_ext_id > 1) {
       throw std::runtime_error(
           "PLOD: bvh_stream::Stream corrupt -- Invalid number of bvh extensions");
    }    

    //Note: This is the preprocessing library version of the file reader!

    //setup bvh
    bvh.set_depth(tree.depth_);
    bvh.set_fan_factor(tree.fan_factor_);
    bvh.set_max_surfels_per_node(tree.max_surfels_per_node_);
    scm::math::vec3f translation(tree.translation_.x_,
                                 tree.translation_.y_,
                                 tree.translation_.z_);
    bvh.set_translation(vec3r(translation));
    if (tree.num_nodes_ != node_id) {
        throw std::runtime_error(
            "PLOD: bvh_stream::Stream corrupt -- Invalid number of node segments");
    }
    if (tree_ext_id > 0) {
        if (tree.num_nodes_ != node_ext_id) {
            throw std::runtime_error(
                "PLOD: bvh_stream::Stream corrupt -- Invalid number of node extensions");
        }
    }
    
    std::vector<shared_file> level_temp_files;
    
    bvh::state_type current_state = static_cast<bvh::state_type>(tree.state_);
    
    //check if intermediate state
    bool interm_state = current_state == bvh::state_type::after_downsweep
      || current_state == bvh::state_type::after_upsweep;

    boost::filesystem::path base_path;
    if (interm_state) {
        if (tree_ext_id != 1) {
            throw std::runtime_error(
                "PLOD: bvh_stream::Stream corrupt -- Stream is missing tree extension");
        }
        //working_directory = tree_ext.working_directory_.string_;
        //basename_ = boost::filesystem::path(tree_ext.filename_.string_);
        base_path = boost::filesystem::path(tree_ext.filename_.string_);

        //setup level temp files
        for (uint32_t i = 0; i < tree_ext.num_disk_accesses_; ++i) {
             level_temp_files.push_back(std::make_shared<file>());
             level_temp_files.back()->open(tree_ext.disk_accesses_[i].string_, false);
        }
    }
    else {
        base_path = boost::filesystem::canonical(boost::filesystem::path(filename));
        base_path.replace_extension("");
    }
    bvh.set_base_path(base_path);

    //setup nodes
    std::vector<bvh_node> bvh_nodes(tree.num_nodes_);

    for (uint32_t i = 0; i < tree.num_nodes_; ++i) {
       const auto& node = nodes[i];

       if (i != node.node_id_) {
           throw std::runtime_error(
               "PLOD: bvh_stream::Stream corrupt -- Invalid node ordering");
       }

       scm::math::vec3f centroid(node.centroid_.x_,
                                 node.centroid_.y_,
                                 node.centroid_.z_);
       scm::math::vec3f box_min(node.bounding_box_.min_.x_,
                                node.bounding_box_.min_.y_,
                                node.bounding_box_.min_.z_);
       scm::math::vec3f box_max(node.bounding_box_.max_.x_,
                                node.bounding_box_.max_.y_,
                                node.bounding_box_.max_.z_);

       if (interm_state) {
           const auto& node_ext = nodes_ext[i];
           if (i != node_ext.node_id_) {
               throw std::runtime_error(
                   "PLOD: bvh_stream::Stream corrupt -- Invalid extension ordering");
           }
           
           if (node_ext.empty_ == 1) {
               bvh_nodes[i] = bvh_node(node.node_id_, node.depth_, bounding_box(vec3r(box_min), vec3r(box_max)));
           }
           else {
               const auto& disk_array = node_ext.disk_array_;
               surfel_disk_array sdarray = surfel_disk_array(level_temp_files[disk_array.disk_access_ref_],
                                                                   disk_array.offset_,
                                                                   disk_array.length_);
               bvh_nodes[i] = bvh_node(node.node_id_, node.depth_, bounding_box(vec3r(box_min), vec3r(box_max)), sdarray);
           }
       }
       else {
           //init empty nodes. We don't use surfelDIskArray
           //because we deal with serialized data
           bvh_nodes[i] = bvh_node(node.node_id_, node.depth_, bounding_box(vec3r(box_min), vec3r(box_max)));
       }

       //set node params
       bvh_nodes[i].set_reduction_error(node.reduction_error_);
       bvh_nodes[i].set_centroid(vec3r(centroid));
       bvh_nodes[i].set_avg_surfel_radius(node.avg_surfel_radius_);
       bvh_nodes[i].set_visibility((bvh_node::node_visibility)node.visibility_);
       bvh_nodes[i].set_max_surfel_radius_deviation(node.max_surfel_radius_deviation_);
    }

    bvh.set_first_leaf(tree.num_nodes_ - std::pow(tree.fan_factor_, tree.depth_));
    bvh.set_state(current_state);
    bvh.set_nodes(bvh_nodes);

}
コード例 #13
0
ファイル: capture.c プロジェクト: hmrten/l2cap
int do_capture(void)
{
	pcap_t *adhandle;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program fcode;
	char buf[512];
	struct pcap_pkthdr *header;
	const u_char *data;
	int res;
	int svindex=0;

	if ((adhandle=pcap_open_live(config.device, 65536, 1, 1000, errbuf)) == NULL) {
		//MessageBox(0, errbuf, "Error", MB_OK);
		log_msg("dbg", "pcap_open_live failed opening device: %s\r\n", config.device);
		//pcap_freealldevs(alldevs);
		return -2;
	}

	if (strcmp("Chronos", config.server) == 0) {
		svindex = 0;
	} else if (strcmp("Naia", config.server) == 0) {
		svindex = 1;
	}

	sprintf(buf, "tcp and ip host %s", _servers[svindex]);

	if (pcap_compile(adhandle, &fcode, buf, 1, 0xffffffff) < 0) {
		//MessageBox(0, "Error compiling pcap filter.", "Error", MB_OK);
		log_msg("dbg", "error compiling pcap filter.\r\n");
		pcap_close(adhandle);
		//pcap_freealldevs(alldevs);
		return -3;
	}

	if (pcap_setfilter(adhandle, &fcode) < 0) {
		//MessageBox(0, "Error setting pcap filter.", "Error", MB_OK);
		log_msg("dbg", "error setting pcap filter.\r\n");
		pcap_close(adhandle);
		//pcap_freealldevs(alldevs);
		return -4;		
	}

	log_msg("dbg", "Listening on %s...\r\n", config.device);

	//pcap_freealldevs(alldevs);

	stopcapturing = 0;

	_svstream = open_stream();
	_clstream = open_stream();

	_isfirst = 1;

	_svbufsize = 0;
	_clbufsize = 0;

	while ((res=pcap_next_ex(adhandle, &header, &data)) >= 0 && !stopcapturing) {
		if (res == 0) {
			continue;
		}
		
		handle_raw_packet(header, data); 
	}

	log_msg("dbg", "Stopped capture.\r\n");

	close_stream(_svstream);
	close_stream(_clstream);
	_svstream = 0;
	_clstream = 0;

	pcap_close(adhandle);

	return 0;
}
コード例 #14
0
	// it is running in decoder thread
	void as_netstream::run()
	{
		set_status(status, playStart);

		m_start_time = now();
		m_video_time = 0;
		
		m_status = PLAY;
		while (m_status == PLAY || m_status == PAUSE)
		{
			if (m_status == PAUSE)
			{
				double paused = now();
				m_decoder.wait();
				m_start_time += now() - paused;
				continue;
			}

			// seek request
			if (m_seek_time >= 0)
			{
				int64 timestamp = (int64) (m_seek_time * AV_TIME_BASE);
				int flags = m_seek_time > m_video_time ? 0 : AVSEEK_FLAG_BACKWARD;
				int ret = av_seek_frame(m_FormatCtx, -1, timestamp, flags);
				if (ret == 0)
				{
					m_aq.clear();
					m_vq.clear();
					m_start_time += m_video_time - m_seek_time;
					m_video_time = m_seek_time;
					set_status(status, seekNotify);
				}
				else
				{
					set_status(error, seekInvalidTime);
				}
				m_seek_time = -1;
			}

			if (get_bufferlength() < m_buffer_time)
			{
				//printf("m_buffer_length=%f, queue_size=%d\n", get_bufferlength(), m_vq.size()); 

				AVPacket pkt;
				int rc = av_read_frame(m_FormatCtx, &pkt);
				if (rc < 0)
				{
					if (m_vq.size() == 0)
					{
						break;
					}
				}
				else
				{
					if (pkt.stream_index == m_video_index)
					{
						m_vq.push(new av_packet(pkt));
					}
					else
					if (pkt.stream_index == m_audio_index)
					{
						if (get_sound_handler())
						{
							m_aq.push(new av_packet(pkt));
						}
					}
					else
					{
						continue;
					}
				}
			}

			// skip expired video frames
			double current_time = now() - m_start_time;
			while (current_time >= m_video_time)
			{
				gc_ptr<av_packet> packet;
				if (m_vq.pop(&packet))
				{
					const AVPacket& pkt = packet->get_packet();

					// update video clock with pts, if present
					if (pkt.dts > 0)
					{
						m_video_time = av_q2d(m_video_stream->time_base) * pkt.dts;
					}
					m_video_time += av_q2d(m_video_stream->codec->time_base);	// +frame_delay

					set_video_data(decode_video(pkt));
				}
				else
				{
					// no packets in queue
//					set_status("status", "NetStream.Buffer.Empty");
					break;
				}
			}

			// Don't hog the CPU.
			// Queues have filled, video frame have shown
			// now it is possible and to have a rest

			int delay = (int) (1000 * (m_video_time - current_time));
			
			// hack, adjust m_start_time after seek
			if (delay > 50)
			{
				m_start_time -= (m_video_time - current_time);
				current_time = now() - m_start_time;
				delay = (int) (1000 * (m_video_time - current_time));
			}

			assert(delay <= 50);

			if (delay > 0)
			{
				if (get_bufferlength() >= m_buffer_time)
				{
//					set_status("status", "NetStream.Buffer.Full");
					tu_timer::sleep(delay);
				}
//				printf("current_time=%f, video_time=%f, delay=%d\n", current_time, m_video_time, delay);
			}
		}

		sound_handler* sound = get_sound_handler();
		if (sound)
		{
			sound->detach_aux_streamer(this);
		}

		close_stream();

		set_status(status, playStop);
		m_status = STOP;
	}
コード例 #15
0
ファイル: windows_specific.cpp プロジェクト: glguida/polyml
Handle OS_spec_dispatch_c(TaskData *taskData, Handle args, Handle code)
{
    unsigned c = get_C_unsigned(taskData, DEREFWORD(code));
    switch (c)
    {
    case 0: /* Return our OS type.  Not in any structure. */
        return Make_arbitrary_precision(taskData, 1); /* 1 for Windows. */

        /* Windows-specific functions. */
    case 1000: /* execute */
        return execute(taskData, args);

    case 1001: /* Get input stream as text. */
        return openProcessHandle(taskData, args, TRUE, TRUE);

    case 1002: /* Get output stream as text. */
        return openProcessHandle(taskData, args, FALSE, TRUE);

    case 1003: /* Get input stream as binary. */
        return openProcessHandle(taskData, args, TRUE, FALSE);

    case 1004: /* Get output stream as binary. */
        return openProcessHandle(taskData, args, FALSE, FALSE);

    case 1005: /* Get result of process. */
        {
            PHANDLETAB hnd = get_handle(DEREFWORD(args), HE_PROCESS);
            if (hnd == 0)
                raise_syscall(taskData, "Process is closed", EINVAL);
            // Close the streams. Either of them may have been
            // passed to the stream package.
            if (hnd->entry.process.hInput != INVALID_HANDLE_VALUE)
                CloseHandle(hnd->entry.process.hInput);
            hnd->entry.process.hInput = INVALID_HANDLE_VALUE;
            if (hnd->entry.process.hEvent)
                CloseHandle(hnd->entry.process.hEvent);
            hnd->entry.process.hEvent = NULL;
            if (hnd->entry.process.readToken)
            {
                PIOSTRUCT strm =
                    get_stream(hnd->entry.process.readToken);
                if (strm != NULL) close_stream(strm);
            }
            hnd->entry.process.readToken = 0;
            if (hnd->entry.process.hOutput != INVALID_HANDLE_VALUE)
                CloseHandle(hnd->entry.process.hOutput);
            hnd->entry.process.hOutput = INVALID_HANDLE_VALUE;
            if (hnd->entry.process.writeToken)
            {
                PIOSTRUCT strm =
                    get_stream(hnd->entry.process.writeToken);
                if (strm != NULL) close_stream(strm);
            }
            hnd->entry.process.writeToken = 0;

            // See if it's finished.
            while (true) {
                DWORD dwResult;
                if (GetExitCodeProcess(hnd->entry.process.hProcess, &dwResult) == 0)
                    raise_syscall(taskData, "GetExitCodeProcess failed",
                            -(int)GetLastError());
                if (dwResult != STILL_ACTIVE) {
                    /* Finished - return the result. */
                    /* Note: we haven't closed the handle because we might want to ask
                       for the result again.  We only close it when we've garbage-collected
                       the token.  Doing this runs the risk of running out of handles.
                       Maybe change it and remember the result in ML. */
                    return Make_arbitrary_precision(taskData, dwResult);
                }
                // Block and try again.
                WaitHandle waiter(hnd->entry.process.hProcess);
                processes->ThreadPauseForIO(taskData, &waiter);
            }
        }

    case 1006: /* Return a constant. */
        {
            unsigned i = get_C_unsigned(taskData, DEREFWORD(args));
            if (i >= sizeof(winConstVec)/sizeof(winConstVec[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return Make_arbitrary_precision(taskData, winConstVec[i]);
        }

        /* Registry functions. */
    case 1007: // Open a key within one of the roots.
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            // This should only ever happen as a result of a fault in
            // the Windows structure.
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return openRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]);
        }

    case 1008: // Open a subkey of an opened key.
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return openRegistryKey(taskData, args, hnd->entry.hKey);
        }

    case 1009: // Create a subkey within one of the roots.
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            // This should only ever happen as a result of a fault in
            // the Windows structure.
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return createRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]);
        }

    case 1010: // Create a subkey within an opened key.
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return createRegistryKey(taskData, args, hnd->entry.hKey);
        }

    case 1011: // Close a registry handle.
        {
            PHANDLETAB hnd = get_handle(DEREFWORD(args), HE_REGISTRY);
            if (hnd != 0) close_handle(hnd);
            return Make_arbitrary_precision(taskData, 0);
        }

    case 1012: // Get a value
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            // This should only ever happen as a result of a fault in
            // the Windows structure.
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return queryRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]);
        }

    case 1013: // Get a value
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return queryRegistryKey(taskData, args, hnd->entry.hKey);
        }

    case 1014: // Delete a subkey
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            // This should only ever happen as a result of a fault in
            // the Windows structure.
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return deleteRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]);
        }

    case 1015: // Delete a subkey
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return deleteRegistryKey(taskData, args, hnd->entry.hKey);
        }

    case 1016: // Set a value
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            // This should only ever happen as a result of a fault in
            // the Windows structure.
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return setRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]);
        }

    case 1017: // Set a value
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return setRegistryKey(taskData, args, hnd->entry.hKey);
        }

    case 1018: // Enumerate a key in the predefined keys
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return enumerateRegistry(taskData, args, hkPredefinedKeyTab[keyIndex], TRUE);
        }

    case 1019: // Enumerate a key in an opened key
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return enumerateRegistry(taskData, args, hnd->entry.hKey, TRUE);
        }

    case 1020: // Enumerate a value in the predefined keys
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return enumerateRegistry(taskData, args, hkPredefinedKeyTab[keyIndex], FALSE);
        }

    case 1021: // Enumerate a value in an opened key
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return enumerateRegistry(taskData, args, hnd->entry.hKey, FALSE);
        }

    case 1022: // Delete a value
        {
            unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0));
            // This should only ever happen as a result of a fault in
            // the Windows structure.
            if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0]))
                raise_syscall(taskData, "Invalid index", 0);
            return deleteRegistryValue(taskData, args, hkPredefinedKeyTab[keyIndex]);
        }

    case 1023: // Delete a value
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY);
            if (hnd == 0)
                raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE);
            return deleteRegistryValue(taskData, args, hnd->entry.hKey);
        }


    case 1030: // Convert UTC time values to local time. -- No longer used??
        {
            FILETIME ftUTC, ftLocal;
            /* Get the file time. */
            getFileTimeFromArb(taskData, DEREFWORDHANDLE(args), &ftUTC);
            if (! FileTimeToLocalFileTime(&ftUTC, &ftLocal))
                raise_syscall(taskData, "FileTimeToLocalFileTime failed",
                        -(int)GetLastError());
            return Make_arb_from_Filetime(taskData, ftLocal);
        }

    case 1031: // Convert local time values to UTC. -- No longer used??
        {
            FILETIME ftUTC, ftLocal;
            /* Get the file time. */
            getFileTimeFromArb(taskData, DEREFWORDHANDLE(args), &ftLocal);
            if (! LocalFileTimeToFileTime(&ftLocal, &ftUTC))
                raise_syscall(taskData, "LocalFileTimeToFileTime failed",
                        -(int)GetLastError());
            return Make_arb_from_Filetime(taskData, ftUTC);
        }

    case 1032: // Get volume information.
        {
            TCHAR rootName[MAX_PATH], volName[MAX_PATH], sysName[MAX_PATH];
            DWORD dwVolSerial, dwMaxComponentLen, dwFlags;
            Handle volHandle, sysHandle, serialHandle, maxCompHandle;
            Handle resultHandle;
            POLYUNSIGNED length = Poly_string_to_C(DEREFWORD(args), rootName, MAX_PATH);
            if (length > MAX_PATH)
                raise_syscall(taskData, "Root name too long", ENAMETOOLONG);
            
            if (!GetVolumeInformation(rootName, volName, MAX_PATH,
                    &dwVolSerial, &dwMaxComponentLen, &dwFlags,
                    sysName, MAX_PATH))
                raise_syscall(taskData, "GetVolumeInformation failed",
                    -(int)GetLastError());
            volHandle = SAVE(C_string_to_Poly(taskData, volName));
            sysHandle = SAVE(C_string_to_Poly(taskData, sysName));
            serialHandle = Make_arbitrary_precision(taskData, dwVolSerial);
            maxCompHandle = Make_arbitrary_precision(taskData, dwMaxComponentLen);
            resultHandle = alloc_and_save(taskData, 4);
            DEREFHANDLE(resultHandle)->Set(0, DEREFWORDHANDLE(volHandle));
            DEREFHANDLE(resultHandle)->Set(1, DEREFWORDHANDLE(sysHandle));
            DEREFHANDLE(resultHandle)->Set(2, DEREFWORDHANDLE(serialHandle));
            DEREFHANDLE(resultHandle)->Set(3, DEREFWORDHANDLE(maxCompHandle));
            return resultHandle;
        }

    case 1033:
        {
            TCHAR fileName[MAX_PATH], execName[MAX_PATH];
            POLYUNSIGNED length = Poly_string_to_C(DEREFWORD(args), fileName, MAX_PATH);
            HINSTANCE hInst;
            if (length > MAX_PATH)
                raise_syscall(taskData, "File name too long", ENAMETOOLONG);
            hInst = FindExecutable(fileName, NULL, execName);
            if ((POLYUNSIGNED)hInst <= 32)
            {
               raise_syscall(taskData, "FindExecutable failed", -(int)(POLYUNSIGNED)hInst);
            }
            return SAVE(C_string_to_Poly(taskData, execName));
        }

    case 1034: // Open a document
        {
            SHELLEXECUTEINFO shellEx;
            memset(&shellEx, 0, sizeof(shellEx));
            shellEx.cbSize = sizeof(shellEx);
            shellEx.lpVerb = _T("open");
            shellEx.lpFile = Poly_string_to_T_alloc(DEREFWORD(args));
            shellEx.hwnd = hMainWindow;
            shellEx.nShow = SW_SHOWNORMAL;
            BOOL fRes = ShellExecuteEx(&shellEx);
            free((void*)shellEx.lpFile);
            if (! fRes)
                raise_syscall(taskData, "ShellExecuteEx failed", 0-GetLastError());
            return Make_arbitrary_precision(taskData, 0);
        }

    case 1035: // Launch an application.
        {
            SHELLEXECUTEINFO shellEx;
            memset(&shellEx, 0, sizeof(shellEx));
            shellEx.cbSize = sizeof(shellEx);
            shellEx.lpVerb = _T("open");
            shellEx.lpFile = Poly_string_to_T_alloc(args->WordP()->Get(0));
            shellEx.lpParameters = Poly_string_to_T_alloc(args->WordP()->Get(1));
            shellEx.nShow = SW_SHOWNORMAL;
            BOOL fRes = ShellExecuteEx(&shellEx);
            free((void*)shellEx.lpFile);
            free((void*)shellEx.lpParameters);
            if (! fRes)
                raise_syscall(taskData, "ShellExecuteEx failed", 0-GetLastError());
            return Make_arbitrary_precision(taskData, 0);
        }

    case 1036: // Does the process have its own console?
        return Make_arbitrary_precision(taskData, hMainWindow != NULL ? 1: 0);

    case 1037: // Simple execute.
        return simpleExecute(taskData, args);


        // DDE
    case 1038: // Start DDE dialogue.
        {
            Handle handToken;
            PHANDLETAB pTab;
            HCONV hcDDEConv;
            TCHAR *serviceName = Poly_string_to_T_alloc(args->WordP()->Get(0));
            TCHAR *topicName = Poly_string_to_T_alloc(args->WordP()->Get(1));
            /* Send a request to the main thread to do the work. */
            hcDDEConv = StartDDEConversation(serviceName, topicName);
            free(serviceName); free(topicName);
            if (hcDDEConv == 0) raise_syscall(taskData, "DdeConnect failed", 0);
            // Create an entry to return the conversation.
            handToken = make_handle_entry(taskData);
            pTab = &handleTable[STREAMID(handToken)];
            pTab->entryType = HE_DDECONVERSATION;
            pTab->entry.hcDDEConv = hcDDEConv;
            return handToken;
        }

    case 1039: // Send DDE execute request.
        {
            PHANDLETAB hnd =
                get_handle(DEREFHANDLE(args)->Get(0), HE_DDECONVERSATION);
            LRESULT res;
            char *command;
            if (hnd == NULL)
            {
                raise_syscall(taskData, "DDE Conversation is closed", 0);
            }
            command = Poly_string_to_C_alloc(args->WordP()->Get(1));
            /* Send a request to the main thread to do the work. */
            res = ExecuteDDE(command, hnd->entry.hcDDEConv);
            free(command);
            if (res == -1) raise_syscall(taskData, "DdeClientTransaction failed", 0);
            else return Make_arbitrary_precision(taskData, res);
        }

    case 1040: // Close a DDE conversation.
        {
            PHANDLETAB hnd = get_handle(args->Word(), HE_DDECONVERSATION);
            if (hnd != 0) close_handle(hnd);
            return Make_arbitrary_precision(taskData, 0);
        }


        // Configuration functions.
    case 1050: // Get version data
        {
            OSVERSIONINFO osver;
            ZeroMemory(&osver, sizeof(OSVERSIONINFO));
            osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
            // GetVersionEx is deprecated in Windows 8.1
            if (! GetVersionEx(&osver))
                raise_syscall(taskData, "GetVersionEx failed", -(int)GetLastError());
            Handle major = Make_arbitrary_precision(taskData, osver.dwMajorVersion);
            Handle minor = Make_arbitrary_precision(taskData, osver.dwMinorVersion);
            Handle build = Make_arbitrary_precision(taskData, osver.dwBuildNumber);
            Handle platform = Make_arbitrary_precision(taskData, osver.dwPlatformId);
            Handle version = SAVE(C_string_to_Poly(taskData, osver.szCSDVersion));
            Handle resVal = alloc_and_save(taskData, 5);
            DEREFHANDLE(resVal)->Set(0, DEREFWORDHANDLE(major));
            DEREFHANDLE(resVal)->Set(1, DEREFWORDHANDLE(minor));
            DEREFHANDLE(resVal)->Set(2, DEREFWORDHANDLE(build));
            DEREFHANDLE(resVal)->Set(3, DEREFWORDHANDLE(platform));
            DEREFHANDLE(resVal)->Set(4, DEREFWORDHANDLE(version));
            return resVal;
        }

    case 1051: // Get windows directory
        {
            TCHAR path[MAX_PATH+1];
            if (GetWindowsDirectory(path, sizeof(path)/sizeof(TCHAR)) == 0)
                raise_syscall(taskData, "GetWindowsDirectory failed", -(int)GetLastError());
            return SAVE(C_string_to_Poly(taskData, path));
        }

    case 1052: // Get system directory
        {
            TCHAR path[MAX_PATH+1];
            if (GetSystemDirectory(path, sizeof(path)/sizeof(TCHAR)) == 0)
                raise_syscall(taskData, "GetSystemDirectory failed", -(int)GetLastError());
            return SAVE(C_string_to_Poly(taskData, path));
        }

    case 1053: // Get computer name
        {
            TCHAR name[MAX_COMPUTERNAME_LENGTH +1];
            DWORD dwSize = MAX_COMPUTERNAME_LENGTH +1;
            if (GetComputerName(name, &dwSize) == 0)
                raise_syscall(taskData, "GetComputerName failed", -(int)GetLastError());
            return SAVE(C_string_to_Poly(taskData, name));
        }

    case 1054: // Get user name
        {
            TCHAR name[UNLEN +1];
            DWORD dwSize = UNLEN +1;
            if (GetUserName(name, &dwSize) == 0)
                raise_syscall(taskData, "GetUserName failed", -(int)GetLastError());
            return SAVE(C_string_to_Poly(taskData, name));
        }

    case 1100: // Get the error result from the last call.
               // This is saved when we make a call to a foreign function.
        {
            return(SAVE(TAGGED(taskData->lastError)));
        }

    case 1101: // Wait for a message.
        {
            while (1)
            {
                HWND hwnd = (HWND)get_C_long(taskData, DEREFWORDHANDLE(args)->Get(0)); /* Handles are treated as SIGNED. */
                UINT wMsgFilterMin = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(1));
                UINT wMsgFilterMax = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(2));
                MSG msg;
                processes->ThreadReleaseMLMemory(taskData);
                // N.B.  PeekMessage may directly call the window proc resulting in a
                // callback to ML.  For this to work a callback must not overwrite "args".
                BOOL result = PeekMessage(&msg, hwnd, wMsgFilterMin, wMsgFilterMax, PM_NOREMOVE);
                processes->ThreadUseMLMemory(taskData);
                if (result) return Make_arbitrary_precision(taskData, 0);
                // Pause until a message arrives.
                processes->ThreadPause(taskData);
            }
        }

    // case 1102: // Return the address of the window callback function.

    case 1103: // Return the application instance.
        return Make_arbitrary_precision(taskData, (POLYUNSIGNED)hApplicationInstance);

    case 1104: // Return the main window handle
        return Make_arbitrary_precision(taskData, (POLYUNSIGNED)hMainWindow);

//    case 1105: // Set the callback function

    default:
        {
            char msg[100];
            sprintf(msg, "Unknown windows-specific function: %d", c);
            raise_exception_string(taskData, EXC_Fail, msg);
            return 0;
        }
    }
}
コード例 #16
0
ファイル: indexamajig.c プロジェクト: biochem-fan/CrystFEL
int main(int argc, char *argv[])
{
	int c;
	char *filename = NULL;
	char *outfile = NULL;
	FILE *fh;
	Stream *st;
	int config_checkprefix = 1;
	int config_basename = 0;
	int integrate_saturated = 0;
	IndexingMethod *indm;
	IndexingPrivate **ipriv;
	char *indm_str = NULL;
	char *cellfile = NULL;
	char *prefix = NULL;
	char *speaks = NULL;
	char *toler = NULL;
	int n_proc = 1;
	struct index_args iargs;
	char *intrad = NULL;
	char *pkrad = NULL;
	char *int_str = NULL;
	char *tempdir = NULL;
	char *int_diag = NULL;
	char *geom_filename = NULL;
	struct beam_params beam;
	int have_push_res = 0;

	/* Defaults */
	iargs.cell = NULL;
	iargs.noisefilter = 0;
	iargs.median_filter = 0;
	iargs.satcorr = 1;
	iargs.tols[0] = 5.0;
	iargs.tols[1] = 5.0;
	iargs.tols[2] = 5.0;
	iargs.tols[3] = 1.5;
	iargs.threshold = 800.0;
	iargs.min_gradient = 100000.0;
	iargs.min_snr = 5.0;
	iargs.check_hdf5_snr = 0;
	iargs.det = NULL;
	iargs.peaks = PEAK_ZAEF;
	iargs.beam = &beam;
	iargs.hdf5_peak_path = NULL;
	iargs.copyme = NULL;
	iargs.pk_inn = -1.0;
	iargs.pk_mid = -1.0;
	iargs.pk_out = -1.0;
	iargs.ir_inn = 4.0;
	iargs.ir_mid = 5.0;
	iargs.ir_out = 7.0;
	iargs.use_saturated = 1;
	iargs.no_revalidate = 0;
	iargs.stream_peaks = 1;
	iargs.stream_refls = 1;
	iargs.int_diag = INTDIAG_NONE;
	iargs.copyme = new_copy_hdf5_field_list();
	if ( iargs.copyme == NULL ) {
		ERROR("Couldn't allocate HDF5 field list.\n");
		return 1;
	}
	iargs.indm = NULL;  /* No default */
	iargs.ipriv = NULL;  /* No default */
	iargs.int_meth = integration_method("rings-nocen", NULL);
	iargs.push_res = 0.0;
	iargs.highres = +INFINITY;
	iargs.fix_profile_r = -1.0;
	iargs.fix_bandwidth = -1.0;
	iargs.fix_divergence = -1.0;

	/* Long options */
	const struct option longopts[] = {

		/* Options with long and short versions */
		{"help",               0, NULL,               'h'},
		{"version",            0, NULL,               'v'},
		{"input",              1, NULL,               'i'},
		{"output",             1, NULL,               'o'},
		{"indexing",           1, NULL,               'z'},
		{"geometry",           1, NULL,               'g'},
		{"pdb",                1, NULL,               'p'},
		{"prefix",             1, NULL,               'x'},
		{"threshold",          1, NULL,               't'},
		{"beam",               1, NULL,               'b'},

		/* Long-only options with no arguments */
		{"filter-noise",       0, &iargs.noisefilter,        1},
		{"no-check-prefix",    0, &config_checkprefix,       0},
		{"basename",           0, &config_basename,          1},
		{"no-peaks-in-stream", 0, &iargs.stream_peaks,       0},
		{"no-refls-in-stream", 0, &iargs.stream_refls,       0},
		{"integrate-saturated",0, &integrate_saturated,      1},
		{"no-use-saturated",   0, &iargs.use_saturated,      0},
		{"no-revalidate",      0, &iargs.no_revalidate,      1},
		{"check-hdf5-snr",     0, &iargs.check_hdf5_snr,     1},

		/* Long-only options which don't actually do anything */
		{"no-sat-corr",        0, &iargs.satcorr,            0},
		{"sat-corr",           0, &iargs.satcorr,            1},
		{"no-check-hdf5-snr",  0, &iargs.check_hdf5_snr,     0},
		{"use-saturated",      0, &iargs.use_saturated,      1},

		/* Long-only options with arguments */
		{"peaks",              1, NULL,                2},
		{"cell-reduction",     1, NULL,                3},
		{"min-gradient",       1, NULL,                4},
		{"record",             1, NULL,                5},
		{"cpus",               1, NULL,                6},
		{"cpugroup",           1, NULL,                7},
		{"cpuoffset",          1, NULL,                8},
		{"hdf5-peaks",         1, NULL,                9},
		{"copy-hdf5-field",    1, NULL,               10},
		{"min-snr",            1, NULL,               11},
		{"tolerance",          1, NULL,               13},
		{"int-radius",         1, NULL,               14},
		{"median-filter",      1, NULL,               15},
		{"integration",        1, NULL,               16},
		{"temp-dir",           1, NULL,               17},
		{"int-diag",           1, NULL,               18},
		{"push-res",           1, NULL,               19},
		{"res-push",           1, NULL,               19}, /* compat */
		{"peak-radius",        1, NULL,               20},
		{"highres",            1, NULL,               21},
		{"fix-profile-radius", 1, NULL,               22},
		{"fix-bandwidth",      1, NULL,               23},
		{"fix-divergence",     1, NULL,               24},

		{0, 0, NULL, 0}
	};

	/* Short options */
	while ((c = getopt_long(argc, argv, "hi:o:z:p:x:j:g:t:vb:",
	                        longopts, NULL)) != -1)
	{
		switch (c) {

			case 'h' :
			show_help(argv[0]);
			return 0;

			case 'v' :
			printf("CrystFEL: " CRYSTFEL_VERSIONSTRING "\n");
			printf(CRYSTFEL_BOILERPLATE"\n");
			return 0;

			case 'b' :
			ERROR("WARNING: This version of CrystFEL no longer "
			      "uses beam files.  Please remove the beam file "
			      "from your indexamajig command line.\n");
			return 1;

			case 'i' :
			filename = strdup(optarg);
			break;

			case 'o' :
			outfile = strdup(optarg);
			break;

			case 'z' :
			indm_str = strdup(optarg);
			break;

			case 'p' :
			cellfile = strdup(optarg);
			break;

			case 'x' :
			prefix = strdup(optarg);
			break;

			case 'j' :
			n_proc = atoi(optarg);
			break;

			case 'g' :
			geom_filename = optarg;
			break;

			case 't' :
			iargs.threshold = strtof(optarg, NULL);
			break;

			case 2 :
			speaks = strdup(optarg);
			break;

			case 3 :
			ERROR("The option '--cell-reduction' is no longer "
			      "used.\n"
			      "The complete indexing behaviour is now "
			      "controlled using '--indexing'.\n"
			      "See 'man indexamajig' for details of the "
			      "available methods.\n");
			return 1;

			case 4 :
			iargs.min_gradient = strtof(optarg, NULL);
			break;

			case 5 :
			ERROR("The option '--record' is no longer used.\n"
			      "Use '--no-peaks-in-stream' and"
			      "'--no-refls-in-stream' if you need to control"
			      "the contents of the stream.\n");
			return 1;

			case 6 :
			case 7 :
			case 8 :
			ERROR("The options --cpus, --cpugroup and --cpuoffset"
			      " are no longer used by indexamajig.\n");
			break;

			case 9 :
			free(iargs.hdf5_peak_path);
			iargs.hdf5_peak_path = strdup(optarg);
			break;

			case 10 :
			add_copy_hdf5_field(iargs.copyme, optarg);
			break;

			case 11 :
			iargs.min_snr = strtof(optarg, NULL);
			break;

			case 13 :
			toler = strdup(optarg);
			break;

			case 14 :
			intrad = strdup(optarg);
			break;

			case 15 :
			iargs.median_filter = atoi(optarg);
			break;

			case 16 :
			int_str = strdup(optarg);
			break;

			case 17 :
			tempdir = strdup(optarg);
			break;

			case 18 :
			int_diag = strdup(optarg);
			break;

			case 19 :
			if ( sscanf(optarg, "%f", &iargs.push_res) != 1 ) {
				ERROR("Invalid value for --push-res\n");
				return 1;
			}
			iargs.push_res *= 1e9;  /* nm^-1 -> m^-1 */
			have_push_res = 1;
			break;

			case 20 :
			pkrad = strdup(optarg);
			break;

			case 21 :
			if ( sscanf(optarg, "%f", &iargs.highres) != 1 ) {
				ERROR("Invalid value for --highres\n");
				return 1;
			}
			/* A -> m^-1 */
			iargs.highres = 1.0 / (iargs.highres/1e10);
			break;

			case 22 :
			if ( sscanf(optarg, "%f", &iargs.fix_profile_r) != 1 ) {
				ERROR("Invalid value for "
				      "--fix-profile-radius\n");
				return 1;
			}
			break;

			case 23 :
			if ( sscanf(optarg, "%f", &iargs.fix_bandwidth) != 1 ) {
				ERROR("Invalid value for --fix-bandwidth\n");
				return 1;
			}
			break;

			case 24 :
			if ( sscanf(optarg, "%f", &iargs.fix_divergence) != 1 ) {
				ERROR("Invalid value for --fix-divergence\n");
				return 1;
			}
			break;

			case 0 :
			break;

			case '?' :
			break;

			default :
			ERROR("Unhandled option '%c'\n", c);
			break;

		}

	}

	if ( tempdir == NULL ) {
		tempdir = strdup(".");
	}

	if ( filename == NULL ) {
		filename = strdup("-");
	}
	if ( strcmp(filename, "-") == 0 ) {
		fh = stdin;
	} else {
		fh = fopen(filename, "r");
	}
	if ( fh == NULL ) {
		ERROR("Failed to open input file '%s'\n", filename);
		return 1;
	}
	free(filename);

	if ( speaks == NULL ) {
		speaks = strdup("zaef");
		STATUS("You didn't specify a peak detection method.\n");
		STATUS("I'm using 'zaef' for you.\n");
	}
	if ( strcmp(speaks, "zaef") == 0 ) {
		iargs.peaks = PEAK_ZAEF;
	} else if ( strcmp(speaks, "hdf5") == 0 ) {
		iargs.peaks = PEAK_HDF5;
	} else if ( strcmp(speaks, "cxi") == 0 ) {
		iargs.peaks = PEAK_CXI;
	} else {
		ERROR("Unrecognised peak detection method '%s'\n", speaks);
		return 1;
	}
	free(speaks);

	/* Set default path for peaks, if appropriate */
	if ( iargs.hdf5_peak_path == NULL ) {
		if ( iargs.peaks == PEAK_HDF5 ) {
			iargs.hdf5_peak_path = strdup("/processing/hitfinder/peakinfo");
		} else if ( iargs.peaks == PEAK_CXI ) {
			iargs.hdf5_peak_path = strdup("/entry_1/result_1");
		}
	}

	if ( prefix == NULL ) {
		prefix = strdup("");
	} else {
		if ( config_checkprefix ) {
			prefix = check_prefix(prefix);
		}
	}

	if ( n_proc == 0 ) {
		ERROR("Invalid number of processes.\n");
		return 1;
	}

	iargs.det = get_detector_geometry(geom_filename, iargs.beam);
	if ( iargs.det == NULL ) {
		ERROR("Failed to read detector geometry from  '%s'\n",
		      geom_filename);
		return 1;
	}

	if ( indm_str == NULL ) {

		STATUS("You didn't specify an indexing method, so I  won't try "
		       " to index anything.\n"
		       "If that isn't what you wanted, re-run with"
		       " --indexing=<methods>.\n");
		indm = NULL;

	} else {

		indm = build_indexer_list(indm_str);
		if ( indm == NULL ) {
			ERROR("Invalid indexer list '%s'\n", indm_str);
			return 1;
		}
		free(indm_str);
	}

	if ( int_str != NULL ) {

		int err;

		iargs.int_meth = integration_method(int_str, &err);
		if ( err ) {
			ERROR("Invalid integration method '%s'\n", int_str);
			return 1;
		}
		free(int_str);
	}
	if ( integrate_saturated ) {
		/* Option provided for backwards compatibility */
		iargs.int_meth |= INTEGRATION_SATURATED;
	}

	if ( have_push_res && !(iargs.int_meth & INTEGRATION_RESCUT) ) {
		ERROR("WARNING: You used --push-res, but not -rescut, "
		      "therefore --push-res will have no effect.\n");
	}

	if ( toler != NULL ) {
		int ttt;
		ttt = sscanf(toler, "%f,%f,%f,%f",
		             &iargs.tols[0], &iargs.tols[1],
		             &iargs.tols[2], &iargs.tols[3]);
		if ( ttt != 4 ) {
			ERROR("Invalid parameters for '--tolerance'\n");
			return 1;
		}
		free(toler);
	}

	if ( intrad != NULL ) {
		int r;
		r = sscanf(intrad, "%f,%f,%f",
		           &iargs.ir_inn, &iargs.ir_mid, &iargs.ir_out);
		if ( r != 3 ) {
			ERROR("Invalid parameters for '--int-radius'\n");
			return 1;
		}
		free(intrad);
	} else {
		STATUS("WARNING: You did not specify --int-radius.\n");
		STATUS("WARNING: I will use the default values, which are"
		       " probably not appropriate for your patterns.\n");
	}

	if ( pkrad != NULL ) {
		int r;
		r = sscanf(pkrad, "%f,%f,%f",
		           &iargs.pk_inn, &iargs.pk_mid, &iargs.pk_out);
		if ( r != 3 ) {
			ERROR("Invalid parameters for '--peak-radius'\n");
			return 1;
		}
		free(pkrad);
	}

	if ( iargs.pk_inn < 0.0 ) {
		iargs.pk_inn = iargs.ir_inn;
		iargs.pk_mid = iargs.ir_mid;
		iargs.pk_out = iargs.ir_out;
	}

	if ( iargs.det == NULL ) {
		ERROR("You need to provide a geometry file (please read the"
		      " manual for more details).\n");
		return 1;
	}

	add_geom_beam_stuff_to_copy_hdf5(iargs.copyme, iargs.det, iargs.beam);

	if ( cellfile != NULL ) {
		iargs.cell = load_cell_from_file(cellfile);
		if ( iargs.cell == NULL ) {
			ERROR("Couldn't read unit cell (from %s)\n", cellfile);
			return 1;
		}
		free(cellfile);
		STATUS("This is what I understood your unit cell to be:\n");
		cell_print(iargs.cell);
	} else {
		STATUS("No unit cell given.\n");
		iargs.cell = NULL;
	}

	if ( int_diag != NULL ) {

		int r;
		signed int h, k, l;

		if ( strcmp(int_diag, "random") == 0 ) {
			iargs.int_diag = INTDIAG_RANDOM;
		}

		if ( strcmp(int_diag, "all") == 0 ) {
			iargs.int_diag = INTDIAG_ALL;
		}

		if ( strcmp(int_diag, "negative") == 0 ) {
			iargs.int_diag = INTDIAG_NEGATIVE;
		}

		if ( strcmp(int_diag, "implausible") == 0 ) {
			iargs.int_diag = INTDIAG_IMPLAUSIBLE;
		}

		if ( strcmp(int_diag, "strong") == 0 ) {
			iargs.int_diag = INTDIAG_STRONG;
		}

		r = sscanf(int_diag, "%i,%i,%i", &h, &k, &l);
		if ( r == 3 ) {
			iargs.int_diag = INTDIAG_INDICES;
			iargs.int_diag_h = h;
			iargs.int_diag_k = k;
			iargs.int_diag_l = l;
		}

		if ( (iargs.int_diag == INTDIAG_NONE)
		  && (strcmp(int_diag, "none") != 0) ) {
			ERROR("Invalid value for --int-diag.\n");
			return 1;
		}

		free(int_diag);

		if ( (n_proc > 1) && (iargs.int_diag != INTDIAG_NONE) ) {
			n_proc = 1;
			STATUS("Ignored \"-j\" because you used --int-diag.\n");
		}

	}

	st = open_stream_for_write_2(outfile, geom_filename, argc, argv);
	if ( st == NULL ) {
		ERROR("Failed to open stream '%s'\n", outfile);
		return 1;
	}
	free(outfile);

	/* Prepare the indexer */
	if ( indm != NULL ) {
		ipriv = prepare_indexing(indm, iargs.cell, iargs.det,
		                         iargs.tols);
		if ( ipriv == NULL ) {
			ERROR("Failed to prepare indexing.\n");
			return 1;
		}
	} else {
		ipriv = NULL;
	}

	gsl_set_error_handler_off();

	iargs.indm = indm;
	iargs.ipriv = ipriv;

	create_sandbox(&iargs, n_proc, prefix, config_basename, fh,
	               st, tempdir);

	free(prefix);
	free(tempdir);
	free_detector_geometry(iargs.det);
	close_stream(st);
	cleanup_indexing(indm, ipriv);

	return 0;
}
コード例 #17
0
ファイル: s_process.c プロジェクト: ajwvm/dsvvalid
/*
 *
 *  Process toktab and create output stream.
 *
 */
void s_process()
{
  int icol,icoltt,i,eofldchar=0,eolchar=0;
  int iline,iq,nc;
  int queue_siz;
  struct streams *s, *t;

  s=&instream;
  if (fseek(s->fp,0,SEEK_SET) != 0)
    err_exit(ERR_PRO_SEEK);
  t=create_outstream(&outstream);
  
  /* Check for queue size needed.*/
  for (i=0,queue_siz=0;toktab[i]->valid;i++)
    if (toktab[i]->type == TOKNUM && (toktab[i]->flag == RS2QUE || toktab[i]->flag == RS2QUEOUT)) queue_siz++;
  queue_siz+=1;  /* For col==0; */

  /* Create queue if needed.*/
  if (queue_siz > 1) {
    queue = malloc(queue_siz*sizeof(struct queues *));
    if (queue==NULL) err_exit(ERR_PRO_QUE);
    for (i=0;i<queue_siz;i++) {
      queue[i] = malloc(sizeof(struct queues));
      if (queue[i]==NULL) err_exit(ERR_PRO_QUE);
      queue[i]->col=0;
    }
  }  
  /* Loop over lines in dsv file */
  for (iline=1;;iline++) {

    if (iline == s->nline) {
      if (s->EOLLast != EOF) goto EOFline;
      eolchar = EOF;
    } 
    else
      eolchar = s->EOLc;
    
    icol=1;    
    iq=0;
    
    /* Loop over tokens in toktab */
    for (i=0;toktab[i]->valid;i++) {
      switch (toktab[i]->type) {
      case TOKNUM:
	icoltt = toktab[i]->u.itok;       
	eofldchar = (icoltt == s->ncol) ? eolchar : *(s->delim);

	switch (toktab[i]->flag) {
	case RS2OUT:
	  nc=icoltt-icol;
	  skip_fld(s,nc);icol+=nc;
	  read_fld(s,eofldchar);icol++;          
	  if PUT_DELIM(i) put_delimout(s);
	  break;
	case RS2QUE:
	  nc=icoltt-icol;
	  skip_fld(s,nc);icol+=nc;
	  push2queue(s,queue[iq],eofldchar);
	  queue[iq++]->col=toktab[i]->u.itok;icol++;
	  break;
	case RS2QUEOUT:      
	  nc=icoltt-icol;
	  skip_fld(s,nc);icol+=nc;
	  push2queueout(s,queue[iq],eofldchar);
	  queue[iq++]->col=toktab[i]->u.itok;icol++;
	  if PUT_DELIM(i) put_delimout(s);
	  break;
	case RQUE2OUT:
	  pullfqueue(icoltt,toktab[i]);
	  if PUT_DELIM(i) put_delimout(s);
	  break;
	default:
	  /*  */
	  break;
	}
	break;
      case TOKLIT:
	read_lit(toktab[i]);
	if PUT_DELIM(i) put_delimout(s);
	break;
      case TOKOPE:
	switch (toktab[i]->u.otok) {
	case PLU:  
	  /* Do not insert delim */
	  break;
	default:
	  err_exit(ERR_SWI_LOGIC);
	  break;
	}
	break;
      default:
	err_exit(ERR_SWI_LOGIC);
	break;
      }
    }  
    skip_EOL(s,eolchar);
    
  EOFline:
    put_EOLout(s,t);
    if (!read_EOL(s)) break;

    /* list_queue(); */
  }
  close_stream(s);
  close_stream(t);
}
コード例 #18
0
ファイル: im-sandbox.c プロジェクト: keitaroyam/CrystFEL
static void start_worker_process(struct sandbox *sb, int slot)
{
	pid_t p;
	int filename_pipe[2];
	int result_pipe[2];
	int stream_pipe[2];

	if ( pipe(filename_pipe) == - 1 ) {
		ERROR("pipe() failed!\n");
		return;
	}

	if ( pipe(result_pipe) == - 1 ) {
		ERROR("pipe() failed!\n");
		return;
	}

	if ( pipe(stream_pipe) == - 1 ) {
		ERROR("pipe() failed!\n");
		return;
	}

	p = fork();
	if ( p == -1 ) {
		ERROR("fork() failed!\n");
		return;
	}

	if ( p == 0 ) {

		Stream *st;
		int j;
		struct sigaction sa;
		int r;
		char *tmp;
		struct stat s;
		size_t ll;

		/* First, disconnect the signal handler */
		sa.sa_flags = 0;
		sigemptyset(&sa.sa_mask);
		sa.sa_handler = SIG_DFL;
		r = sigaction(SIGCHLD, &sa, NULL);
		if ( r == -1 ) {
			ERROR("Failed to set signal handler!\n");
			return;
		}

		ll = 64 + strlen(sb->tmpdir);
		tmp = malloc(ll);
		if ( tmp == NULL ) {
			ERROR("Failed to allocate temporary dir\n");
			return;
		}

		snprintf(tmp, 63, "%s/worker.%i", sb->tmpdir, slot);

		if ( stat(tmp, &s) == -1 ) {
			if ( errno != ENOENT ) {
				ERROR("Failed to stat temporary folder.\n");
				return;
			}

			r = mkdir(tmp, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
			if ( r ) {
				ERROR("Failed to create temporary folder: %s\n",
				strerror(errno));
				return;
			}
		}

		/* Free resources which will not be needed by worker */
		for ( j=0; j<sb->n_proc; j++ ) {
			if ( (j != slot) && (sb->running[j]) ) {
				close(sb->stream_pipe_write[j]);
			}
		}
		for ( j=0; j<sb->n_proc; j++ ) {
			if ( (j != slot) && (sb->running[j]) ) {
				if ( sb->result_fhs[j] != NULL ) {
					fclose(sb->result_fhs[j]);
				}
				close(sb->filename_pipes[j]);
			}
		}
		free(sb->filename_pipes);
		free(sb->result_fhs);
		free(sb->pids);
		/* Also prefix, use_this_one_instead and fh */

		/* Child process gets the 'read' end of the filename
		 * pipe, and the 'write' end of the result pipe. */
		close(filename_pipe[1]);
		close(result_pipe[0]);

		st = open_stream_fd_for_write(stream_pipe[1]);
		run_work(sb->iargs, filename_pipe[0], result_pipe[1],
		         st, slot, tmp);
		close_stream(st);

		//close(filename_pipe[0]);
		close(result_pipe[1]);

		exit(0);

	}

	/* Parent process gets the 'write' end of the filename pipe
	 * and the 'read' end of the result pipe. */
	sb->pids[slot] = p;
	sb->running[slot] = 1;
	add_pipe(sb->reader, stream_pipe[0]);
	close(filename_pipe[0]);
	close(result_pipe[1]);
	close(stream_pipe[1]);
	sb->filename_pipes[slot] = filename_pipe[1];

	sb->result_fhs[slot] = fdopen(result_pipe[0], "r");
	if ( sb->result_fhs[slot] == NULL ) {
		ERROR("fdopen() failed.\n");
		return;
	}
}
コード例 #19
0
void Application::init_connections(){


    CONNECT (player, pause(),                                       listen,				pause());
           CONNECT (player, search(int),							listen,			jump(int));
           CONNECT (player, sig_volume_changed(int),				listen,			setVolume(int));
           CONNECT (player, sig_rec_button_toggled(bool),			listen,			record_button_toggled(bool));
           CONNECT (player, setupLastFM(),                          ui_lastfm, 		show_win()); // IND
           CONNECT (player, baseDirSelected(const QString &),		library, 		baseDirSelected(const QString & ));
           CONNECT (player, reloadLibrary(), 						library, 		reloadLibrary());
           CONNECT (player, importDirectory(QString),				library,		importDirectory(QString));
           CONNECT (player, libpath_changed(QString),               library, 			setLibraryPath(QString));
           CONNECT (player, fileSelected(QStringList &),			playlist, 			psl_createPlaylist(QStringList&));
           CONNECT (player, play(),                                 playlist,			psl_play());
           CONNECT (player, stop(),                                 playlist,			psl_stop());
           CONNECT (player, forward(),                              playlist,			psl_forward());
           CONNECT (player, backward(),                             playlist,			psl_backward());
           CONNECT (player, sig_stream_selected(const QString&, const QString&), 		playlist, psl_play_stream(const QString&, const QString&));
           CONNECT (player, show_playlists(),						ui_playlist_chooser, 	show()); // IND
           CONNECT (player, skinChanged(bool),                      ui_playlist, 		change_skin(bool));
           CONNECT (player, show_small_playlist_items(bool),		ui_playlist,		psl_show_small_playlist_items(bool));
           CONNECT (player, sig_sound_engine_changed(QString&), 	plugin_loader,      psl_switch_engine(QString&));
           CONNECT (player, sig_show_stream_rec(bool),              ui_stream_rec,		psl_show(bool)); // IND
           CONNECT (player, sig_show_socket(),                      ui_socket_setup,    show()); // IND


           CONNECT (player, sig_correct_id3(const MetaData&), 	ui_id3_editor,		change_meta_data(const MetaData&)); // IND


           CONNECT (playlist, sig_selected_file_changed_md(const MetaData&),		player,		update_track(const MetaData&));
           CONNECT (playlist, sig_selected_file_changed_md(const MetaData&), 		listen, 		changeTrack(const MetaData & ));
           CONNECT (playlist, sig_selected_file_changed_md(const MetaData&),		lastfm,			psl_track_changed(const MetaData&));
           CONNECT (playlist, sig_no_track_to_play(),								listen,			stop());
           CONNECT (playlist, sig_goon_playing(),                                   listen,			play());
           CONNECT (playlist, sig_selected_file_changed(int),                       ui_playlist, 	track_changed(int));
           CONNECT (playlist, sig_playlist_created(vector<MetaData>&, int), 		ui_playlist, 	fillPlaylist(vector<MetaData>&, int));
           //CONNECT (&playlist, sig_cur_played_info_changed(const MetaData&),   	&player,  		update_info(const MetaData&));
           CONNECT (playlist, sig_playlist_prepared(int, vector<MetaData>&), 		playlists,      save_playlist_as_custom(int, vector<MetaData>&));
           CONNECT (playlist, sig_playlist_prepared(QString, vector<MetaData>&), 	playlists,      save_playlist_as_custom(QString, vector<MetaData>&));
           CONNECT (playlist, sig_library_changed(), 								ui_library, 	library_changed());
           CONNECT (playlist, sig_import_files(const vector<MetaData>&), 			library, 		importFiles(const vector<MetaData>&));
           CONNECT (playlist, sig_need_more_radio(),								lastfm, 		psl_radio_playlist_request());
           CONNECT (playlist, sig_radio_active(int),								player,         set_radio_active(int));
           CONNECT (playlist, sig_radio_active(int),								ui_playlist,	set_radio_active(int));

           // Can be done inside player
           CONNECT (playlist, sig_radio_active(int),								ui_playlist_chooser, set_radio_active(int));

           CONNECT (playlist, sig_data_for_id3_change(const vector<MetaData>&), 	ui_id3_editor,	change_meta_data(const vector<MetaData>&)); // IND

           CONNECT (ui_playlist, selected_row_changed(int), 					playlist, 	psl_change_track(int));
           CONNECT (ui_playlist, clear_playlist(),                              playlist, 	psl_clear_playlist());
           CONNECT (ui_playlist, playlist_mode_changed(const Playlist_Mode&),   playlist, 	psl_playlist_mode_changed(const Playlist_Mode&));
           CONNECT (ui_playlist, dropped_tracks(const vector<MetaData>&, int),  playlist, 	psl_insert_tracks(const vector<MetaData>&, int));
           CONNECT (ui_playlist, sound_files_dropped(QStringList&), 			playlist, 	psl_createPlaylist(QStringList&));
           CONNECT (ui_playlist, directory_dropped(const QString&, int),		playlist, 	psl_directoryDropped(const QString &, int ));
           CONNECT (ui_playlist, rows_removed(const QList<int>&),               playlist, 	psl_remove_rows(const QList<int>&));
           CONNECT (ui_playlist, sig_import_to_library(bool),					playlist,	psl_import_new_tracks_to_library(bool));

           CONNECT (listen, track_finished(),                                   playlist,	psl_next_track() );
           CONNECT (listen, sig_valid_strrec_track(const MetaData&),            playlist,  psl_valid_strrec_track(const MetaData&));
           CONNECT (listen, scrobble_track(const MetaData&),                    lastfm, 	psl_scrobble(const MetaData&));

           // should be sent to player
           CONNECT (listen, eq_presets_loaded(const vector<EQ_Setting>&),       ui_eq,	fill_eq_presets(const vector<EQ_Setting>&));
           CONNECT (listen, eq_found(const QStringList&),                       ui_eq, 	fill_available_equalizers(const QStringList&));

           CONNECT (listen, total_time_changed_signal(qint64),                  player,	total_time_changed(qint64));
           CONNECT (listen, timeChangedSignal(quint32),                         player,	setCurrentPosition(quint32) );

           CONNECT(library, sig_playlist_created(QStringList&), 			playlist, 		psl_createPlaylist(QStringList&));
           CONNECT(library, sig_import_result(bool),						playlist,		psl_import_result(bool));
           CONNECT(library, sig_import_result(bool),						ui_playlist,	import_result(bool));
           CONNECT(library, sig_reload_library_finished(),                  ui_library, 	reloading_library_finished());
           CONNECT(library, sig_reloading_library(QString&),				ui_library, 	reloading_library(QString&));
           CONNECT(library, sig_import_result(bool),						ui_library,	import_result(bool));
           CONNECT(library, sig_metadata_loaded(vector<MetaData>&), 		ui_library, 	fill_library_tracks(vector<MetaData>&));
           CONNECT(library, sig_all_albums_loaded(vector<Album>&),          ui_library, 	fill_library_albums(vector<Album>&));
           CONNECT(library, sig_all_artists_loaded(vector<Artist>&), 		ui_library, 	fill_library_artists(vector<Artist>&));
           CONNECT(library, sig_track_mime_data_available(const vector<MetaData>&), 		ui_library, 	track_info_available(const vector<MetaData>&));
           CONNECT(library, sig_tracks_for_playlist_available(vector<MetaData>&),           playlist, psl_createPlaylist(vector<MetaData>&));
           CONNECT(library, sig_import_result(bool),						playlists,		import_result(bool));
           CONNECT(library, sig_delete_answer(QString), 					ui_library, 	psl_delete_answer(QString));
           CONNECT(library, sig_play_next_tracks(const vector<MetaData>&),  playlist,		psl_play_next_tracks(const vector<MetaData>&));

           if(ui_id3_editor)
               CONNECT(library, sig_change_id3_tags(const vector<MetaData>&),	ui_id3_editor,	change_meta_data(const vector<MetaData>&)); // IND

           CONNECT(ui_library, sig_album_dbl_clicked(), 						library, 		psl_prepare_album_for_playlist());
           CONNECT(ui_library, sig_artist_dbl_clicked(), 						library, 		psl_prepare_artist_for_playlist());
           CONNECT(ui_library, sig_track_dbl_clicked(int),                      library, 		psl_prepare_track_for_playlist(int));
           CONNECT(ui_library, sig_artist_pressed(const QList<int>&),           library, 		psl_selected_artists_changed(const QList<int>&));
           CONNECT(ui_library, sig_album_pressed(const QList<int>&),            library, 		psl_selected_albums_changed(const QList<int>&));
           CONNECT(ui_library, sig_track_pressed(const QList<int>&),            library, 		psl_selected_tracks_changed(const QList<int>&));
           CONNECT(ui_library, sig_filter_changed(const Filter&),               library, 		psl_filter_changed(const Filter&));

           CONNECT(ui_library, sig_sortorder_changed(Sort::ArtistSort, Sort::AlbumSort, Sort::TrackSort),
                   library, 	 psl_sortorder_changed(Sort::ArtistSort, Sort::AlbumSort, Sort::TrackSort));

           CONNECT(ui_library, sig_show_id3_editor(const QList<int>&),              library, 		psl_change_id3_tags(const QList<int>&));
           CONNECT(ui_library, sig_delete_tracks(int),                              library,		psl_delete_tracks(int));
           CONNECT(ui_library, sig_delete_certain_tracks(const QList<int>&, int),	library,		psl_delete_certain_tracks(const QList<int>&, int));
           CONNECT(ui_library, sig_play_next_tracks(const QList<int>&),             library,		psl_play_next_tracks(const QList<int>&));
           CONNECT(ui_library, sig_play_next_all_tracks(),                          library,		psl_play_next_all_tracks());


           CONNECT(ui_lastfm, sig_activated(bool), player, psl_lfm_activated(bool));
           CONNECT(ui_lastfm, sig_activated(bool), ui_playlist, psl_lfm_activated(bool));
           CONNECT(ui_lastfm, new_lfm_credentials(QString, QString), 		lastfm, 		psl_login(QString, QString));


           CONNECT(ui_eq, eq_changed_signal(int, int),                          listen, 	eq_changed(int, int));
           CONNECT(ui_eq, eq_enabled_signal(bool),                              listen, 	eq_enable(bool));
           CONNECT(ui_eq, close_event(),                                        player, 	close_eq());


           CONNECT(ui_playlist, edit_id3_signal(),                                  playlist, 		psl_edit_id3_request());

           CONNECT(ui_id3_editor, id3_tags_changed(), 							ui_library, 	id3_tags_changed());
           CONNECT(ui_id3_editor, id3_tags_changed(vector<MetaData>&), 			playlist, 		psl_id3_tags_changed(vector<MetaData>&));
           CONNECT(ui_id3_editor, id3_tags_changed(vector<MetaData>&), 			player, 		psl_id3_tags_changed(vector<MetaData>&));


           CONNECT(lastfm,	sig_similar_artists_available(const QList<int>&),		playlist,		psl_similar_artists_available(const QList<int>&));
           CONNECT(lastfm,	sig_last_fm_logged_in(bool),							ui_playlist,	last_fm_logged_in(bool));
           CONNECT(lastfm,	sig_last_fm_logged_in(bool),							player,		last_fm_logged_in(bool));
           CONNECT(lastfm,	sig_new_radio_playlist(const vector<MetaData>&),		playlist,		psl_new_radio_playlist_available(const vector<MetaData>&));
           CONNECT(lastfm, sig_track_info_fetched(const MetaData&, bool, bool),     player,		lfm_info_fetched(const MetaData&, bool, bool));

           CONNECT(ui_playlist_chooser, sig_playlist_chosen(int),		playlists, load_single_playlist(int));
           CONNECT(ui_playlist_chooser, sig_delete_playlist(int),       playlists, delete_playlist(int));
           CONNECT(ui_playlist_chooser, sig_save_playlist(int), 		playlist, 	psl_prepare_playlist_for_save(int));
           CONNECT(ui_playlist_chooser, sig_save_playlist(QString), 	playlist, 	psl_prepare_playlist_for_save(QString));
           CONNECT(ui_playlist_chooser, sig_clear_playlist(),           playlist, 	psl_clear_playlist());
           CONNECT(ui_playlist_chooser, sig_closed(),                   player, 	close_playlist_chooser());

           CONNECT(playlists, sig_single_playlist_loaded(CustomPlaylist&),      playlist, 				psl_createPlaylist(CustomPlaylist&));
           CONNECT(playlists, sig_all_playlists_loaded(QMap<int, QString>&), 	ui_playlist_chooser, 	all_playlists_fetched(QMap<int, QString>&));
           CONNECT(playlists, sig_import_tracks(const vector<MetaData>&),       library, 				importFiles(const vector<MetaData>&));


            CONNECT(ui_lfm_radio, listen_clicked(const QString&, int),          lastfm,		psl_radio_init(const QString&, int));
            CONNECT(ui_lfm_radio, close_event(), 								player, 	close_lfm_radio());

            CONNECT(ui_stream, sig_play_stream(const QString&, const QString&), 	playlist, 	psl_play_stream(const QString&, const QString&));
            CONNECT(ui_stream, sig_close_event(), 									player, 	close_stream());


           CONNECT (ui_stream_rec, sig_stream_recorder_active(bool),	listen,		psl_strrip_set_active(bool));
           CONNECT (ui_stream_rec, sig_stream_recorder_active(bool),	player,     psl_strrip_set_active(bool));
           CONNECT (ui_stream_rec, sig_path_changed(const QString&), 	listen,		psl_strrip_set_path(const QString& ));
           CONNECT (ui_stream_rec, sig_complete_tracks(bool),           listen,		psl_strrip_complete_tracks(bool));
           CONNECT (ui_stream_rec, sig_create_playlist(bool),           listen,		psl_strrip_set_create_playlist(bool ));


           bool is_socket_active = set->getSocketActivated();
           if(is_socket_active){
               CONNECT (remote_socket, sig_play(),		playlist,			psl_play());
               CONNECT (remote_socket, sig_next(),		playlist,			psl_forward());
               CONNECT (remote_socket, sig_prev(),		playlist,			psl_backward());
               CONNECT (remote_socket, sig_stop(),		playlist,			psl_stop());
               CONNECT (remote_socket, sig_pause(),		listen,				pause());
               CONNECT (remote_socket, sig_setVolume(int),player,			setVolume(int));

               remote_socket->start();
           }
}
コード例 #20
0
ファイル: setpwnam.c プロジェクト: bdwalton/util-linux
/*
 *  setpwnam () --
 *	takes a struct passwd in which every field is filled in and valid.
 *	If the given username exists in the passwd file, the entry is
 *	replaced with the given entry.
 */
int setpwnam(struct passwd *pwd)
{
	FILE *fp = NULL, *pwf = NULL;
	int save_errno;
	int found;
	int namelen;
	int buflen = 256;
	int contlen, rc;
	char *linebuf = NULL;
	char *tmpname = NULL;

	pw_init();

	if ((fp = xfmkstemp(&tmpname)) == NULL)
		return -1;

	/* ptmp should be owned by root.root or root.wheel */
	if (fchown(fileno(fp), (uid_t) 0, (gid_t) 0) < 0)
		goto fail;

	/* acquire exclusive lock */
	if (lckpwdf() < 0)
		goto fail;
	pwf = fopen(PASSWD_FILE, "r");
	if (!pwf)
		goto fail;

	namelen = strlen(pwd->pw_name);

	linebuf = malloc(buflen);
	if (!linebuf)
		goto fail;

	/* parse the passwd file */
	found = false;

	/* Do you wonder why I don't use getpwent? Read comments at top of
	 * file */
	while (fgets(linebuf, buflen, pwf) != NULL) {
		contlen = strlen(linebuf);
		while (linebuf[contlen - 1] != '\n' && !feof(pwf)) {
			char *tmp;
			/* Extend input buffer if it failed getting the whole line,
			 * so now we double the buffer size */
			buflen *= 2;
			tmp = realloc(linebuf, buflen);
			if (tmp == NULL)
				goto fail;
			linebuf = tmp;
			/* And fill the rest of the buffer */
			if (fgets(&linebuf[contlen], buflen / 2, pwf) == NULL)
				break;
			contlen = strlen(linebuf);
			/* That was a lot of work for nothing. Gimme perl! */
		}

		/* Is this the username we were sent to change? */
		if (!found && linebuf[namelen] == ':' &&
		    !strncmp(linebuf, pwd->pw_name, namelen)) {
			/* Yes! So go forth in the name of the Lord and
			 * change it!  */
			if (putpwent(pwd, fp) < 0)
				goto fail;
			found = true;
			continue;
		}
		/* Nothing in particular happened, copy input to output */
		fputs(linebuf, fp);
	}

	/* xfmkstemp is too restrictive by default for passwd file */
	if (fchmod(fileno(fp), 0644) < 0)
		goto fail;
	rc = close_stream(fp);
	fp = NULL;
	if (rc != 0)
		goto fail;

	fclose(pwf);	/* I don't think I want to know if this failed */
	pwf = NULL;

	if (!found) {
		errno = ENOENT;	/* give me something better */
		goto fail;
	}

	/* we don't care if we can't remove the backup file */
	unlink(PASSWD_FILE ".OLD");
	/* we don't care if we can't create the backup file */
	ignore_result(link(PASSWD_FILE, PASSWD_FILE ".OLD"));
	/* we DO care if we can't rename to the passwd file */
	if (rename(tmpname, PASSWD_FILE) < 0)
		goto fail;
	/* finally:  success */
	ulckpwdf();
	return 0;

 fail:
	save_errno = errno;
	ulckpwdf();
	if (fp != NULL)
		fclose(fp);
	if (tmpname != NULL)
		unlink(tmpname);
	free(tmpname);
	if (pwf != NULL)
		fclose(pwf);
	free(linebuf);
	errno = save_errno;
	return -1;
}
コード例 #21
0
ファイル: script.c プロジェクト: avagin/util-linux
int
main(int argc, char **argv) {
	sigset_t block_mask, unblock_mask;
	struct sigaction sa;
	int ch;
	FILE *timingfd = NULL;

	enum { FORCE_OPTION = CHAR_MAX + 1 };

	static const struct option longopts[] = {
		{ "append",	no_argument,	   NULL, 'a' },
		{ "command",	required_argument, NULL, 'c' },
		{ "return",	no_argument,	   NULL, 'e' },
		{ "flush",	no_argument,	   NULL, 'f' },
		{ "force",	no_argument,	   NULL, FORCE_OPTION, },
		{ "quiet",	no_argument,	   NULL, 'q' },
		{ "timing",	optional_argument, NULL, 't' },
		{ "version",	no_argument,	   NULL, 'V' },
		{ "help",	no_argument,	   NULL, 'h' },
		{ NULL,		0, NULL, 0 }
	};

	setlocale(LC_ALL, "");
	setlocale(LC_NUMERIC, "C");	/* see comment above */
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while ((ch = getopt_long(argc, argv, "ac:efqt::Vh", longopts, NULL)) != -1)
		switch(ch) {
		case 'a':
			aflg = 1;
			break;
		case 'c':
			cflg = optarg;
			break;
		case 'e':
			eflg = 1;
			break;
		case 'f':
			fflg = 1;
			break;
		case FORCE_OPTION:
			forceflg = 1;
			break;
		case 'q':
			qflg = 1;
			break;
		case 't':
			if (optarg)
				if ((timingfd = fopen(optarg, "w")) == NULL)
					err(EXIT_FAILURE, _("cannot open %s"), optarg);
			tflg = 1;
			break;
		case 'V':
			printf(_("%s from %s\n"), program_invocation_short_name,
						  PACKAGE_STRING);
			exit(EXIT_SUCCESS);
			break;
		case 'h':
			usage(stdout);
			break;
		case '?':
		default:
			usage(stderr);
		}
	argc -= optind;
	argv += optind;

	if (argc > 0)
		fname = argv[0];
	else {
		fname = DEFAULT_OUTPUT;
		die_if_link(fname);
	}

	if ((fscript = fopen(fname, aflg ? "a" : "w")) == NULL) {
		warn(_("cannot open %s"), fname);
		fail();
	}

	shell = getenv("SHELL");
	if (shell == NULL)
		shell = _PATH_BSHELL;

	getmaster();
	if (!qflg)
		printf(_("Script started, file is %s\n"), fname);
	fixtty();

#ifdef HAVE_LIBUTEMPTER
	utempter_add_record(master, NULL);
#endif
	/* setup SIGCHLD handler */
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sa.sa_handler = finish;
	sigaction(SIGCHLD, &sa, NULL);

	/* init mask for SIGCHLD */
	sigprocmask(SIG_SETMASK, NULL, &block_mask);
	sigaddset(&block_mask, SIGCHLD);

	sigprocmask(SIG_SETMASK, &block_mask, &unblock_mask);
	child = fork();
	sigprocmask(SIG_SETMASK, &unblock_mask, NULL);

	if (child < 0) {
		warn(_("fork failed"));
		fail();
	}
	if (child == 0) {

		sigprocmask(SIG_SETMASK, &block_mask, NULL);
		subchild = child = fork();
		sigprocmask(SIG_SETMASK, &unblock_mask, NULL);

		if (child < 0) {
			warn(_("fork failed"));
			fail();
		}
		if (child) {
			if (!timingfd)
				timingfd = fdopen(STDERR_FILENO, "w");
			dooutput(timingfd);
		} else
			doshell();
	} else {
		sa.sa_handler = resize;
		sigaction(SIGWINCH, &sa, NULL);
	}
	doinput();

	if (close_stream(timingfd) != 0)
		errx(EXIT_FAILURE, _("write error"));
	return EXIT_SUCCESS;
}
コード例 #22
0
ファイル: output.c プロジェクト: Brainiarc7/libav
int main(int argc, char **argv)
{
    OutputStream video_st = { 0 }, audio_st = { 0 };
    const char *filename;
    AVOutputFormat *fmt;
    AVFormatContext *oc;
    int have_video = 0, have_audio = 0;
    int encode_video = 0, encode_audio = 0;

    /* Initialize libavcodec, and register all codecs and formats. */
    av_register_all();

    if (argc != 2) {
        printf("usage: %s output_file\n"
               "API example program to output a media file with libavformat.\n"
               "The output format is automatically guessed according to the file extension.\n"
               "Raw images can also be output by using '%%d' in the filename\n"
               "\n", argv[0]);
        return 1;
    }

    filename = argv[1];

    /* Autodetect the output format from the name. default is MPEG. */
    fmt = av_guess_format(NULL, filename, NULL);
    if (!fmt) {
        printf("Could not deduce output format from file extension: using MPEG.\n");
        fmt = av_guess_format("mpeg", NULL, NULL);
    }
    if (!fmt) {
        fprintf(stderr, "Could not find suitable output format\n");
        return 1;
    }

    /* Allocate the output media context. */
    oc = avformat_alloc_context();
    if (!oc) {
        fprintf(stderr, "Memory error\n");
        return 1;
    }
    oc->oformat = fmt;
    snprintf(oc->filename, sizeof(oc->filename), "%s", filename);

    /* Add the audio and video streams using the default format codecs
     * and initialize the codecs. */
    if (fmt->video_codec != AV_CODEC_ID_NONE) {
        add_video_stream(&video_st, oc, fmt->video_codec);
        have_video = 1;
        encode_video = 1;
    }
    if (fmt->audio_codec != AV_CODEC_ID_NONE) {
        add_audio_stream(&audio_st, oc, fmt->audio_codec);
        have_audio = 1;
        encode_audio = 1;
    }

    /* Now that all the parameters are set, we can open the audio and
     * video codecs and allocate the necessary encode buffers. */
    if (have_video)
        open_video(oc, &video_st);
    if (have_audio)
        open_audio(oc, &audio_st);

    av_dump_format(oc, 0, filename, 1);

    /* open the output file, if needed */
    if (!(fmt->flags & AVFMT_NOFILE)) {
        if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
            fprintf(stderr, "Could not open '%s'\n", filename);
            return 1;
        }
    }

    /* Write the stream header, if any. */
    avformat_write_header(oc, NULL);

    while (encode_video || encode_audio) {
        /* select the stream to encode */
        if (encode_video &&
            (!encode_audio || av_compare_ts(video_st.next_pts, video_st.enc->time_base,
                                            audio_st.next_pts, audio_st.enc->time_base) <= 0)) {
            encode_video = !write_video_frame(oc, &video_st);
        } else {
            encode_audio = !process_audio_stream(oc, &audio_st);
        }
    }

    /* Write the trailer, if any. The trailer must be written before you
     * close the CodecContexts open when you wrote the header; otherwise
     * av_write_trailer() may try to use memory that was freed on
     * av_codec_close(). */
    av_write_trailer(oc);

    /* Close each codec. */
    if (have_video)
        close_stream(oc, &video_st);
    if (have_audio)
        close_stream(oc, &audio_st);

    if (!(fmt->flags & AVFMT_NOFILE))
        /* Close the output file. */
        avio_close(oc->pb);

    /* free the stream */
    avformat_free_context(oc);

    return 0;
}
コード例 #23
0
ファイル: pxz.c プロジェクト: ip1981/pxz
int main( int argc, char **argv ) {
	int i;
	uint64_t p, threads, chunk_size;
	uint8_t *m;
	struct stat s;
	ssize_t rd, ts = 0;
	size_t page_size;
	struct sigaction new_action, old_action;
	struct utimbuf u;
	lzma_filter filters[LZMA_FILTERS_MAX + 1];
	lzma_options_lzma lzma_options;
	
	page_size = sysconf(_SC_PAGE_SIZE);
	xzcmd = malloc(xzcmd_max);
	if (!xzcmd) {
		fprintf(stderr, "Failed to allocate %lu bytes for xz command.\n", xzcmd_max);
		return -1;
	}
	snprintf(xzcmd, xzcmd_max, XZ_BINARY);
	
	parse_args(argc, argv);

	lzma_lzma_preset(&lzma_options, opt_complevel);

	filters[0].id = LZMA_FILTER_LZMA2;
	filters[0].options = &lzma_options;
	filters[1].id = LZMA_VLI_UNKNOWN;

	
	for (i=0; i<files; i++) {
		int std_in = file[i][0] == '-' && file[i][1] == '\0';
#ifdef _OPENMP
		threads = omp_get_max_threads();
#else
		threads = 1;
#endif
		if ( (rd=strlen(file[i])) >= 3 && !strncmp(&file[i][rd-3], ".xz", 3) ) {
			if (opt_verbose) {
				error(EXIT_FAILURE, 0, "ignoring '%s', it seems to be already compressed", file[i]);
			}
			continue;
		}
		
		if ( !std_in ) {
			if ( stat(file[i], &s)) {
				error(EXIT_FAILURE, errno, "can't stat '%s'", file[i]);
			}
		}
		
		chunk_size = opt_context_size * lzma_options.dict_size;
		chunk_size = (chunk_size + page_size)&~(page_size-1);
		
		if ( opt_verbose ) {
			fprintf(stderr, "context size per thread: %"PRIu64" B\n", chunk_size);
		}
		
		if ( opt_threads && (threads > opt_threads || opt_force) ) {
			threads = opt_threads;
		}
		
		fo = stdout;
		if ( std_in ) {
			fi = stdin;
		} else {
			if ( !(fi=fopen(file[i], "rb")) ) {
				error(EXIT_FAILURE, errno, "can't open '%s' for reading", file[i]);
			}
			if ( !opt_stdout ) {
				snprintf(str, sizeof(str), "%s.xz", file[i]);
				if ( !(fo=fopen(str, "wb")) ) {
					error(EXIT_FAILURE, errno, "error creating target archive '%s'", str);
				}
			}
		}
		
		if ( opt_verbose ) {
			if ( fo != stdout ) {
				fprintf(stderr, "%s -> %"PRIu64"/%"PRIu64" thread%c: [", file[i], threads, (s.st_size+chunk_size-1)/chunk_size, threads != 1 ? 's' : ' ');
			} else {
				fprintf(stderr, "%"PRIu64" thread%c: [", threads, threads != 1 ? 's' : ' ');
			}
			fflush(stderr);
		}
		
		m  = malloc(threads*chunk_size);
		
		new_action.sa_handler = term_handler;
		sigemptyset (&new_action.sa_mask);
		new_action.sa_flags = 0;
		
		sigaction(SIGINT, NULL, &old_action);
		if (old_action.sa_handler != SIG_IGN) sigaction(SIGINT, &new_action, NULL);
		sigaction(SIGHUP, NULL, &old_action);
		if (old_action.sa_handler != SIG_IGN) sigaction(SIGHUP, &new_action, NULL);
		sigaction(SIGTERM, NULL, &old_action);
		if (old_action.sa_handler != SIG_IGN) sigaction(SIGTERM, &new_action, NULL);
		
		ftemp = malloc(threads*sizeof(ftemp[0]));
		
		while ( !feof(fi) ) {
			size_t actrd;
			
			for (p=0; p<threads; p++) {
				ftemp[p] = tmpfile();
			}
			
			for ( actrd=rd=0; !feof(fi) && !ferror(fi) && (uint64_t)rd < threads*chunk_size; rd += actrd) {
				actrd = fread(&m[rd], 1, threads*chunk_size-actrd, fi);
			}
			if (ferror(fi)) {
				error(EXIT_FAILURE, errno, "error in reading input");
			}

#pragma omp parallel for private(p) num_threads(threads)
			for ( p=0; p<(rd+chunk_size-1)/chunk_size; p++ ) {
				off_t pt, len = rd-p*chunk_size >= chunk_size ? chunk_size : rd-p*chunk_size;
				uint8_t *mo;
				lzma_stream strm = LZMA_STREAM_INIT;
				lzma_ret ret;
				
				mo = malloc(BUFFSIZE);
				
				if ( lzma_stream_encoder(&strm, filters, LZMA_CHECK_CRC64) != LZMA_OK ) {
					error(EXIT_FAILURE, errno, "unable to initialize LZMA encoder");
				}
				
				for (pt=0; pt<len; pt+=BUFFSIZE) {
					strm.next_in = &m[p*chunk_size+pt];
					strm.avail_in = len-pt >= BUFFSIZE ? BUFFSIZE : len-pt;
					strm.next_out = mo;
					strm.avail_out = BUFFSIZE;
					do {
						ret = lzma_code(&strm, LZMA_RUN);
						if ( ret != LZMA_OK ) {
							error(EXIT_FAILURE, 0, "error in LZMA_RUN");
						}
						if ( BUFFSIZE - strm.avail_out > 0 ) {
							if ( !fwrite(mo, 1, BUFFSIZE - strm.avail_out, ftemp[p]) ) {
								error(EXIT_FAILURE, errno, "writing to temp file failed");
							}
							strm.next_out = mo;
							strm.avail_out = BUFFSIZE;
						}
					} while ( strm.avail_in );
				}
				
				strm.next_out = mo;
				strm.avail_out = BUFFSIZE;
				do {
					ret = lzma_code(&strm, LZMA_FINISH);
					if ( ret != LZMA_OK && ret != LZMA_STREAM_END ) {
						error(EXIT_FAILURE, 0, "error in LZMA_FINISH");
					}
					if ( BUFFSIZE - strm.avail_out > 0 ) {
						if ( !fwrite(mo, 1, BUFFSIZE - strm.avail_out, ftemp[p]) ) {
							error(EXIT_FAILURE, errno, "writing to temp file failed");
						}
						strm.next_out = mo;
						strm.avail_out = BUFFSIZE;
					}
				} while ( ret == LZMA_OK );
				lzma_end(&strm);
				
				free(mo);
				
				if ( opt_verbose ) {
					fprintf(stderr, "%"PRIu64" ", p);
					fflush(stderr);
				}
			}
			
			for ( p=0; p<threads; p++ ) {
				rewind(ftemp[p]);
				while ( (rd=fread(buf, 1, sizeof(buf), ftemp[p])) > 0 ) {
					if ( fwrite(buf, 1, rd, fo) != (size_t)rd ) {
						error(0, errno, "writing to archive failed");
						if ( fo != stdout && unlink(str) ) {
							error(0, errno, "error deleting corrupted target archive %s", str);
						}
						exit(EXIT_FAILURE);
					} else ts += rd;
				}
				if (rd < 0) {
					error(0, errno, "reading from temporary file failed");
					if ( fo != stdout && unlink(str) ) {
						error(0, errno, "error deleting corrupted target archive %s", str);
					}
					exit(EXIT_FAILURE);
				}
				if ( close_stream(ftemp[p]) ) {
					error(0, errno, "I/O error in temp file");
				}
			}
		}
		
		if ( fi != stdin && close_stream(fi) ) {
			error(0, errno, "I/O error in input file");
		}
		
		if ( opt_verbose ) {
			fprintf(stderr, "] ");
		}

		free(ftemp);
		
		if ( fo != stdout ) {
			if ( close_stream(fo) ) {
				error(0, errno, "I/O error in target archive");
			}
		} else return 0;
		
		if ( chmod(str, s.st_mode) ) {
			error(0, errno, "warning: unable to change archive permissions");
		}

		u.actime = s.st_atime;
		u.modtime = s.st_mtime;
		
		if ( utime(str, &u) ) {
			error(0, errno, "warning: unable to change archive timestamp");
		}
		
		sigaction(SIGINT, &old_action, NULL);
		sigaction(SIGHUP, &old_action, NULL);
		sigaction(SIGTERM, &old_action, NULL);
		
		if ( opt_verbose ) {
			fprintf(stderr, "%"PRIu64" -> %zd %3.3f%%\n", s.st_size, ts, ts*100./s.st_size);
		}
		
		if ( !opt_keep && unlink(file[i]) ) {
			error(0, errno, "error deleting input file %s", file[i]);
		}
	}
	
	return 0;
}
コード例 #24
0
ファイル: output.c プロジェクト: rforge/rcwb
/**
 * Prints a corpus, typically (some of) the matches of a query.
 *
 * (Not sure why it's called "catalog"; is this a pun on the cat keyword? -- AH 2012-07-17)
 *
 * The query is represented by a subcorpus (cl); only results
 * #first..#last; will be printed; use (0,-1) for entire corpus.
 *
 * @param cl     The corpus/subcorpus/query to output.
 * @param rd     Block of output redirection info; if NULL, default settings will be used.
 * @param first  Offset of first match to print.
 * @param last   Offset of last match to print.
 * @param mode   Print mode to use.
 */
void 
catalog_corpus(CorpusList *cl,
               struct Redir *rd,
               int first, int last,
               PrintMode mode)
{
  int i;
  Boolean printHeader = False;

  struct Redir default_redir;

  if ((cl == NULL) || (!access_corpus(cl)))
    return;

  if (!rd) {
    default_redir.name = NULL;
    default_redir.mode = "w";
    default_redir.stream = NULL;
    default_redir.is_pipe = 0;
    rd = &default_redir;
  }

  if (!open_stream(rd, cl->corpus->charset)) {
    cqpmessage(Error, "Can't open output stream.");
    return;
  }

  assert(rd->stream);

  /* ======================================== BINARY OUTPUT */

  if (rangeoutput || mode == PrintBINARY) {

    for (i = 0; (i < cl->size); i++) {
      fwrite(&(cl->range[i].start), sizeof(int), 1, rd->stream);
      fwrite(&(cl->range[i].end), sizeof(int), 1, rd->stream);
    }

  }
  else {

    /* ====================================== ASCII, SGML OR HTML OUTPUT */

/*     if (CD.printStructureTags == NULL) */
/*       CD.printStructureTags = ComputePrintStructures(cl); */
    /* now done for current_corpus in options.c ! */

    printHeader = GlobalPrintOptions.print_header;

    /* questionable... */
    if (GlobalPrintMode == PrintHTML)
      printHeader = True;

#ifndef __MINGW__
    if (rd->is_pipe && handle_sigpipe) {
      if (signal(SIGPIPE, bp_signal_handler) == SIG_ERR)
        perror("Can't install signal handler for broken pipe (ignored)");
    }
#endif

    /* do the job. */
    
    verify_context_descriptor(cl->corpus, &CD, 1);
    
    broken_pipe = 0;

    /* first version (Oli Christ):
       if ((!silent || printHeader) && !(rd->stream == stdout || rd->is_paging));
       */
    /* second version (Stefan Evert):     
       if (printHeader || (mode == PrintASCII && !(rd->stream == stdout || rd->is_paging))); 
    */

    /* header is printed _only_ when explicitly requested now (or, when in HTML mode; see above);
     * previous behaviour was to print header automatically when saving results to a file;
     * this makes sense when such files are created to document the results of a corpus search,
     * but nowadays they are mostly used for automatic post-processing (e.g. in a Web interface),
     * where the header is just a nuisance that has to be stripped.
     */
    if (printHeader) {
      /* print something like a header */
      print_corpus_info_header(cl, rd->stream, mode, 1);
    }
    else if (printNrMatches && mode == PrintASCII)
      fprintf(rd->stream, "%d matches.\n", cl->size);
    
    print_output(cl, rd->stream, 
                 isatty(fileno(rd->stream)) || rd->is_paging, 
                 &CD, first, last, mode);

#ifndef __MINGW__
    if (rd->is_paging && handle_sigpipe) {
      if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        perror("Can't reinstall SIG_IGN signal handler");
    }
#endif
    
  }

  close_stream(rd);
}
コード例 #25
0
ファイル: output.c プロジェクト: jing-git/dhcpd-pools
/*! \brief The xml output formats.
 * FIXME: This function should return void.
 */
int output_xml(void)
{
	unsigned int i;
	struct range_t *range_p;
	double range_size;
	struct shared_network_t *shared_p;
	int ret;
	FILE *outfile;

	if (config.output_file[0]) {
		outfile = fopen(config.output_file, "w+");
		if (outfile == NULL) {
			err(EXIT_FAILURE, "output_xml: %s", config.output_file);
		}
	} else {
		outfile = stdout;
	}

	range_p = ranges;
	range_size = get_range_size(range_p);
	shared_p = shared_networks;

	fprintf(outfile, "<dhcpstatus>\n");

	if (config.output_format[0] == 'X' || config.output_format[0] == 'J') {
		struct leases_t *l;
		for (l = leases; l != NULL; l = l->hh.next) {
			if (l->type == ACTIVE) {
				fputs("<active_lease>\n\t<ip>", outfile);
				fputs(ntop_ipaddr(&l->ip), outfile);
				fputs("</ip>\n\t<macaddress>", outfile);
				if (l->ethernet != NULL) {
					fputs(l->ethernet, outfile);
				}
				fputs("</macaddress>\n</active_lease>\n",
				      outfile);
			}
		}
	}

	if (config.output_limit[1] & BIT1) {
		for (i = 0; i < num_ranges; i++) {
			fprintf(outfile, "<subnet>\n");
			if (range_p->shared_net) {
				fprintf(outfile,
					"\t<location>%s</location>\n",
					range_p->shared_net->name);
			} else {
				fprintf(outfile, "\t<location></location>\n");
			}

			fprintf(outfile, "\t<network></network>\n");
			fprintf(outfile, "\t<netmask></netmask>\n");
			fprintf(outfile, "\t<range>%s ",
				ntop_ipaddr(&range_p->first_ip));
			fprintf(outfile, "- %s</range>\n",
				ntop_ipaddr(&range_p->last_ip));
			fprintf(outfile, "\t<gateway></gateway>\n");
			fprintf(outfile, "\t<defined>%g</defined>\n",
				range_size);
			fprintf(outfile, "\t<used>%g</used>\n",
				range_p->count);
			fprintf(outfile, "\t<free>%g</free>\n",
				range_size - range_p->count);
			range_p++;
			range_size = get_range_size(range_p);
			fprintf(outfile, "</subnet>\n");
		}
	}

	if (config.output_limit[1] & BIT2) {
		for (i = 0; i < num_shared_networks; i++) {
			shared_p++;
			fprintf(outfile, "<shared-network>\n");
			fprintf(outfile, "\t<location>%s</location>\n",
				shared_p->name);
			fprintf(outfile, "\t<defined>%g</defined>\n",
				shared_p->available);
			fprintf(outfile, "\t<used>%g</used>\n",
				shared_p->used);
			fprintf(outfile, "\t<free>%g</free>\n",
				shared_p->available - shared_p->used);
			fprintf(outfile, "</shared-network>\n");
		}
	}

	if (config.output_limit[0] & BIT3) {
		fprintf(outfile, "<summary>\n");
		fprintf(outfile, "\t<location>%s</location>\n",
			shared_networks->name);
		fprintf(outfile, "\t<defined>%g</defined>\n",
			shared_networks->available);
		fprintf(outfile, "\t<used>%g</used>\n", shared_networks->used);
		fprintf(outfile, "\t<free>%g</free>\n",
			shared_networks->available - shared_networks->used);
		fprintf(outfile, "</summary>\n");
	}

	fprintf(outfile, "</dhcpstatus>\n");
	if (outfile == stdout) {
		ret = fflush(stdout);
		if (ret) {
			warn("output_xml: fflush");
		}
	} else {
		ret = close_stream(outfile);
		if (ret) {
			warn("output_xml: fclose");
		}
	}

	return 0;
}
コード例 #26
0
ファイル: output.c プロジェクト: rforge/rcwb
/**
 * Outputs a blob of information on the mother-corpus of the specified cl.
 */
void 
corpus_info(CorpusList *cl)
{
  FILE *fd;
  FILE *outfd;
  char buf[CL_MAX_LINE_LENGTH];
  int i, ok, stream_ok;
  struct Redir rd = { NULL, NULL, NULL, 0, 0 }; /* for paging (with open_stream()) */

  CorpusList *mom = NULL;
  CorpusProperty p;

  /* first, the case where cl is actually a full corpus */
  if (cl->type == SYSTEM) {

    stream_ok = open_stream(&rd, ascii);
    outfd = (stream_ok) ? rd.stream : NULL; /* use pager, or simply print to stdout if it fails */
    /* print size (should be the mother_size entry) */
    fprintf(outfd, "Size:    %d\n", cl->mother_size);
    /* print charset */
    fprintf(outfd, "Charset: ");

    if (cl->corpus->charset == unknown_charset) {
      fprintf(outfd, "<unsupported> (%s)\n", cl_corpus_property(cl->corpus, "charset"));
    }
    else {
      fprintf(outfd, "%s\n", cl_charset_name(cl->corpus->charset));
    }
    /* print properties */
    fprintf(outfd, "Properties:\n");
    p = cl_first_corpus_property(cl->corpus);
    if (p == NULL)
      fprintf(outfd, "\t<none>\n");
    else 
      for ( ; p != NULL; p = cl_next_corpus_property(p))
        fprintf(outfd, "\t%s = '%s'\n", p->property, p->value);
    fprintf(outfd, "\n");
    

    if (cl->corpus->info_file == NULL)
      fprintf(outfd, "No further information available about %s\n", cl->name);
    else if ((fd = open_file(cl->corpus->info_file, "rb")) == NULL)
      cqpmessage(Warning,
                 "Can't open info file %s for reading",
                 cl->corpus->info_file);
    else {
      ok = 1;
      do {
        i = fread(&buf[0], sizeof(char), CL_MAX_LINE_LENGTH, fd);
        if (fwrite(&buf[0], sizeof(char), i, outfd) != i)
          ok = 0;
      } while (ok && (i == CL_MAX_LINE_LENGTH));
      fclose(fd);
    }

    if (stream_ok) 
      close_stream(&rd);        /* close pipe to pager if we were using it */
  }
  /* if cl is not actually a full corpus, try to find its mother and call this function on that */
  else if (cl->mother_name == NULL)
    cqpmessage(Warning, 
               "Corrupt corpus information for %s", cl->name);
  else if ((mom = findcorpus(cl->mother_name, SYSTEM, 0)) != NULL) {
    corpus_info(mom);
  }
  /* if the mother is not loaded, we just have to print an error */
  else {
    cqpmessage(Info,
               "%s is a subcorpus of %s which is not loaded. Try 'info %s' "
               "for information about %s.\n",
               cl->name, cl->mother_name, cl->mother_name, cl->mother_name);
  }
}
コード例 #27
0
ファイル: output.c プロジェクト: jing-git/dhcpd-pools
/*! \brief Text output format, which is the default.
 * FIXME: This function should return void. */
int output_txt(void)
{
	unsigned int i;
	struct range_t *range_p;
	double range_size;
	struct shared_network_t *shared_p;
	int ret;
	FILE *outfile;
	int max_ipaddr_length = config.dhcp_version == VERSION_6 ? 39 : 16;

	if (config.output_file[0]) {
		outfile = fopen(config.output_file, "w+");
		if (outfile == NULL) {
			err(EXIT_FAILURE, "output_txt: %s", config.output_file);
		}
	} else {
		outfile = stdout;
	}

	range_p = ranges;
	range_size = get_range_size(range_p);
	shared_p = shared_networks;

	if (config.output_limit[0] & BIT1) {
		fprintf(outfile, "Ranges:\n");
		fprintf
		    (outfile,
		     "%-20s%-*s   %-*s %5s %5s %10s  %5s %5s %9s",
		     "shared net name",
		     max_ipaddr_length,
		     "first ip",
		     max_ipaddr_length,
		     "last ip",
		     "max", "cur", "percent", "touch", "t+c", "t+c perc");
		if (config.backups_found == true) {
			fprintf(outfile, "     bu  bu perc");
		}
		fprintf(outfile, "\n");
	}
	if (config.output_limit[1] & BIT1) {
		for (i = 0; i < num_ranges; i++) {
			if (range_p->shared_net) {
				fprintf(outfile, "%-20s",
					range_p->shared_net->name);
			} else {
				fprintf(outfile, "not_defined         ");
			}
			/* Outputting of first_ip and last_ip need to be
			 * separate since ntop_ipaddr always returns the
			 * same buffer */
			fprintf(outfile, "%-*s",
				max_ipaddr_length,
				ntop_ipaddr(&range_p->first_ip));
			fprintf(outfile,
				" - %-*s %5g %5g %10.3f  %5g %5g %9.3f",
				max_ipaddr_length,
				ntop_ipaddr(&range_p->last_ip),
				range_size,
				range_p->count,
				(float)(100 * range_p->count) / range_size,
				range_p->touched,
				range_p->touched + range_p->count,
				(float)(100 *
					(range_p->touched +
					 range_p->count)) / range_size);
			if (config.backups_found == true) {
				fprintf(outfile, "%7g %8.3f",
					range_p->backups,
					(float)(100 * range_p->backups) /
					range_size);
			}
			fprintf(outfile, "\n");
			range_p++;
			range_size = get_range_size(range_p);
		}
	}
	if (config.output_limit[1] & BIT1 && config.output_limit[0] & BIT2) {
		fprintf(outfile, "\n");
	}
	if (config.output_limit[0] & BIT2) {
		fprintf(outfile, "Shared networks:\n");
		fprintf(outfile,
			"name                   max   cur     percent  touch    t+c  t+c perc");
		if (config.backups_found == true) {
			fprintf(outfile, "     bu  bu perc");
		}
		fprintf(outfile, "\n");
	}
	if (config.output_limit[1] & BIT2) {
		for (i = 0; i < num_shared_networks; i++) {
			shared_p++;
			fprintf(outfile,
				"%-20s %5g %5g %10.3f %7g %6g %9.3f",
				shared_p->name, shared_p->available,
				shared_p->used,
				(float)(100 * shared_p->used) /
				shared_p->available, shared_p->touched,
				shared_p->touched + shared_p->used,
				(float)(100 *
					(shared_p->touched +
					 shared_p->used)) /
				shared_p->available);
			if (config.backups_found == true) {
				fprintf(outfile, "%7g %8.3f",
					shared_p->backups,
					(float)(100 * shared_p->backups) /
					shared_p->available);
			}

			fprintf(outfile, "\n");
		}
	}
	if (config.output_limit[1] & BIT2 && config.output_limit[0] & BIT3) {
		fprintf(outfile, "\n");
	}
	if (config.output_limit[0] & BIT3) {
		fprintf(outfile, "Sum of all ranges:\n");
		fprintf(outfile,
			"name                   max   cur     percent  touch    t+c  t+c perc");

		if (config.backups_found == true) {
			fprintf(outfile, "     bu  bu perc");
		}
		fprintf(outfile, "\n");
	}
	if (config.output_limit[1] & BIT3) {
		fprintf(outfile, "%-20s %5g %5g %10.3f %7g %6g %9.3f",
			shared_networks->name,
			shared_networks->available,
			shared_networks->used,
			(float)(100 * shared_networks->used) /
			shared_networks->available,
			shared_networks->touched,
			shared_networks->touched + shared_networks->used,
			(float)(100 *
				(shared_networks->touched +
				 shared_networks->used)) /
			shared_networks->available);

		if (config.backups_found == true) {
			fprintf(outfile, "%7g %8.3f",
				shared_networks->backups,
				(float)(100 * shared_networks->backups) /
				shared_networks->available);
		}
		fprintf(outfile, "\n");
	}
	if (outfile == stdout) {
		ret = fflush(stdout);
		if (ret) {
			warn("output_txt: fflush");
		}
	} else {
		ret = close_stream(outfile);
		if (ret) {
			warn("output_txt: fclose");
		}
	}

	return 0;
}
コード例 #28
0
ファイル: output.c プロジェクト: rforge/rcwb
/* tabulate specified query result, using settings from global list of tabulation items;
   return value indicates whether tabulation was successful (otherwise, generates error message) */
int
print_tabulation(CorpusList *cl, int first, int last, struct Redir *rd)
{
  TabulationItem item = TabulationList;
  int current;
  
  if (! cl) 
    return 0;

  if (first <= 0) first = 0;    /* make sure that first and last match to tabulate are in range */
  if (last >= cl->size) last = cl->size - 1;

  while (item) {                /* obtain attribute handles for tabulation items */
    if (item->attribute_name) {
      if (NULL != (item->attribute = cl_new_attribute(cl->corpus, item->attribute_name, ATT_POS))) {
        item->attribute_type = ATT_POS;
      }
      else if (NULL != (item->attribute = cl_new_attribute(cl->corpus, item->attribute_name, ATT_STRUC))) {
        item->attribute_type = ATT_STRUC;
        if (! cl_struc_values(item->attribute)) {
          cqpmessage(Error, "No annotated values for s-attribute ``%s'' in named query %s", item->attribute_name, cl->name);
          return 0;
        }
      }
      else {
        cqpmessage(Error, "Can't find attribute ``%s'' for named query %s", item->attribute_name, cl->name);
        return 0;
      }
    }
    else {
      item->attribute_type = ATT_NONE; /* no attribute -> print corpus position */
    }
    if (cl->size > 0) {
      /* work around bug: anchor validation will fail for empty query result (but then loop below is void anyway) */
      if (! (pt_validate_anchor(cl, item->anchor1) && pt_validate_anchor(cl, item->anchor2)))
	return 0;
    }
    item = item->next;
  }

  if (! open_stream(rd, cl->corpus->charset)) {
    cqpmessage(Error, "Can't redirect output to file or pipe\n");
    return 0;
  }

  /* tabulate selected attribute values for matches <first> .. <last> */
  for (current = first; current <= last; current++) {
    TabulationItem item = TabulationList;
    while (item) {
      int start = pt_get_anchor_cpos(cl, current, item->anchor1, item->offset1);
      int end   = pt_get_anchor_cpos(cl, current, item->anchor2, item->offset2);
      int cpos;

      if (start < 0 || end < 0) /* one of the anchors is undefined -> print single undefined value for entire range */
        start = end = -1;

      for (cpos = start; cpos <= end; cpos++) {
        if (item->attribute_type == ATT_NONE) {
          fprintf(rd->stream, "%d", cpos);
        }
        else {
          if (cpos >= 0) {      /* undefined anchors print empty string */
            char *string = NULL;
            if (item->attribute_type == ATT_POS) 
              string = cl_cpos2str(item->attribute, cpos);
            else
              string = cl_cpos2struc2str(item->attribute, cpos);
            if (string) {
              if (item->flags) {
                char *copy = cl_strdup(string);
                cl_string_canonical(copy, cl->corpus->charset, item->flags);
                fprintf(rd->stream, "%s", copy);
                cl_free(copy);
              }
              else {
                fprintf(rd->stream, "%s", string);
              }
            }
          }
        }
        if (cpos < end)         /* multiple values for tabulation item are separated by blanks */
          fprintf(rd->stream, " "); 
      }
      if (item->next)           /* multiple tabulation items are separated by TABs */
        fprintf(rd->stream, "\t");
      item = item->next;
    }
    fprintf(rd->stream, "\n");
  }
  
  close_stream(rd);
  free_tabulation_list();
  return 1;
}
コード例 #29
0
/*PAGE
 *
 * daemon
 *
 * This task runs forever.  It waits for service requests on the FTP port
 * (port 21 by default).  When a request is received, it opens a new session
 * to handle those requests until the connection is closed.
 *
 * Input parameters:
 *   NONE
 *
 * Output parameters:
 *   NONE
 */
static void
daemon(rtems_task_argument args __attribute__((unused)))
{
  int                 s;
  socklen_t	      addrLen;
  struct sockaddr_in  addr;
  FTPD_SessionInfo_t  *info = NULL;


  s = socket(PF_INET, SOCK_STREAM, 0);
  if (s < 0)
    syslog(LOG_ERR, "ftpd: Error creating socket: %s", serr());

  addr.sin_family      = AF_INET;
  addr.sin_port        = htons(rtems_ftpd_configuration.port);
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  memset(addr.sin_zero, 0, sizeof(addr.sin_zero));

  if (0 > bind(s, (struct sockaddr *)&addr, sizeof(addr)))
    syslog(LOG_ERR, "ftpd: Error binding control socket: %s", serr());
  else if (0 > listen(s, 1))
    syslog(LOG_ERR, "ftpd: Error listening on control socket: %s", serr());
  else while (1)
  {
    int ss;
    addrLen = sizeof(addr);
    ss = accept(s, (struct sockaddr *)&addr, &addrLen);
    if (0 > ss)
      syslog(LOG_ERR, "ftpd: Error accepting control connection: %s", serr());
    else if(!set_socket_timeout(ss, ftpd_timeout))
      close_socket(ss);
    else
    {
      info = task_pool_obtain();
      if (NULL == info)
      {
        close_socket(ss);
      }
      else
      {
        info->ctrl_socket = ss;
        if ((info->ctrl_fp = fdopen(info->ctrl_socket, "r+")) == NULL)
        {
          syslog(LOG_ERR, "ftpd: fdopen() on socket failed: %s", serr());
          close_stream(info);
          task_pool_release(info);
        }
        else
        {
          /* Initialize corresponding SessionInfo structure */
          info->def_addr = addr;
          if(0 > getsockname(ss, (struct sockaddr *)&addr, &addrLen))
          {
            syslog(LOG_ERR, "ftpd: getsockname(): %s", serr());
            close_stream(info);
            task_pool_release(info);
          }
          else
          {
            info->use_default = 1;
            info->ctrl_addr  = addr;
            info->pasv_socket = -1;
            info->data_socket = -1;
            info->xfer_mode   = TYPE_A;
            info->data_addr.sin_port =
              htons(ntohs(info->ctrl_addr.sin_port) - 1);
            info->idle = ftpd_timeout;
            /* Wakeup the session task.  The task will call task_pool_release
               after it closes connection. */
            rtems_event_send(info->tid, FTPD_RTEMS_EVENT);
          }
        }
      }
    }
  }
  rtems_task_delete(RTEMS_SELF);
}
コード例 #30
0
ファイル: fifo.cpp プロジェクト: Jongsix/espeak
static void* say_thread(void*)
{
  ENTER("say_thread");

  SHOW_TIME("say_thread > post my_sem_stop_is_acknowledged\n");

  // announce that thread is started
  sem_post(&my_sem_stop_is_acknowledged);

  int look_for_inactivity=0;

  while(1)
    {
      SHOW_TIME("say_thread > wait for my_sem_start_is_required\n");

      int a_start_is_required = 0;
      if (look_for_inactivity)
	{
	  a_start_is_required = sleep_until_start_request_or_inactivity();
	  if (!a_start_is_required)
	    {
	      close_stream();
	    }
	}
      look_for_inactivity = 1;

      if (!a_start_is_required)
	{
	  while ((sem_wait(&my_sem_start_is_required) == -1) && errno == EINTR)
	    {
	      continue; // Restart when interrupted by handler
	    }
	}
      SHOW_TIME("say_thread > get my_sem_start_is_required\n");

      SHOW_TIME("say_thread > my_command_is_running = 1\n");
      my_command_is_running = 1;

      while( my_command_is_running)
	{
	  SHOW_TIME("say_thread > locking\n");
	  int a_status = pthread_mutex_lock(&my_mutex);
	  assert (!a_status);
	  t_espeak_command* a_command = (t_espeak_command*)pop();

	  if (a_command == NULL)
	    {
	      SHOW_TIME("say_thread > text empty (talking=0) \n");
	      a_status = pthread_mutex_unlock(&my_mutex);
	      SHOW_TIME("say_thread > unlocked\n");
	      SHOW_TIME("say_thread > my_command_is_running = 0\n");
	      my_command_is_running = 0;
	    }
	  else
	    {
	      display_espeak_command(a_command);
	      // purge start semaphore
	      SHOW_TIME("say_thread > purge my_sem_start_is_required\n");
	      while(0 == sem_trywait(&my_sem_start_is_required))
		{
		};

	      if (my_stop_is_required)
		{
		  SHOW_TIME("say_thread > my_command_is_running = 0\n");
		  my_command_is_running = 0;
		}
	      SHOW_TIME("say_thread > unlocking\n");
	      a_status = pthread_mutex_unlock(&my_mutex);

	      if (my_command_is_running)
		{
		  process_espeak_command(a_command);
		}
	      delete_espeak_command(a_command);
	    }
	}

      if (my_stop_is_required)
	{
	  // no mutex required since the stop command is synchronous
	  // and waiting for my_sem_stop_is_acknowledged
	  init(1);

	  // purge start semaphore
	  SHOW_TIME("say_thread > purge my_sem_start_is_required\n");
	  while(0==sem_trywait(&my_sem_start_is_required))
	    {
	    };

	  // acknowledge the stop request
	  SHOW_TIME("say_thread > post my_sem_stop_is_acknowledged\n");
	  int a_status = sem_post(&my_sem_stop_is_acknowledged);
	  assert( a_status != -1);
	}
      // and wait for the next start
      SHOW_TIME("say_thread > wait for my_sem_start_is_required\n");
    }

  return NULL;
}