status_t rdef_compile(const char *outputFile) { clear_error(); if (outputFile == NULL || outputFile[0] == '\0') { rdef_err = B_BAD_VALUE; return rdef_err; } rsrc_file = outputFile; rdef_err = open_output_file(); if (rdef_err != B_OK) return rdef_err; for (ptr_iter_t i = input_files.begin(); (i != input_files.end()) && (rdef_err == B_OK); ++i) { char *path = (char *)*i; AddIncludeDir add(path); compile_file(path); } close_output_file(); return rdef_err; }
static COStream find_output_file(const char* pathname, boolean make) { struct outfile_struct * os; COStream altout; for ( os = outfiles ; ; os = os->next ) { if ( os == NULL ) { if ( !make ) return NULL; altout = open_output_file( pathname, binary ); if ( altout == NULL ) return make_buffer_output_stream(); os = allocate(sizeof(struct outfile_struct),MemoryStream); os->next = outfiles; os->out = altout; outfiles = os; break; } if ( strcmp(pathname, cos_pathname(os->out)) == 0 ) { altout = os->out; break; } } return altout; }
void create_jpg_file(char *output_name, t_image *mlx_image_struct, unsigned char *mlx_buffer) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE *outfile; JSAMPROW row_pointer[1]; int row_stride; cinfo.err = jpeg_std_error(&jerr); open_output_file(output_name, &outfile, &cinfo); cinfo.image_width = mlx_image_struct->size[0]; cinfo.image_height = mlx_image_struct->size[1]; jpeg_set_defaults(&cinfo); jpeg_start_compress(&cinfo, TRUE); row_stride = cinfo.image_width * 3; while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = &mlx_buffer[cinfo.next_scanline * row_stride]; jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_finish_compress(&cinfo); fclose(outfile); jpeg_destroy_compress(&cinfo); free(mlx_buffer); }
void Monitor::init(string filename) { fname = filename; active = true; open_output_file(filename); }
void generate_lr_parser (string fname, string_list predefs) { full_verbose = 1; verbose = 1; warning ("generating lr parser..."); open_output_file (fname, "lr", "c"); generate_std_includes (predefs); generate_meta_rules (); close_output_file (); };
// constructor // SequenceDataOutputFile_FASTA::SequenceDataOutputFile_FASTA( const char* file_name, const char* compressor, const char* options) : m_file_name(file_name) { m_file = open_output_file( file_name, compressor, options ); }
int main(int argc, char *argv[]) { char pts_name[PTSNAME_BUFLEN]; int pts_master; int fd1, fd2; /* For "who"'s output */ int rc = 0; if (argc < 3) { fprintf (stderr, "Usage: %s file1 file2\n", argv[0]); exit(1); } fd1 = open_output_file(argv[1]); fd2 = open_output_file(argv[2]); /* STEP 1: Create the pty device */ if ((pts_master = ptym_open(pts_name)) < 0) { fprintf(stderr, "ptym_open failed, exiting..\n"); rc = 1; goto out; } /* STEP 2: Add an entry */ if (spawn_utempter(pts_master, "add") != 0) { rc = 1; goto out; } /* STEP 3: "who" for our caller to verify if the entry was added */ (void)spawn_who(fd1); /* STEP 4: Delete the entry */ if (spawn_utempter(pts_master, "del") != 0) { rc = 1 ; goto out; } /* STEP 5: "who" to verify the deletion */ (void)spawn_who(fd2); out: close(pts_master); close (fd1); close (fd2); exit(rc); }
/** * Opens all output files. */ static void open_output_files() { /* open files for stdout/stderr */ if ((out_file != NULL) || (err_file != NULL)) { if ((null_fd = open("/dev/null", O_WRONLY)) == -1) die("Can't open /dev/null: %s\n", strerror (errno)); close(STDIN_FILENO); dup2(null_fd, STDIN_FILENO); if (out_file != NULL) { if ((out_fd = open_output_file(out_file)) == -1) { die("Can't open \"%s\" for stdout: %s\n", out_file, strerror(errno)); } } else { out_fd = null_fd; } if (err_file != NULL) { if ((out_file != NULL) && (strcmp(err_file, out_file) == 0)) err_fd = out_fd; else if ((err_fd = open_output_file(err_file)) == -1) { die("Can't open \"%s\" for stderr: %s\n", err_file, strerror (errno)); } } else { err_fd = null_fd; } } }
Boolean open_alignment_output(char *filename,ALNOUT_OPTPTR alnout_opt) { if(!alnout_opt->output_clustal && !alnout_opt->output_nbrf && !alnout_opt->output_gcg && !alnout_opt->output_phylip && !alnout_opt->output_gde && !alnout_opt->output_nexus && !alnout_opt->output_gscope && !alnout_opt->output_relacs && !alnout_opt->output_rsf && !alnout_opt->output_tfa) { error("You must select an alignment output format"); return FALSE; } if(alnout_opt->output_clustal) if((alnout_opt->clustal_outfile=open_output_file(filename, "CLUSTAL", "aln", alnout_opt->clustal_outname))==NULL) return FALSE; if(alnout_opt->output_nbrf) if((alnout_opt->nbrf_outfile=open_output_file(filename, "NBRF", "pir", alnout_opt->nbrf_outname))==NULL) return FALSE; if(alnout_opt->output_gcg) if((alnout_opt->gcg_outfile=open_output_file(filename, "GCG", "msf", alnout_opt->gcg_outname))==NULL) return FALSE; if(alnout_opt->output_phylip) if((alnout_opt->phylip_outfile=open_output_file(filename, "PHYLIP", "phy", alnout_opt->phylip_outname))==NULL) return FALSE; if(alnout_opt->output_gde) if((alnout_opt->gde_outfile=open_output_file(filename, "GDE", "gde", alnout_opt->gde_outname))==NULL) return FALSE; if(alnout_opt->output_tfa) if((alnout_opt->tfa_outfile=open_output_file(filename, "FASTA", "tfa", alnout_opt->tfa_outname))==NULL) return FALSE; if(alnout_opt->output_nexus) if(alnout_opt->output_nexus) if((alnout_opt->nexus_outfile=open_output_file(filename, "NEXUS", "nxs", alnout_opt->nexus_outname))==NULL) return FALSE; if(alnout_opt->output_gscope) if((alnout_opt->gscope_outfile=open_output_file(filename, "GSCOPE", "msf", alnout_opt->gscope_outname))==NULL) return FALSE; if(alnout_opt->output_relacs) if((alnout_opt->relacs_outfile=open_output_file(filename, "RELACS", "xml", alnout_opt->relacs_outname))==NULL) return FALSE; if(alnout_opt->output_rsf) { if((alnout_opt->rsf_outfile=open_output_file(filename, "RSF", "rsf", alnout_opt->rsf_outname))==NULL) return FALSE; } return TRUE; }
// when both input file and output file are provided. void general_case(char *input_file, char *output_file, struct list_s *list, int reverse) { int fd_in, fd_out; fd_in = open_input_file(input_file); fd_out = open_output_file(output_file); read_input(fd_in, list); sort(list, reverse); write_to_file(fd_out, list); close(fd_in); close(fd_out); }
/*===========================================================================*/ FILE *open_output_using_big_buffer(char *filename,size_t bytes) { FILE *ans; /*-------------------------------------------------------*/ ans=open_output_file(filename); big_output_file_buffer=(unsigned char *) g_malloc(bytes); if (big_output_file_buffer!=((unsigned char *) NULL)){ setvbuf(ans,(char *) big_output_file_buffer,_IOFBF,(size_t) bytes);} /*-------------------------------------------------------*/ return(ans); }
void generate(const txtvc::command_line& args) { // Open files first and handle error on open ourselves. std::ofstream header, source; open_output_file(header, args.output_header()); open_output_file(source, args.output_source()); // Enable exceptions, so that we don't need to do error checking // on subsequent output operations. header.exceptions(std::ios::badbit | std::ios::eofbit | std::ios::failbit); source.exceptions(std::ios::badbit | std::ios::eofbit | std::ios::failbit); try { generate_header_prolog(header, args); generate_source_prolog(source, args); for (const auto& filename : args.fontfiles()) { txtvc::bfgfont font(filename); const auto font_data_identifier = font.name() + "_data"; generate_source_font_data(source, font, font_data_identifier); generate_source_font_spec(source, font, font_data_identifier); generate_header_font_declaration(header, font.name()); } generate_header_epilog(header); header.close(); source.close(); } catch (const std::ios::failure&) { const auto error = errno; if (error) { // errno is nonzero: assume I/O error throw std::runtime_error(strerror(error)); } // errno is zero: assume programmer's error and rethrow throw; } }
static struct shenc * setup_enc(char * filename) { struct shenc * shenc; int ret; shenc = calloc (1, sizeof(*shenc)); if (!shenc) return NULL; ret = ctrlfile_get_params(filename, &shenc->ainfo, &shenc->stream_type); if (ret < 0) { fprintf(stderr, "Error opening control file (%s)\n", filename); goto err; } fprintf(stderr, "Input file: %s\n", shenc->ainfo.input_file_name_buf); fprintf(stderr, "Output file: %s\n", shenc->ainfo.output_file_name_buf); /* Setup encoder */ shenc->encoder = shcodecs_encoder_init(shenc->ainfo.xpic, shenc->ainfo.ypic, shenc->stream_type); if (!shenc->encoder) { fprintf(stderr, "Error initializing encoder\n"); goto err; } shcodecs_encoder_set_input_callback(shenc->encoder, get_input, shenc); shcodecs_encoder_set_output_callback(shenc->encoder, write_output, shenc); /* set parameters for use in encoding */ ret = ctrlfile_set_enc_param(shenc->encoder, filename); if (ret < 0) { fprintf(stderr, "Problem with encoder params in control file!\n"); goto err; } /* open input YUV data file */ if (open_input_image_file(&shenc->ainfo)) { fprintf(stderr, "Error opening input file\n"); goto err; } if (open_output_file(&shenc->ainfo)) { goto err; } return shenc; err: cleanup(shenc); return NULL; }
static int extract_file(LHAReader *reader, char *filename, LHADecoderProgressCallback callback, void *callback_data) { FILE *fstream; char *tmp_filename = NULL; int result; // Construct filename? if (filename == NULL) { tmp_filename = full_path_for_header(reader->curr_file); if (tmp_filename == NULL) { return 0; } filename = tmp_filename; } // Create decoder. If the file cannot be created, there is no // need to even create an output file. If successful, open the // output file and decode. result = 0; if (open_decoder(reader, callback, callback_data)) { fstream = open_output_file(reader, filename); if (fstream != NULL) { result = do_decode(reader, fstream); fclose(fstream); } } // Set timestamp on file: if (result) { set_timestamps_from_header(filename, reader->curr_file); } free(tmp_filename); return result; }
print_all_bindings() { Ref<sdlModule> bmod; Set<Ref<sdlModule> > omods; W_COERCE(Shore::begin_transaction(3)); Ref<sdlDeclaration> lpt; for (lpt = g_module_list; lpt != NULL; lpt = lpt->next) { bmod = ((Ref<sdlModDecl> &)lpt)->dmodule; omods.add(bmod); } // this should be a readonly transacton, so never commit. if (omods.get_size()>0) { if (open_output_file(omods.get_elt(0)->name.string()) == 0) print_cxx_binding(omods); } SH_DO(SH_COMMIT_TRANSACTION); return 0; }
static int process_bind(char *lname) { Ref<sdlModule> bmod; Set<Ref<sdlModule> > omods; // first, [re]open stdout for appropriate name. // do this outside of a transaction.. W_COERCE(Shore::begin_transaction(3)); bmod = lookup_module(lname); if (bmod == 0) // null value { cerr << "couldn't find module " << lname << endl; return -1; } omods.add(bmod); if (open_output_file(lname)==0) print_cxx_binding(omods); // this should be a readonly transaction, so never commit. SH_DO(SH_COMMIT_TRANSACTION); return 0; }
void generate_leftcorner_parser (string basename, string_list predefs) { compute_leftcorner_relations (); generate_goal_for_rules (); generate_goal_relation (); warning ("generating left corner parser..."); open_output_file (basename, "leftcorner", "c"); generate_std_includes (predefs); code_lattices (); code_lexicon (); generate_meta_rules (); generate_rule_declarations (); code_nodenrs (basename); if (editor) generate_enter_templates (); warning ("coding syntax rules..."); code_goal_for_rules (); code_goal_relation (); generate_parser_routines (); warning ("coding postamble and main..."); generate_start_rule (predefs); generate_module_interface (basename, predefs); generate_main (basename); close_output_file (); };
int receive_file() { // Create an output file with the url_path name if(0 != open_output_file()) { printf("Could not open the output file\n"); return -1; } // Sending 'retr' command char retr_cmd[50]; memset(retr_cmd, 0, 50); strcpy(retr_cmd, "retr "); strcat(retr_cmd, msg.url_path); strcat(retr_cmd, "\n"); printf("Command: %s\n", retr_cmd); if(write(ctrl_ftp.socket_fd, retr_cmd, strlen(retr_cmd)) < 0) { printf("Could not send 'retr' command\n"); return -1; } // Reading the server response char buf[MAX_SIZE_MEDIUM]; int bytes_read = 0; memset(buf, 0, MAX_SIZE_MEDIUM - 1); while((bytes_read = read(recv_ftp.socket_fd, buf, 255)) > 0) { buf[bytes_read] = '\0'; //printf("Read : %s\n", buf); fwrite(buf, sizeof(char), bytes_read, o_file.fd); memset(buf, 0, 255); } fclose(o_file.fd); return 0; }
static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm) { AVOutputFormat *output_format; int ret; output_format = av_guess_format(NULL, ffm->params.file, NULL); if (output_format == NULL) { printf("Couldn't find an appropriate muxer for '%s'\n", ffm->params.file); return FFM_ERROR; } ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL, NULL); if (ret < 0) { printf("Couldn't initialize output context: %s\n", av_err2str(ret)); return FFM_ERROR; } ffm->output->oformat->video_codec = AV_CODEC_ID_NONE; ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE; if (!init_streams(ffm)) { free_avformat(ffm); return FFM_ERROR; } ret = open_output_file(ffm); if (ret != FFM_SUCCESS) { free_avformat(ffm); return ret; } return FFM_SUCCESS; }
void gen_basic_array(CONTEXT *c) { NODE *cf,*hf; char *ots,*maybe_space; int i; NODE *k,*v; CONTEXT *ctx; /* check: can we proceed? */ if ((c->am.first_key!=NULL) && (c->am.first_key->type==nt_int) && (c->am.last_key!=NULL) && (c->am.last_key->type==nt_int)) c->generator=gen_basic_array; else { c->generator=NULL; return; } cf=open_output_file(c->c_file); hf=open_output_file(c->h_file); k=node_new(); k->type=nt_int; if (c->value_c_type==NULL) ots="int"; else ots=c->value_c_type; maybe_space=(ots[strlen(ots)-1]=='*')?"":" "; of_write(hf,"/* basic array lookup for map \"%s\" */\n\n", c->id); of_write(hf,"extern %s%s__icemap_%s_array[];\n", ots,maybe_space,c->id); if (c->am.first_key->x==0) of_write(hf,"#define %s_lookup(idx) \\\n" " (__icemap_%s_array[(idx)])\n\n", c->id,c->id); else of_write(hf,"#define %s_lookup(idx) \\\n" " (__icemap_%s_array[(idx)-%d])\n\n", c->id,c->id,c->am.first_key->x); of_write(cf,"/* basic array lookup for map \"%s\" */\n\n", c->id); of_write(cf,"%s%s__icemap_%s_array[%d]={\n", ots,maybe_space,c->id,c->am.last_key->x-c->am.first_key->x+1); of_indent(cf,2); for (i=c->am.first_key->x;i<=c->am.last_key->x;i++) { k->x=i; v=arrow_map_lookup(&(c->am),k); if (v==NULL) of_write_wrapped(cf,"0 /* missing key */,"); else if (v->type==nt_int) of_write_wrapped(cf,"0x%X,",v->x); else of_write_wrapped(cf,"\"%s\",",v->cp); } of_unindent(cf,2); of_write(cf,"\n};\n\n"); node_delete(k); for (ctx=context_stack->parent;ctx;ctx=ctx->parent) ctx->leaves++; }
int main(int argc, char **argv) { twolame_options *encopts = NULL; SNDFILE *inputfile = NULL; FILE *outputfile = NULL; short int *pcmaudio = NULL; int samples_read = 0; unsigned int frame_count = 0; unsigned char *mp2buffer = NULL; int mp2fill_size = 0; int audioReadSize = 0; // Allocate memory for the PCM audio data if ((pcmaudio = (short int *) calloc(AUDIOBUFSIZE, sizeof(short int))) == NULL) { fprintf(stderr, "Error: pcmaudio memory allocation failed\n"); exit(ERR_MEM_ALLOC); } // Allocate memory for the encoded MP2 audio data if ((mp2buffer = (unsigned char *) calloc(MP2BUFSIZE, sizeof(unsigned char))) == NULL) { fprintf(stderr, "Error: mp2buffer memory allocation failed\n"); exit(ERR_MEM_ALLOC); } // Initialise Encoder Options Structure encopts = twolame_init(); if (encopts == NULL) { fprintf(stderr, "Error: initializing libtwolame encoder failed.\n"); exit(ERR_MEM_ALLOC); } // Get options and parameters from the command line parse_args(argc, argv, encopts); // Open the input file inputfile = open_input_file( inputfilename ); twolame_set_num_channels( encopts, sfinfo.channels ); twolame_set_in_samplerate( encopts, sfinfo.samplerate ); // Open the output file outputfile = open_output_file( outputfilename ); // display file settings print_file_config( inputfile, twolame_get_verbosity(encopts) ); // initialise twolame with this set of options if (twolame_init_params( encopts ) != 0) { fprintf(stderr, "Error: configuring libtwolame encoder failed.\n"); exit(ERR_INVALID_PARAM); } // display encoder settings twolame_print_config( encopts ); // Only encode a single frame of mpeg audio ? if (single_frame_mode) audioReadSize = 1152; else audioReadSize = AUDIOBUFSIZE; // Now do the reading/encoding/writing while ((samples_read = sf_read_short( inputfile, pcmaudio, audioReadSize )) > 0) { int bytes_out = 0; // Force byte swapping if requested if (byteswap) { int i; for (i = 0; i<samples_read; i++) { short tmp = pcmaudio[i]; char *src = (char*)&tmp; char *dst = (char*)&pcmaudio[i]; dst[0] = src[1]; dst[1] = src[0]; } } // Calculate the number of samples we have (per channel) samples_read /= sfinfo.channels; // Do swapping of left and right channels if requested if (channelswap && sfinfo.channels == 2) { int i; for(i=0; i<samples_read; i++) { short tmp = pcmaudio[(2*i)]; pcmaudio[(2*i)] = pcmaudio[(2*i)+1]; pcmaudio[(2*i)+1] = tmp; } } // Encode the audio to MP2 mp2fill_size = twolame_encode_buffer_interleaved( encopts, pcmaudio, samples_read, mp2buffer, MP2BUFSIZE); // Stop if we don't have any bytes (probably don't have enough audio for a full frame of mpeg audio) if (mp2fill_size==0) break; if (mp2fill_size<0) { fprintf(stderr,"error while encoding audio: %d\n", mp2fill_size); exit(ERR_WRITING_OUTPUT); } // Write the encoded audio out bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile); if (bytes_out<=0) { perror("error while writing to output file"); exit(ERR_WRITING_OUTPUT); } // Only single frame ? if (single_frame_mode) break; // Display Progress frame_count += (samples_read / 1152); if (twolame_get_verbosity(encopts)>0) { fprintf(stderr, "[%04i", frame_count); //fprintf(stderr, "/%04i", (int)(sfinfo.frames / sfinfo.channels / 1152)); fprintf(stderr, "]\r"); fflush(stderr); } } // // flush any remaining audio. (don't send any new audio data) There // should only ever be a max of 1 frame on a flush. There may be zero // frames if the audio data was an exact multiple of 1152 // mp2fill_size = twolame_encode_flush( encopts, mp2buffer, MP2BUFSIZE); if (mp2fill_size>0) { int bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile); if (bytes_out<=0) { perror("error while writing to output file"); exit(ERR_WRITING_OUTPUT); } } if (twolame_get_verbosity(encopts)>1) { fprintf(stderr, "\nEncoding Finished.\n"); } // Close input and output files sf_close( inputfile ); fclose( outputfile ); // Close the libtwolame encoder twolame_close(&encopts); // Free up memory free(pcmaudio); free(mp2buffer); return (ERR_NO_ERROR); }
/* * Make duplicate object index. * * If referred tag is only one, direct link which points the tag is generated. * Else if two or more tag exists, indirect link which points the tag list * is generated. */ int makedupindex(void) { STRBUF *sb = strbuf_open(0); STRBUF *tmp = strbuf_open(0); STRBUF *command = strbuf_open(0); int definition_count = 0; char srcdir[MAXPATHLEN]; int db; FILEOP *fileop = NULL; FILE *op = NULL; FILE *ip = NULL; snprintf(srcdir, sizeof(srcdir), "../%s", SRCS); for (db = GTAGS; db < GTAGLIM; db++) { const char *kind = kinds[db]; const char *option = options[db]; int writing = 0; int count = 0; int entry_count = 0; const char *ctags_xid, *ctags_x; char tag[IDENTLEN], prev[IDENTLEN], first_line[MAXBUFLEN]; if (gtags_exist[db] == 0) continue; prev[0] = 0; first_line[0] = 0; /* * construct command line. */ strbuf_reset(command); strbuf_sprintf(command, "%s -x%s --result=ctags-xid --encode-path=\" \t\" --nofilter=path", quote_shell(global_path), option); /* * Optimization when the --dynamic option is specified. */ if (dynamic) { strbuf_puts(command, " --nosource"); if (db != GSYMS) strbuf_puts(command, " --nofilter=sort"); } strbuf_puts(command, " \".*\""); if ((ip = popen(strbuf_value(command), "r")) == NULL) die("cannot execute command '%s'.", strbuf_value(command)); while ((ctags_xid = strbuf_fgets(sb, ip, STRBUF_NOCRLF)) != NULL) { char fid[MAXFIDLEN]; ctags_x = parse_xid(ctags_xid, fid, NULL); /* tag name */ (void)strcpy_withterm(tag, ctags_x, sizeof(tag), ' '); if (strcmp(prev, tag)) { count++; if (vflag) fprintf(stderr, " [%d] adding %s %s\n", count, kind, tag); if (writing) { if (!dynamic) { fputs_nl(gen_list_end(), op); fputs_nl(body_end, op); fputs_nl(gen_page_end(), op); close_file(fileop); html_count++; } writing = 0; /* * cache record: " <fid>\0<entry number>\0" */ strbuf_reset(tmp); strbuf_putc(tmp, ' '); strbuf_putn(tmp, count - 1); strbuf_putc(tmp, '\0'); strbuf_putn(tmp, entry_count); cache_put(db, prev, strbuf_value(tmp), strbuf_getlen(tmp) + 1); } /* single entry */ if (first_line[0]) { char fid[MAXFIDLEN]; const char *ctags_x = parse_xid(first_line, fid, NULL); const char *lno = nextelement(ctags_x); strbuf_reset(tmp); strbuf_puts_withterm(tmp, lno, ' '); strbuf_putc(tmp, '\0'); strbuf_puts(tmp, fid); cache_put(db, prev, strbuf_value(tmp), strbuf_getlen(tmp) + 1); } /* * Chop the tail of the line. It is not important. * strlimcpy(first_line, ctags_x, sizeof(first_line)); */ strncpy(first_line, ctags_xid, sizeof(first_line)); first_line[sizeof(first_line) - 1] = '\0'; strlimcpy(prev, tag, sizeof(prev)); entry_count = 0; } else { /* duplicate entry */ if (first_line[0]) { char fid[MAXFIDLEN]; const char *ctags_x = parse_xid(first_line, fid, NULL); if (!dynamic) { char path[MAXPATHLEN]; snprintf(path, sizeof(path), "%s/%s/%d.%s", distpath, dirs[db], count, HTML); fileop = open_output_file(path, cflag); op = get_descripter(fileop); fputs_nl(gen_page_begin(tag, SUBDIR), op); fputs_nl(body_begin, op); fputs_nl(gen_list_begin(), op); fputs_nl(gen_list_body(srcdir, ctags_x, fid), op); } writing = 1; entry_count++; first_line[0] = 0; } if (!dynamic) { fputs_nl(gen_list_body(srcdir, ctags_x, fid), op); } entry_count++; } } if (db == GTAGS) definition_count = count; if (pclose(ip) != 0) die("'%s' failed.", strbuf_value(command)); if (writing) { if (!dynamic) { fputs_nl(gen_list_end(), op); fputs_nl(body_end, op); fputs_nl(gen_page_end(), op); close_file(fileop); html_count++; } /* * cache record: " <fid>\0<entry number>\0" */ strbuf_reset(tmp); strbuf_putc(tmp, ' '); strbuf_putn(tmp, count); strbuf_putc(tmp, '\0'); strbuf_putn(tmp, entry_count); cache_put(db, prev, strbuf_value(tmp), strbuf_getlen(tmp) + 1); } if (first_line[0]) { char fid[MAXFIDLEN]; const char *ctags_x = parse_xid(first_line, fid, NULL); const char *lno = nextelement(ctags_x); strbuf_reset(tmp); strbuf_puts_withterm(tmp, lno, ' '); strbuf_putc(tmp, '\0'); strbuf_puts(tmp, fid); cache_put(db, prev, strbuf_value(tmp), strbuf_getlen(tmp) + 1); } } strbuf_close(sb); strbuf_close(tmp); strbuf_close(command); return definition_count; }
static void output_cpu_logs(char *dirname) { int i; struct per_cpu_data *pcd; size_t n, idx, start, end, len; size_t padding; char *source, fname[MAX_FNAME + 1]; /* allocate subbuf memory */ subbuf = GETBUF(chan.subbuf_size); if (!subbuf) { error(FATAL, "cannot allocate memory\n"); } for (i = 0; i < kt->cpus; i++) { pcd = &per_cpu[i]; if (pcd->buf.subbufs_produced == 0 && pcd->buf.offset == 0) { if (is_global == 1) { error(WARNING, "There is no data in the relay buffer.\n"); break; } else { error(WARNING, "[cpu:%d]There is no data in the relay buffer.\n", i); continue; } } end = pcd->buf.subbufs_produced + 1; if (pcd->buf.subbufs_produced >= chan.n_subbufs) { start = end - chan.n_subbufs; } else { start = 0; } create_output_filename(fname, MAX_FNAME, i); fprintf(fp, "--- generating '%s/%s' ---\n", dirname, fname); fprintf(fp, " subbufs ready on relayfs:%ld\n", (long)end); fprintf(fp, " n_subbufs:%ld, read subbuf from:%ld(%ld) " "to:%ld(%ld) (offset:0-%ld)\n\n", (long)chan.n_subbufs, (long)start, (long)(start % chan.n_subbufs), (long)end-1, (long)((end-1) % chan.n_subbufs), (long) pcd->buf.offset); outfp = open_output_file(dirname, fname); for (n = start; n < end; n++) { /* read relayfs subbufs and write to log file */ idx = n % chan.n_subbufs; source = pcd->buf.start + idx * chan.subbuf_size; if (old_format == 1) { readmem((ulong)pcd->buf.padding + sizeof(unsigned) * idx, KVADDR, &padding, sizeof(unsigned), "padding", FAULT_ON_ERROR); } else { readmem((ulong)pcd->buf.padding + sizeof(padding) * idx, KVADDR, &padding, sizeof(padding), "padding", FAULT_ON_ERROR); } if (n == end - 1) { len = pcd->buf.offset; } else { len = chan.subbuf_size; } if (old_format == 1) { source += sizeof(unsigned int); len -= sizeof(unsigned int) + padding; } else { len -= padding; } if (len > 0) { readmem((ulong)source, KVADDR, subbuf, len, "subbuf", FAULT_ON_ERROR); if (fwrite(subbuf, len, 1, outfp) != 1) { error(FATAL, "cannot write log data\n"); } } } fclose(outfp); outfp = NULL; /* * -a option retrieve the old data of subbuffer where the * probe record is written at that time. */ if (retrieve_all == 1 && start != 0) { strncat(fname, ".may_broken", MAX_FNAME); fprintf(fp, "--- generating '%s/%s' ---\n", dirname, fname); fprintf(fp, " read subbuf %ld(%ld) (offset:%ld-%ld)\n", (long)start-1, (long)((start-1) % chan.n_subbufs), (long)pcd->buf.offset, (long)chan.subbuf_size); outfp = open_output_file(dirname, fname); idx = (start - 1) % chan.n_subbufs; source = pcd->buf.start + idx * chan.subbuf_size + pcd->buf.offset; len = chan.subbuf_size - pcd->buf.offset; if (len) { readmem((ulong)source, KVADDR, subbuf, len, "may_broken_subbuf", FAULT_ON_ERROR); if (fwrite(subbuf, len, 1, outfp) != 1) { error(FATAL, "cannot write log data(may_broken)\n"); } } fclose(outfp); outfp = NULL; } if (is_global == 1) break; } if (subbuf) { FREEBUF(subbuf); subbuf = NULL; } return; }
int main(int argc,char **argv, char **envp) { struct plugins_list_entry *list; char config_file[SRVBUFLEN]; int logf; /* getopt() stuff */ extern char *optarg; extern int optind, opterr, optopt; int errflag, cp; #if defined HAVE_MALLOPT mallopt(M_CHECK_ACTION, 0); #endif umask(077); compute_once(); memset(cfg_cmdline, 0, sizeof(cfg_cmdline)); memset(&config, 0, sizeof(struct configuration)); memset(&config_file, 0, sizeof(config_file)); log_notifications_init(&log_notifications); config.acct_type = ACCT_PMBGP; find_id_func = NULL; plugins_list = NULL; errflag = 0; rows = 0; /* getting commandline values */ while (!errflag && ((cp = getopt(argc, argv, ARGS_PMBGPD)) != -1)) { cfg_cmdline[rows] = malloc(SRVBUFLEN); switch (cp) { case 'L': strlcpy(cfg_cmdline[rows], "bgp_daemon_ip: ", SRVBUFLEN); strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows])); rows++; break; case 'l': strlcpy(cfg_cmdline[rows], "bgp_daemon_port: ", SRVBUFLEN); strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows])); rows++; break; case 'D': strlcpy(cfg_cmdline[rows], "daemonize: true", SRVBUFLEN); rows++; break; case 'd': debug = TRUE; strlcpy(cfg_cmdline[rows], "debug: true", SRVBUFLEN); rows++; break; case 'f': strlcpy(config_file, optarg, sizeof(config_file)); break; case 'F': strlcpy(cfg_cmdline[rows], "pidfile: ", SRVBUFLEN); strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows])); rows++; break; case 'S': strlcpy(cfg_cmdline[rows], "syslog: ", SRVBUFLEN); strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows])); rows++; break; case 'h': usage_daemon(argv[0]); exit(0); break; case 'V': version_daemon(PMBGPD_USAGE_HEADER); exit(0); break; default: usage_daemon(argv[0]); exit(1); break; } } /* post-checks and resolving conflicts */ if (strlen(config_file)) { if (parse_configuration_file(config_file) != SUCCESS) exit(1); } else { if (parse_configuration_file(NULL) != SUCCESS) exit(1); } list = plugins_list; while (list) { list->cfg.acct_type = ACCT_PMBGP; set_default_preferences(&list->cfg); if (!strcmp(list->type.string, "core")) { memcpy(&config, &list->cfg, sizeof(struct configuration)); config.name = list->name; config.type = list->type.string; } list = list->next; } if (config.files_umask) umask(config.files_umask); if (config.daemon) { if (debug || config.debug) printf("WARN ( %s/core ): debug is enabled; forking in background. Logging to standard error (stderr) will get lost.\n", config.name); daemonize(); } initsetproctitle(argc, argv, envp); if (config.syslog) { logf = parse_log_facility(config.syslog); if (logf == ERR) { config.syslog = NULL; printf("WARN ( %s/core ): specified syslog facility is not supported. Logging to standard error (stderr).\n", config.name); } else openlog(NULL, LOG_PID, logf); Log(LOG_INFO, "INFO ( %s/core ): Start logging ...\n", config.name); } if (config.logfile) { config.logfile_fd = open_output_file(config.logfile, "a", FALSE); while (list) { list->cfg.logfile_fd = config.logfile_fd ; list = list->next; } } if (config.proc_priority) { int ret; ret = setpriority(PRIO_PROCESS, 0, config.proc_priority); if (ret) Log(LOG_WARNING, "WARN ( %s/core ): proc_priority failed (errno: %d)\n", config.name, errno); else Log(LOG_INFO, "INFO ( %s/core ): proc_priority set to %d\n", config.name, getpriority(PRIO_PROCESS, 0)); } if (strlen(config_file)) { char canonical_path[PATH_MAX], *canonical_path_ptr; canonical_path_ptr = realpath(config_file, canonical_path); if (canonical_path_ptr) Log(LOG_INFO, "INFO ( %s/core ): Reading configuration file '%s'.\n", config.name, canonical_path); } else Log(LOG_INFO, "INFO ( %s/core ): Reading configuration from cmdline.\n", config.name); pm_setproctitle("%s [%s]", "Core Process", config.proc_name); if (config.pidfile) write_pid_file(config.pidfile); /* signal handling we want to inherit to plugins (when not re-defined elsewhere) */ signal(SIGCHLD, startup_handle_falling_child); /* takes note of plugins failed during startup phase */ signal(SIGHUP, reload); /* handles reopening of syslog channel */ signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, reload_maps); /* sets to true the reload_maps flag */ signal(SIGPIPE, SIG_IGN); /* we want to exit gracefully when a pipe is broken */ signal(SIGINT, my_sigint_handler); signal(SIGTERM, my_sigint_handler); if (!config.nfacctd_bgp) config.nfacctd_bgp = BGP_DAEMON_ONLINE; if (!config.nfacctd_bgp_port) config.nfacctd_bgp_port = BGP_TCP_PORT; bgp_prepare_daemon(); skinny_bgp_daemon(); }
/** \ingroup HighLevel_Sign \brief Sign a file \param inname Input filename \param outname Output filename. If NULL, a name is constructed from the input filename. \param seckey Secret Key to use for signing \param armored Write armoured text, if set. \param overwrite May overwrite existing file, if set. \return 1 if OK; else 0; */ unsigned pgp_sign_file(pgp_io_t *io, const char *inname, const char *outname, const pgp_seckey_t *seckey, const char *hashname, const int64_t from, const uint64_t duration, const unsigned armored, const unsigned cleartext, const unsigned overwrite) { pgp_create_sig_t *sig; pgp_sig_type_t sig_type; pgp_hash_alg_t hash_alg; pgp_memory_t *infile; pgp_output_t *output; pgp_hash_t *hash; unsigned ret; uint8_t keyid[PGP_KEY_ID_SIZE]; int fd_out; sig = NULL; sig_type = PGP_SIG_BINARY; infile = NULL; output = NULL; hash = NULL; fd_out = 0; /* find the hash algorithm */ hash_alg = pgp_str_to_hash_alg(hashname); if (hash_alg == PGP_HASH_UNKNOWN) { (void) fprintf(io->errs, "pgp_sign_file: unknown hash algorithm: \"%s\"\n", hashname); return 0; } /* read input file into buf */ infile = pgp_memory_new(); if (!pgp_mem_readfile(infile, inname)) { return 0; } /* setup output file */ fd_out = open_output_file(&output, inname, outname, (armored) ? "asc" : "gpg", overwrite); if (fd_out < 0) { pgp_memory_free(infile); return 0; } /* set up signature */ sig = pgp_create_sig_new(); if (!sig) { pgp_memory_free(infile); pgp_teardown_file_write(output, fd_out); return 0; } pgp_start_sig(sig, seckey, hash_alg, sig_type); if (cleartext) { if (pgp_writer_push_clearsigned(output, sig) != 1) { return 0; } /* Do the signing */ pgp_write(output, pgp_mem_data(infile), (unsigned)pgp_mem_len(infile)); pgp_memory_free(infile); /* add signature with subpackets: */ /* - creation time */ /* - key id */ ret = pgp_writer_use_armored_sig(output) && pgp_add_time(sig, (int64_t)from, "birth") && pgp_add_time(sig, (int64_t)duration, "expiration"); if (ret == 0) { pgp_teardown_file_write(output, fd_out); return 0; } pgp_keyid(keyid, PGP_KEY_ID_SIZE, &seckey->pubkey, hash_alg); ret = pgp_add_issuer_keyid(sig, keyid) && pgp_end_hashed_subpkts(sig) && pgp_write_sig(output, sig, &seckey->pubkey, seckey); pgp_teardown_file_write(output, fd_out); if (ret == 0) { PGP_ERROR_1(&output->errors, PGP_E_W, "%s", "Cannot sign file as cleartext"); } } else { /* set armoured/not armoured here */ if (armored) { pgp_writer_push_armor_msg(output); } /* write one_pass_sig */ pgp_write_one_pass_sig(output, seckey, hash_alg, sig_type); /* hash file contents */ hash = pgp_sig_get_hash(sig); hash->add(hash, pgp_mem_data(infile), (unsigned)pgp_mem_len(infile)); #if 1 /* output file contents as Literal Data packet */ pgp_write_litdata(output, pgp_mem_data(infile), (const int)pgp_mem_len(infile), PGP_LDT_BINARY); #else /* XXX - agc - sync with writer.c 1094 for ops_writez */ pgp_setup_memory_write(&litoutput, &litmem, bufsz); pgp_setup_memory_write(&zoutput, &zmem, bufsz); pgp_write_litdata(litoutput, pgp_mem_data(pgp_mem_data(infile), (const int)pgp_mem_len(infile), PGP_LDT_BINARY); pgp_writez(zoutput, pgp_mem_data(litmem), pgp_mem_len(litmem)); #endif /* add creation time to signature */ pgp_add_time(sig, (int64_t)from, "birth"); pgp_add_time(sig, (int64_t)duration, "expiration"); /* add key id to signature */ pgp_keyid(keyid, PGP_KEY_ID_SIZE, &seckey->pubkey, hash_alg); pgp_add_issuer_keyid(sig, keyid); pgp_end_hashed_subpkts(sig); pgp_write_sig(output, sig, &seckey->pubkey, seckey); /* tidy up */ pgp_teardown_file_write(output, fd_out); pgp_create_sig_delete(sig); pgp_memory_free(infile); ret = 1; } return ret; }
/* sign a file, and put the signature in a separate file */ int pgp_sign_detached(pgp_io_t *io, const char *f, char *sigfile, pgp_seckey_t *seckey, const char *hash, const int64_t from, const uint64_t duration, const unsigned armored, const unsigned overwrite) { pgp_create_sig_t *sig; pgp_hash_alg_t hash_alg; pgp_output_t *output; pgp_memory_t *mem; uint8_t keyid[PGP_KEY_ID_SIZE]; int fd; /* find out which hash algorithm to use */ hash_alg = pgp_str_to_hash_alg(hash); if (hash_alg == PGP_HASH_UNKNOWN) { (void) fprintf(io->errs,"Unknown hash algorithm: %s\n", hash); return 0; } /* setup output file */ fd = open_output_file(&output, f, sigfile, (armored) ? "asc" : "sig", overwrite); if (fd < 0) { (void) fprintf(io->errs,"Can't open output file: %s\n", f); return 0; } /* create a new signature */ sig = pgp_create_sig_new(); pgp_start_sig(sig, seckey, hash_alg, PGP_SIG_BINARY); /* read the contents of 'f', and add that to the signature */ mem = pgp_memory_new(); if (!pgp_mem_readfile(mem, f)) { pgp_teardown_file_write(output, fd); return 0; } /* set armoured/not armoured here */ if (armored) { pgp_writer_push_armor_msg(output); } pgp_sig_add_data(sig, pgp_mem_data(mem), pgp_mem_len(mem)); pgp_memory_free(mem); /* calculate the signature */ pgp_add_time(sig, from, "birth"); pgp_add_time(sig, (int64_t)duration, "expiration"); pgp_keyid(keyid, sizeof(keyid), &seckey->pubkey, hash_alg); pgp_add_issuer_keyid(sig, keyid); pgp_end_hashed_subpkts(sig); pgp_write_sig(output, sig, &seckey->pubkey, seckey); pgp_teardown_file_write(output, fd); pgp_seckey_free(seckey); return 1; }
FILE *RB_TROFF_Generate_Header_Start( FILE *dest_doc, struct RB_header *cur_header ) { static char *manpage = NULL; int sec_item; if ( manpage == NULL ) manpage = RB_malloc( MAXPATHLEN ); if ( cur_header->name ) { char *file = RB_Get_FullDocname( cur_header->owner->filename ); char *name = basename( cur_header->name ); char *path = basename( file ); int len, i; struct RB_Item *item; char *section = NULL; /* Search for SECTION header and use this section for man pages */ sec_item = RB_Get_Item_Type("SECTION"); for( item = cur_header->items; item ; item = item->next) { if( item->type == sec_item ) { /* Item found, search for nonempty line */ for(i = 0 ; i < item->no_lines; i++ ) { section = item->lines[i]->line; while( *section && utf8_isspace(*section) ) section++; if( *section ) { /* nonempty line found, break */ break; } } break; } } len = path - file; memcpy( manpage, file, len ); /* we found a section header, strip at next whitespace */ if( section && *section ) { char *to, *ptr; ptr = RB_malloc( strlen(section) + 1 ); to = ptr; while( *section && !utf8_isspace(*section) ) { *to++ = *section++; } *to++ = 0; section = ptr; } else { section = man_section; } sprintf( manpage + len, "%s.%s%s", name, section, compress_ext ); dest_doc = open_output_file( manpage ); if ( dest_doc == NULL ) { RB_Panic( "Cannot open %s: %s\n", manpage, strerror( errno ) ); } RB_Say( "+ Generating man page \"%s\"\n", SAY_INFO, manpage ); /* Check for aliases if we have symlink() */ #ifdef HAVE_SYMLINK for ( i = 1; i < cur_header->no_names; i++ ) { char *base = basename( cur_header->names[i] ); char *buf = strchr( manpage, 0 ) + 1; memcpy( buf, file, len ); sprintf( buf + len, "%s.%s%s", base, section, compress_ext ); unlink( buf ); symlink( basename( manpage ), buf ); RB_Say( "+ Linked with \"%s\"\n", SAY_INFO, buf ); } #else USE( i ); #endif /* Append document type and title */ fprintf( dest_doc, ".\\\" Source: %s\n", cur_header->owner->filename->fullname ); write_comment( dest_doc, COMMENT_ROBODOC COMMENT_COPYRIGHT ); fprintf( dest_doc, ".TH %s %s \"", name, section ); { time_t ttp; char timeBuffer[255]; time( &ttp ); strftime( timeBuffer, sizeof timeBuffer, "%b %d, %Y", localtime( &ttp ) ); fputs( timeBuffer, dest_doc ); if ( name > cur_header->name ) { path = cur_header->name; len = name - path - 1; } else len = strlen( path = name ); if ( len >= (signed)sizeof timeBuffer ) len = sizeof timeBuffer - 1; memcpy( timeBuffer, path, len ); timeBuffer[len] = 0; fprintf( dest_doc, "\" %s \"%s Reference\"\n", timeBuffer, timeBuffer ); } if( section != man_section ) { free(section); } } return dest_doc; }
/* * makedefineindex: make definition index (including alphabetic index) * * @param[in] file definition index file * @param[in] total definitions total * @param[out] defines @defines * Globals used (input): * tag cache XXX: should this be global output, not input? */ int makedefineindex(const char *file, int total, STRBUF *defines) { int count = 0; int alpha_count = 0; FILEOP *fileop_MAP = NULL, *fileop_DEFINES, *fileop_ALPHA = NULL; FILE *MAP = NULL; FILE *DEFINES, *STDOUT, *TAGS, *ALPHA = NULL; STRBUF *sb = strbuf_open(0); STRBUF *url = strbuf_open(0); /* Index link */ const char *target = (Fflag) ? "mains" : "_top"; const char *indexlink; const char *index_string = "Index Page"; char command[1024], buf[1024], alpha[32], alpha_f[32], *_; if (!aflag && !Fflag) indexlink = "mains"; else if (Fflag) indexlink = "../defines"; else indexlink = "../mains"; if (map_file) { fileop_MAP = open_output_file(makepath(distpath, "MAP", NULL), 0); MAP = get_descripter(fileop_MAP); } fileop_DEFINES = open_output_file(makepath(distpath, file, NULL), 0); DEFINES = get_descripter(fileop_DEFINES); fputs_nl(gen_page_begin(title_define_index, TOPDIR), DEFINES); fputs_nl(body_begin, DEFINES); fputs(header_begin, DEFINES); if (Fflag) fputs(gen_href_begin(NULL, "defines", normal_suffix, NULL), DEFINES); fputs(title_define_index, DEFINES); if (Fflag) fputs(gen_href_end(), DEFINES); fputs_nl(header_end, DEFINES); if (!aflag && !Fflag) { fputs(gen_href_begin_with_title(NULL, indexlink, normal_suffix, NULL, index_string), DEFINES); if (Iflag) fputs(gen_image(CURRENT, back_icon, ".."), DEFINES); else fputs("[..]", DEFINES); fputs_nl(gen_href_end(), DEFINES); } if (!aflag) { if (!no_order_list) fputs_nl(list_begin, DEFINES); } /* * map DEFINES to STDOUT. */ STDOUT = DEFINES; snprintf(command, sizeof(command), PQUOTE "%s -c" PQUOTE, quote_shell(global_path)); if ((TAGS = popen(command, "r")) == NULL) die("cannot execute '%s'.", command); alpha[0] = '\0'; while ((_ = strbuf_fgets(sb, TAGS, STRBUF_NOCRLF)) != NULL) { const char *tag, *line; char guide[1024], url_for_map[1024]; count++; tag = _; message(" [%d/%d] adding %s", count, total, tag); if (aflag && (alpha[0] == '\0' || !locatestring(tag, alpha, MATCH_AT_FIRST))) { const char *msg = (alpha_count == 1) ? "definition" : "definitions"; int c; if (alpha[0]) { char tmp[128]; snprintf(tmp, sizeof(tmp), "%d %s", alpha_count, msg); strbuf_puts(defines, gen_href_begin_with_title("defines", alpha_f, HTML, NULL, tmp)); strbuf_sprintf(defines, "[%s]", alpha); strbuf_puts_nl(defines, gen_href_end()); alpha_count = 0; if (!no_order_list) fputs_nl(list_end, ALPHA); else fputs_nl(br, ALPHA); fputs(gen_href_begin_with_title(NULL, indexlink, normal_suffix, NULL, index_string), ALPHA); if (Iflag) fputs(gen_image(PARENT, back_icon, ".."), ALPHA); else fputs("[..]", ALPHA); fputs_nl(gen_href_end(), ALPHA); fputs_nl(body_end, ALPHA); fputs_nl(gen_page_end(), ALPHA); close_file(fileop_ALPHA); html_count++; } /* * setup index char (for example, 'a' of '[a]'). * alpha is used for display. * alpha_f is used for part of path. */ c = (unsigned char)*tag; if (c > 127) { int i2 = *(tag + 1) & 0xff; /* * for multi-byte(EUC) code. */ alpha[0] = *tag; alpha[1] = *(tag + 1); alpha[2] = '\0'; snprintf(alpha_f, sizeof(alpha_f), "%03d%03d", c, i2); } else if (isalpha(c) || c == '_') { alpha[0] = *tag; alpha[1] = '\0'; /* * for CD9660 or FAT file system */ if (islower(c)) { alpha_f[0] = 'l'; alpha_f[1] = *tag; alpha_f[2] = '\0'; } else { alpha_f[0] = *tag; alpha_f[1] = '\0'; } } else { alpha[0] = *tag; alpha[1] = '\0'; snprintf(alpha_f, sizeof(alpha_f), "%03d", c); } snprintf(buf, sizeof(buf), "%s/defines/%s.%s", distpath, alpha_f, HTML); fileop_ALPHA = open_output_file(buf, 0); ALPHA = get_descripter(fileop_ALPHA); snprintf(buf, sizeof(buf), "[%s]", alpha); fputs_nl(gen_page_begin(buf, SUBDIR), ALPHA); fputs_nl(body_begin, ALPHA); fprintf(ALPHA, "%s[%s]%s\n", header_begin, alpha, header_end); fputs(gen_href_begin_with_title(NULL, indexlink, normal_suffix, NULL, index_string), ALPHA); if (Iflag) fputs(gen_image(PARENT, back_icon, ".."), ALPHA); else fputs("[..]", ALPHA); fputs_nl(gen_href_end(), ALPHA); if (!no_order_list) fputs_nl(list_begin, ALPHA); else fprintf(ALPHA, "%s%s\n", br, br); STDOUT = ALPHA; } alpha_count++; /* * generating url for function definition. */ line = cache_get(GTAGS, tag); strbuf_reset(url); if (line == NULL) die("internal error in makedefineindex()."); /* * About the format of 'line', please see the head comment of cache.c. */ if (*line == ' ') { const char *fid = line + 1; const char *enumber = nextstring(fid); snprintf(url_for_map, sizeof(url_for_map), "%s/%s.%s", DEFS, fid, HTML); if (dynamic) { if (*action != '/' && aflag) strbuf_puts(url, "../"); strbuf_puts(url, action); strbuf_sprintf(url, "?pattern=%s%stype=definitions", tag, quote_amp); } else { if (aflag) strbuf_puts(url, "../"); strbuf_sprintf(url, "%s/%s.%s", DEFS, fid, HTML); } snprintf(guide, sizeof(guide), "Multiple defined in %s places.", enumber); } else { const char *lno = line; const char *fid = nextstring(line); const char *path = gpath_fid2path(fid, NULL); path += 2; /* remove './' */ snprintf(url_for_map, sizeof(url_for_map), "%s/%s.%s#L%s", SRCS, fid, HTML, lno); if (aflag) strbuf_puts(url, "../"); strbuf_sprintf(url, "%s/%s.%s#L%s", SRCS, fid, HTML, lno); snprintf(guide, sizeof(guide), "Defined at %s in %s.", lno, path); } if (!no_order_list) fputs(item_begin, STDOUT); fputs(gen_href_begin_with_title_target(NULL, strbuf_value(url), NULL, NULL, guide, target), STDOUT); fputs(tag, STDOUT); fputs(gen_href_end(), STDOUT); if (!no_order_list) fputs(item_end, STDOUT); else fputs(br, STDOUT); fputc('\n', STDOUT); if (map_file) fprintf(MAP, "%s\t%s\n", tag, url_for_map); } if (pclose(TAGS) != 0) die("terminated abnormally '%s' (errno = %d).", command, errno); if (aflag && alpha[0]) { char tmp[128]; const char *msg = (alpha_count == 1) ? "definition" : "definitions"; snprintf(tmp, sizeof(tmp), "%d %s", alpha_count, msg); strbuf_puts(defines, gen_href_begin_with_title("defines", alpha_f, HTML, NULL, tmp)); strbuf_sprintf(defines, "[%s]", alpha); strbuf_puts_nl(defines, gen_href_end()); if (!no_order_list) fputs_nl(list_end, ALPHA); else fputs_nl(br, ALPHA); fputs(gen_href_begin_with_title(NULL, indexlink, normal_suffix, NULL, index_string), ALPHA); if (Iflag) fputs(gen_image(PARENT, back_icon, ".."), ALPHA); else fputs("[..]", ALPHA); fputs_nl(gen_href_end(), ALPHA); fputs_nl(body_end, ALPHA); fputs_nl(gen_page_end(), ALPHA); close_file(fileop_ALPHA); html_count++; fputs(strbuf_value(defines), DEFINES); } if (!no_order_list && !aflag) fputs_nl(list_end, DEFINES); if (!aflag && !Fflag) { fputs(gen_href_begin_with_title(NULL, "mains", normal_suffix, NULL, index_string), DEFINES); if (Iflag) fputs(gen_image(CURRENT, back_icon, ".."), DEFINES); else fputs("[..]", DEFINES); fputs_nl(gen_href_end(), DEFINES); } fputs_nl(body_end, DEFINES); fputs_nl(gen_page_end(), DEFINES); close_file(fileop_DEFINES); html_count++; if (map_file) close_file(fileop_MAP); strbuf_close(sb); strbuf_close(url); return count; }
int main(void) { int frame = 0, ret = 0, got_picture = 0, frameFinished = 0, videoStream = 0, check_yuv = 0; int frame_size = 0, bitrate = 0; int streamIdx = 0; unsigned i=0; enum AVMediaType mediaType; struct SwsContext *sws_ctx = NULL; AVStream *video_st = NULL; AVCodecContext *pCodecCtx = NULL, *ctxEncode = NULL; AVFrame *pFrame = NULL; AVPacket input_pkt, output_pkt; check_yuv = check_file(); // Register all formats and codecs av_register_all(); if (open_input_file(check_yuv) < 0) exit(1); if (open_output_file() < 0) exit(1); init_parameter(&input_pkt, &output_pkt); //init parameter function pictureEncoded_init(); // initialize SWS context for software scaling sws_ctx = sws_getContext(inFmtCtx->streams[streamIdx]->codec->width, inFmtCtx->streams[streamIdx]->codec->height, inFmtCtx->streams[streamIdx]->codec->pix_fmt, clip_width, clip_height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); while (av_read_frame(inFmtCtx, &input_pkt) >= 0) { streamIdx = input_pkt.stream_index; mediaType = inFmtCtx->streams[streamIdx]->codec->codec_type; av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", streamIdx); av_log(NULL, AV_LOG_DEBUG, "Going to reencode \n"); pFrame = av_frame_alloc(); if (!pFrame) { ret = AVERROR(ENOMEM); break; } av_packet_rescale_ts(&input_pkt, inFmtCtx->streams[videoStream]->time_base, inFmtCtx->streams[streamIdx]->codec->time_base); if (mediaType == AVMEDIA_TYPE_VIDEO){ ret = avcodec_decode_video2(inFmtCtx->streams[streamIdx]->codec, pFrame, &frameFinished, &input_pkt); // Decode video frame (input_pkt-> pFrame) if (ret < 0) { av_frame_free(&pFrame); av_log(NULL, AV_LOG_ERROR, "Decoding failed\n"); break; } if (frameFinished){ frame_num++; sws_scale(sws_ctx, (const uint8_t * const *)pFrame->data, pFrame->linesize, 0, clip_height, pictureEncoded->data, pictureEncoded->linesize); pictureEncoded->pts = av_frame_get_best_effort_timestamp(pFrame); //pictureEncoded-> output_pkt //avcodec_encode_video2(ctxEncode, &output_pkt, pictureEncoded, &got_picture); avcodec_encode_video2(ofmt_ctx->streams[streamIdx]->codec, &output_pkt, pictureEncoded, &got_picture); av_frame_free(&pFrame); //if the function is working if (got_picture){ printf("Encoding %d \n", frame_use); frame_use++; av_packet_rescale_ts(&output_pkt, ofmt_ctx->streams[streamIdx]->codec->time_base, ofmt_ctx->streams[streamIdx]->time_base); //av_packet_rescale_ts(&output_pkt, ctxEncode->time_base, video_st->time_base); ret = av_interleaved_write_frame(ofmt_ctx, &output_pkt); if (ret < 0) { fprintf(stderr, "Error muxing packet\n"); break; } } } av_free_packet(&input_pkt); av_free_packet(&output_pkt); } } //flush encoders for (i = 0; i < inFmtCtx->nb_streams; i++) { if (inFmtCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { ret = flush_encoder(i); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n"); exit(1); } } } printf("\n\n total frame_num : %d , frame_encode: %d \n", frame_num-1, frame_use-1); /* 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(ofmt_ctx); // Free the YUV frame av_frame_free(&pFrame); av_frame_free(&pictureEncoded); // Close the codecs //avcodec_close(pCodecCtx); // Close the video file avformat_close_input(&inFmtCtx); //avcodec_close(ctxEncode); return 0; }
/* Main program. */ int main(int argc, char* argv[]) { const int verbose = 0; if ((argc < 2) || (argc > 6)) { print_syntax(argv[0]); return 1; } const char* infile = argv[1]; const char* out_pmusic = NULL; const char* out_labels = NULL; double sm_segment_min_dur = 4.0f; double b_segment_min_dur = 4.0f; if (argc >= 3) { out_pmusic = argv[2]; } if (argc >= 4) { out_labels = argv[3]; } if (argc >= 5) { sm_segment_min_dur = atof(argv[4]); } if (argc >= 6) { b_segment_min_dur = atof(argv[5]); } /* Load file */ WAVE* wave = open_wav(infile, verbose); if (wave == NULL) { return 1; } /* Init Opus encoder */ OpusSM* sm = init_opus(wave); if (sm == NULL) { wclose(wave); return 1; } /* Open output files */ FILE* ofp_pmusic = open_output_file(out_pmusic); if (ofp_pmusic == NULL) { wclose(wave); sm_destroy(sm); return 1; } FILE* ofp_labels = open_output_file(out_labels); if (ofp_labels == NULL) { wclose(wave); sm_destroy(sm); fclose(ofp_pmusic); return 1; } /* Processing */ int error = process(infile, wave, sm, ofp_pmusic, ofp_labels, sm_segment_min_dur, b_segment_min_dur ); /* Clean up */ sm = sm_destroy(sm); wave = wclose(wave); fclose(ofp_pmusic); fclose(ofp_labels); return error; }