void write_mobs_to_disk(int zone) { int counter, realcounter; FILE *fp; struct char_data *mob; zone = real_zone(zone); int i; // ideally, this would just fill a VTable with vals...maybe one day sprintf(buf, "%s/%d.mob", MOB_PREFIX, zone_table[zone].number); fp = fopen(buf, "w+"); /* start running through all mobiles in this zone */ for (counter = zone_table[zone].number * 100; counter <= zone_table[zone].top; counter++) { /* write mobile to disk */ realcounter = real_mobile(counter); if (realcounter >= 0) { mob = mob_proto+realcounter; if (!strcmp("an unfinished mob", GET_NAME(mob))) continue; fprintf(fp, "#%ld\n", GET_MOB_VNUM(mob)); fprintf(fp, "Keywords:\t%s\n" "Name:\t%s\n" "RoomDesc:$\n%s\n~\n", mob->player.physical_text.keywords? mob->player.physical_text.keywords : "mob unnamed", mob->player.physical_text.name? mob->player.physical_text.name : "An unnamed mob", cleanup(buf2, mob->player.physical_text.room_desc? mob->player.physical_text.room_desc : "An unnamed mob is here.")); fprintf(fp, "LookDesc:$\n%s~\n", cleanup(buf2, mob->player.physical_text.look_desc? mob->player.physical_text.look_desc : "An unnamed mob is here.")); if (mob->mob_specials.arrive) fprintf(fp, "ArriveMsg:\t%s\n", mob->mob_specials.arrive); if (mob->mob_specials.leave) fprintf(fp, "LeaveMsg:\t%s\n", mob->mob_specials.leave); fprintf(fp, "MobFlags:\t%s\n" "AffFlags:\t%s\n" "Race:\t%s\n" "Gender:\t%s\n", MOB_FLAGS(mob).ToString(), AFF_FLAGS(mob).ToString(), npc_classes[(int)mob->player.race], genders[(int)mob->player.sex]); if (mob->char_specials.position != POS_STANDING) fprintf(fp, "Position:\t%s\n", position_types[(int)mob->char_specials.position]); if (mob->mob_specials.default_pos) fprintf(fp, "DefaultPos:\t%s\n", position_types[(int)mob->mob_specials.default_pos]); if (mob->mob_specials.attack_type != TYPE_HIT) fprintf(fp, "AttackType:\t%s\n", attack_types[mob->mob_specials.attack_type-TYPE_HIT]); fprintf(fp, "[ATTRIBUTES]\n" "\tBod:\t%d\n" "\tQui:\t%d\n" "\tStr:\t%d\n" "\tCha:\t%d\n" "\tInt:\t%d\n" "\tWil:\t%d\n" "\tMag:\t%d\n", GET_REAL_BOD(mob), GET_REAL_QUI(mob), GET_REAL_STR(mob), GET_REAL_CHA(mob), GET_REAL_INT(mob), GET_REAL_WIL(mob), mob->real_abils.mag / 100); fprintf(fp, "[POINTS]\n" "\tHeight:\t%d\n" "\tWeight:\t%d\n", mob->player.height, mob->player.weight); if (GET_LEVEL(mob) > 0) fprintf(fp, "\tLevel:\t%d\n", GET_LEVEL(mob)); if (int(GET_MAX_PHYSICAL(mob) / 100) != 10) fprintf(fp, "\tMaxPhys:\t%d\n", int(GET_MAX_PHYSICAL(mob) / 100)); if (int(GET_MAX_MENTAL(mob) / 100) != 10) fprintf(fp, "\tMaxMent:\t%d\n", int(GET_MAX_MENTAL(mob) / 100)); if (GET_BALLISTIC(mob) > 0) fprintf(fp, "\tBallistic:\t%d\n", GET_BALLISTIC(mob)); if (GET_IMPACT(mob) > 0) fprintf(fp, "\tImpact:\t%d\n", GET_IMPACT(mob)); if (GET_NUYEN(mob) > 0) fprintf(fp, "\tCash:\t%d\n", GET_NUYEN(mob)); if (GET_BANK(mob) > 0) fprintf(fp, "\tBank:\t%d\n", GET_BANK(mob)); if (GET_KARMA(mob) > 0) fprintf(fp, "\tKarma:\t%d\n", GET_KARMA(mob)); fprintf(fp, "[SKILLS]\n"); for (i = 0; i <= 8; i = i +2) if (mob->mob_specials.mob_skills[i]) fprintf(fp, "\t%s:\t%d\n", skills[mob->mob_specials.mob_skills[i]].name, mob->mob_specials.mob_skills[i+1]); fprintf(fp, "BREAK\n"); } // close if statement } // close for loop fprintf(fp, "END\n"); fclose(fp); write_index_file("mob"); }
int main(int argc, char *argv[]) { int ret; opj_dparameters_t parameters; /* decompression parameters */ img_fol_t img_fol; opj_image_t *image = NULL; FILE *fsrc = NULL; bool bResult; int num_images; int i,imageno; dircnt_t *dirptr; opj_codec_t* dinfo = NULL; /* handle to a decompressor */ opj_stream_t *cio = NULL; opj_codestream_info_t cstr_info; /* Codestream information structure */ char indexfilename[OPJ_PATH_LEN]; /* index file name */ OPJ_INT32 l_tile_x0,l_tile_y0; OPJ_UINT32 l_tile_width,l_tile_height,l_nb_tiles_x,l_nb_tiles_y; /* configure the event callbacks (not required) */ /* set decoding parameters to default values */ opj_set_default_decoder_parameters(¶meters); /* Initialize indexfilename and img_fol */ *indexfilename = 0; memset(&img_fol,0,sizeof(img_fol_t)); /* parse input and get user encoding parameters */ if(parse_cmdline_decoder(argc, argv, ¶meters,&img_fol, indexfilename) == 1) { return EXIT_FAILURE; } /* Initialize reading of directory */ if(img_fol.set_imgdir==1){ num_images=get_num_images(img_fol.imgdirpath); dirptr=(dircnt_t*)malloc(sizeof(dircnt_t)); if(dirptr){ dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char)); // Stores at max 10 image file names dirptr->filename = (char**) malloc(num_images*sizeof(char*)); if(!dirptr->filename_buf){ return EXIT_FAILURE; } for(i=0;i<num_images;i++){ dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN; } } if(load_images(dirptr,img_fol.imgdirpath)==1){ return EXIT_FAILURE; } if (num_images==0){ fprintf(stdout,"Folder is empty\n"); return EXIT_FAILURE; } }else{ num_images=1; } /*Encoding image one by one*/ for(imageno = 0; imageno < num_images ; imageno++) { image = NULL; fprintf(stderr,"\n"); if(img_fol.set_imgdir==1){ if (get_next_file(imageno, dirptr,&img_fol, ¶meters)) { fprintf(stderr,"skipping file...\n"); continue; } } /* read the input file and put it in memory */ /* ---------------------------------------- */ fsrc = fopen(parameters.infile, "rb"); if (!fsrc) { fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile); return EXIT_FAILURE; } cio = opj_stream_create_default_file_stream(fsrc,true); /* decode the code-stream */ /* ---------------------- */ switch (parameters.decod_format) { case J2K_CFMT: { /* JPEG-2000 codestream */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_J2K); break; } case JP2_CFMT: { /* JPEG 2000 compressed image data */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_JP2); break; } case JPT_CFMT: { /* JPEG 2000, JPIP */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_JPT); break; } default: fprintf(stderr, "skipping file..\n"); opj_stream_destroy(cio); continue; } /* catch events using our callbacks and give a local context */ /* setup the decoder decoding parameters using user parameters */ opj_setup_decoder(dinfo, ¶meters); /* decode the stream and fill the image structure */ /* if (*indexfilename) // If need to extract codestream information image = opj_decode_with_info(dinfo, cio, &cstr_info); else */ bResult = opj_read_header( dinfo, &image, &l_tile_x0, &l_tile_y0, &l_tile_width, &l_tile_height, &l_nb_tiles_x, &l_nb_tiles_y, cio); //image = opj_decode(dinfo, cio); //bResult = bResult && (image != 00); //bResult = bResult && opj_end_decompress(dinfo,cio); //if // (!image) //{ // fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); // opj_destroy_codec(dinfo); // opj_stream_destroy(cio); // fclose(fsrc); // return EXIT_FAILURE; //} /* dump image */ if(!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to read header\n"); return EXIT_FAILURE; } j2k_dump_image(stdout, image); /* dump cp */ //j2k_dump_cp(stdout, image, dinfo->m_codec); /* close the byte stream */ opj_stream_destroy(cio); fclose(fsrc); /* Write the index to disk */ if (*indexfilename) { char bSuccess; bSuccess = write_index_file(&cstr_info, indexfilename); if (bSuccess) { fprintf(stderr, "Failed to output index file\n"); ret = EXIT_FAILURE; } } /* free remaining structures */ if (dinfo) { opj_destroy_codec(dinfo); } /* free codestream information structure */ if (*indexfilename) opj_destroy_cstr_info(&cstr_info); /* free image data structure */ opj_image_destroy(image); } return ret; }
// MAIN LOOP! void zedit_parse(struct descriptor_data *d, char *arg) { int number, i = 0, zone; switch (d->edit_mode) { case ZEDIT_CONFIRM_EDIT_DATA: switch (*arg) { case 'y': case 'Y': d->edit_zon = new zone_data; // we do need to zero it out since we are accessing its elements memset((char *) ZON, 0, sizeof(struct zone_data)); *d->edit_zon = zone_table[d->edit_number]; if (zone_table[d->edit_number].name) d->edit_zon->name = str_dup(zone_table[d->edit_number].name); zedit_disp_data_menu(d); break; case 'n': case 'N': STATE(d) = CON_PLAYING; PLR_FLAGS(d->character).RemoveBit(PLR_EDITING); break; default: send_to_char("That's not a valid choice!\r\n", d->character); send_to_char("Do you wish to edit the data?\r\n", d->character); break; } break; case ZEDIT_CONFIRM_CREATE_DATA: switch (*arg) { case 'y': case 'Y': d->edit_zon = new zone_data; // we do need to zero it out since we are accessing its elements memset((char *) ZON, 0, sizeof(struct zone_data)); // set a few vars ZON->name = str_dup("an unfinished zone"); ZON->number = CH->player_specials->saved.zonenum; ZON->top = ZON->number * 100 + 99; zedit_disp_data_menu(d); break; case 'n': case 'N': STATE(d) = CON_PLAYING; PLR_FLAGS(d->character).RemoveBit(PLR_EDITING); break; default: send_to_char("That's not a valid choice!\r\n", d->character); send_to_char("Do you wish to edit the data?\r\n", d->character); break; } break; case ZEDIT_CONFIRM_SAVEDATA: switch (*arg) { int zone_num; case 'y': case 'Y': zone_num = real_zone(ZON->number); sprintf(buf,"%s wrote new zcmd %ld in zone %d", GET_CHAR_NAME(d->character), d->edit_number, zone_table[zone_num].number); mudlog(buf, d->character, LOG_WIZLOG, TRUE); // first we insert into memory if (zone_num > -1) { // ie, it already exists ZON->cmd = zone_table[zone_num].cmd; delete [] zone_table[zone_num].name; zone_table[zone_num] = *ZON; } else { // here we got to add a new spot int counter; int found = 0; struct zone_data *new_z_table; // create new table + 2 new_z_table = new struct zone_data[top_of_zone_table + 2]; for (counter = 0; counter < top_of_zone_table + 1; counter++) { if (!found) { if (zone_table[counter].number > CH->player_specials->saved.zonenum) { new_z_table[counter] = *(ZON); found = 1; new_z_table[counter + 1] = zone_table[counter]; } else new_z_table[counter] = zone_table[counter]; } else new_z_table[counter + 1] = zone_table[counter]; } if (!found) new_z_table[top_of_zone_table + 1] = *(ZON); top_of_zone_table++; delete [] zone_table; zone_table = new_z_table; } write_zone_to_disk(ZONENUM); write_index_file("zon"); d->edit_mode = 0; delete ZON; ZON = NULL; PLR_FLAGS(d->character).RemoveBit(PLR_EDITING); STATE(d) = CON_PLAYING; send_to_char("Done.\r\n", d->character); break; // end of 'y' case in confirm savestring case 'n': case 'N': if (ZON) { if (ZON->name) delete [] ZON->name; delete ZON; } STATE(d) = CON_PLAYING; ZON = NULL; d->edit_number = 0; PLR_FLAGS(CH).RemoveBit(PLR_EDITING); break; // end of 'n' case in confirm savestring default: send_to_char("Please enter yes or no.\r\n" "Do you wish to save this zone internally?\r\n", CH); break; } break; // end of confirm savestring case ZEDIT_CONFIRM_ADD_CMD: switch (*arg) { case 'y': case 'Y': COM = new reset_com; COM->command = '*'; zedit_disp_command_menu(d); break; case 'n': case 'N': STATE(d) = CON_PLAYING; PLR_FLAGS(d->character).RemoveBit(PLR_EDITING); break; default: send_to_char("That's not a valid choice!\r\n", CH); send_to_char("Do you wish to add a command?\r\n", CH); break; } break; case ZEDIT_CONFIRM_INSERT_CMD: switch (*arg) { case 'y': case 'Y': COM = new reset_com; COM->command = '*'; // so it knows to insert if they decide to save d->edit_number2 = TRUE; zedit_disp_command_menu(d); break; case 'n': case 'N': STATE(d) = CON_PLAYING; PLR_FLAGS(d->character).RemoveBit(PLR_EDITING); break; default: send_to_char("That's not a valid choice!\r\n", CH); send_to_char("Do you wish to insert a command?\r\n", CH); break; } break; case ZEDIT_CONFIRM_EDIT_CMD: switch (*arg) { case 'y': case 'Y': COM = new reset_com; *COM = zone_table[real_zone(ZONENUM)].cmd[d->edit_number]; zedit_disp_command_menu(d); break; case 'n': case 'N': STATE(d) = CON_PLAYING; PLR_FLAGS(d->character).RemoveBit(PLR_EDITING); break; default: send_to_char("That's not a valid choice!\r\n", CH); send_to_char("Do you wish to edit the command?\r\n", CH); break; } break; case ZEDIT_DATA_MENU: switch (*arg) { case 'q': case 'Q': send_to_char("Do you wish to save this zone internally?\r\n", CH); d->edit_mode = ZEDIT_CONFIRM_SAVEDATA; break; case '1': send_to_char("Enter zone name: ", CH); d->edit_mode = ZEDIT_ZONE_NAME; break; case '2': send_to_char("Enter top of zone: ", CH); d->edit_mode = ZEDIT_TOP_OF_ZONE; break; case '3': send_to_char("Lifespan (in ticks between resets): ", CH); d->edit_mode = ZEDIT_LIFESPAN; break; case '4': CLS(CH); send_to_char("1) Don't reset\r\n" "2) Reset only if no PCs are in the zone\r\n" "3) Always reset\r\n" "0) Quit\r\n" "Enter reset mode: ", CH); d->edit_mode = ZEDIT_RESET_MODE; break; case '5': send_to_char("Zone security (1 (none) - 15 (paranoid)):\r\n", CH); d->edit_mode = ZEDIT_SECURITY; break; case '6': send_to_char("0) Seattle\r\n" "1) Portland\r\n" "Enter juridiction: ", CH); d->edit_mode = ZEDIT_JURID; break; case '7': if (!access_level(CH, LVL_VICEPRES)) { send_to_char("That's not a valid choice.\r\n", CH); return; } send_to_char("Enter ID list seperated by spaces:\r\n", CH); d->edit_mode = ZEDIT_ID_LIST; break; case '8': if (!access_level(CH, LVL_VICEPRES)) { send_to_char("That's not a valid choice.\r\n", CH); return; } send_to_char("Zone is connected (1 - yes, 0 - no)? ", CH); d->edit_mode = ZEDIT_CONNECTED; break; default: send_to_char("That's not a valid choice.\r\n", CH); zedit_disp_data_menu(d); break; } break; case ZEDIT_COMMAND_MENU: switch (*arg) { case 'q': case 'Q': send_to_char("Do you wish to save this zone command internally?\r\n", CH); d->edit_mode = ZEDIT_CONFIRM_SAVECMDS; break; case '1': zedit_disp_type_cmd(d); d->edit_mode = ZEDIT_CMD_TYPE; break; case '2': send_to_char("\r\n1) Always\r\n2) If last\r\nEnter your selection: ", CH); d->edit_mode = ZEDIT_IF_FLAG_CMD; break; case '3': switch (COM->command) { case 'M': case 'S': send_to_char("\r\nEnter virtual number of mob: ", CH); d->edit_mode = ZEDIT_ARG1; break; case 'H': case 'U': case 'I': case 'O': case 'P': case 'E': case 'G': case 'R': case 'N': case 'C': send_to_char("\r\nEnter virtual number of obj: ", CH); d->edit_mode = ZEDIT_ARG1; break; case 'D': zedit_disp_direction_menu(d); d->edit_mode = ZEDIT_DIRECTION_OF_DOOR; break; case 'V': send_to_char("\r\nEnter virtual number of vehicle: ", CH); d->edit_mode = ZEDIT_ARG1; break; default: zedit_disp_command_menu(d); break; } break; case '4': switch (COM->command) { case 'M': case 'S': case 'U': case 'I': case 'O': case 'P': case 'E': case 'N': case 'G': case 'H': case 'V': send_to_char("Enter max allowed to exist in game: ", CH); d->edit_mode = ZEDIT_ARG2; break; case 'R': case 'D': send_to_char("Enter the room number: ", CH); d->edit_mode = ZEDIT_REMOVE_ROOM; break; case 'C': send_to_char(" 0) Cyberware\r\n 1) Bioware\r\nEnter location to place obj: ", CH); d->edit_mode = ZEDIT_ARG2; break; default: zedit_disp_command_menu(d); break; } break; case '5': switch (COM->command) { case 'M': case 'O': case 'V': send_to_char("Enter the room number: ", CH); d->edit_mode = ZEDIT_ARG3; break; case 'H': send_to_char("Enter the host number: ", CH); d->edit_mode = ZEDIT_ARG3; break; case 'P': send_to_char("Enter the object number: ", CH); d->edit_mode = ZEDIT_ARG3; break; case 'E': zedit_disp_wear_menu(d); d->edit_mode = ZEDIT_WEAR; break; case 'D': zedit_disp_state_menu(d); d->edit_mode = ZEDIT_DOOR_STATE; break; case 'N': send_to_char("Enter total number to give mob: ", CH); d->edit_mode = ZEDIT_ARG3; break; default: zedit_disp_command_menu(d); break; } break; } break; case ZEDIT_CONFIRM_SAVECMDS: int zone_num, top_of_cmds; switch (*arg) { case 'y': case 'Y': zone_num = real_zone(ZONENUM); top_of_cmds = zone_table[zone_num].num_cmds; sprintf(buf,"%s wrote new zcmd %ld in zone %d", GET_CHAR_NAME(d->character), d->edit_number, zone_table[zone_num].number); mudlog(buf, d->character, LOG_WIZLOG, TRUE); // first, determine if you are adding or replacing if (d->edit_number < top_of_cmds) { if (!d->edit_number2) zone_table[zone_num].cmd[d->edit_number] = *(COM); else { int counter; struct reset_com *new_cmds; new_cmds = new struct reset_com[top_of_cmds + 1]; if (top_of_cmds > 1) { // first count your way up for (counter = 0; counter < d->edit_number; counter++) new_cmds[counter] = zone_table[zone_num].cmd[counter]; for (counter = top_of_cmds; counter > d->edit_number; counter--) new_cmds[counter] = zone_table[zone_num].cmd[counter-1]; new_cmds[d->edit_number] = *(COM); zone_table[zone_num].num_cmds++; delete [] zone_table[zone_num].cmd; zone_table[zone_num].cmd = new_cmds; } else { new_cmds[1] = zone_table[zone_num].cmd[0]; new_cmds[0] = *(COM); zone_table[zone_num].num_cmds++; if (zone_table[zone_num].cmd) delete [] zone_table[zone_num].cmd; zone_table[zone_num].cmd = new_cmds; } } } else { int counter; struct reset_com *new_cmds; // create a new set of commands, with 1 extra spot new_cmds = new struct reset_com[top_of_cmds + 1]; // we know it is always going in at the end, so we copy the old 1st if (top_of_cmds > 0) { // you have to do this in case there are 0 cmds for (counter = 0; counter < top_of_cmds; counter++) new_cmds[counter] = zone_table[zone_num].cmd[counter]; // tada, here it goes now, do not increase counter, for loop new_cmds[counter] = *(COM); // already did! zone_table[zone_num].num_cmds++; delete [] zone_table[zone_num].cmd; zone_table[zone_num].cmd = new_cmds; } else { new_cmds[0] = *(COM); zone_table[zone_num].num_cmds++; if (zone_table[zone_num].cmd) delete [] zone_table[zone_num].cmd; zone_table[zone_num].cmd = new_cmds; } } // end else write_zone_to_disk(ZONENUM); d->edit_mode = 0; delete COM; COM = NULL; PLR_FLAGS(d->character).RemoveBit(PLR_EDITING); STATE(d) = CON_PLAYING; send_to_char("Done.\r\n", d->character); break; // for 'y' case case 'n': case 'N': if (COM) delete COM; STATE(d) = CON_PLAYING; COM = NULL; d->edit_number = 0; PLR_FLAGS(CH).RemoveBit(PLR_EDITING); break; // for 'n' case default: send_to_char("That's not a valid choice.\r\n", CH); send_to_char("Do you wish to save this zone command internally?\r\n", CH); break; } // for switch in confirm save cmds break; // for ZEDIT_CONFIRM_SAVECMDS case ZEDIT_ARG3: number = atoi(arg); switch (COM->command) { case 'H': COM->arg3 = MAX(0, real_host(number)); break; case 'M': case 'V': case 'O': COM->arg3 = MAX(0, real_room(number)); if (!access_level(CH, LVL_ADMIN) && !(number >= (ZONENUM * 100) && number <= zone_table[real_zone(ZONENUM)].top)) COM->arg3 = 0; break; case 'P': COM->arg3 = MAX(0, real_object(number)); if (!access_level(CH, LVL_ADMIN) && (number < 600 || number > 699)) { for (zone = 0; zone <= top_of_zone_table; zone++) if (number >= (zone_table[zone].number * 100) && number <= zone_table[zone].top) break; if (zone <= top_of_zone_table) { for (i = 0; i < 5; i++) if (zone_table[zone].editor_ids[i] == GET_IDNUM(CH)) break; } else i = 5; } if (i >= 5) COM->arg3 = 0; break; case 'N': COM->arg3 = MIN(25, MAX(0, number)); break; } zedit_disp_command_menu(d); break; case ZEDIT_DOOR_STATE: number = atoi(arg); if ((number < 0) || (number > 3)) { zedit_disp_state_menu(d); return; } else if (number != 0) COM->arg3 = number - 1; zedit_disp_command_menu(d); break; case ZEDIT_WEAR: number = atoi(arg); if ((number < 0) || (number > (NUM_WEARS - 1))) { zedit_disp_wear_menu(d); return; } else if (number != 0) COM->arg3 = number - 1; zedit_disp_command_menu(d); break; case ZEDIT_REMOVE_ROOM: number = atoi(arg); COM->arg1 = MAX(0, real_room(number)); if (!access_level(CH, LVL_ADMIN) && !(number >= (ZONENUM * 100) && number <= zone_table[real_zone(ZONENUM)].top)) COM->arg1 = 0; zedit_disp_command_menu(d); break; case ZEDIT_ARG2: number = atoi(arg); if (COM->command == 'C' && (number < 0 || number > 1)) { send_to_char("Value must be either 0 (cyberware) or 1 (bioware).\r\n" "Enter location to place obj: ", CH); return; } else if ((number < -1) || (number > 1000)) { send_to_char("Value must be between -1 and 1000.\r\n" "Enter max allowed to exist in game: ", CH); return; } COM->arg2 = number; zedit_disp_command_menu(d); break; case ZEDIT_DIRECTION_OF_DOOR: number = atoi(arg); if (number < 0 || number > 10) { zedit_disp_direction_menu(d); return; } else if (number != 0) COM->arg2 = number - 1; zedit_disp_command_menu(d); break; case ZEDIT_ARG1: number = atoi(arg); if (COM->command == 'V') { COM->arg1 = MAX(0, real_vehicle(number)); } else { if (COM->command == 'M' || COM->command == 'S') { COM->arg1 = MAX(0, real_mobile(number)); if (!access_level(CH, LVL_ADMIN)) { for (zone = 0; zone <= top_of_zone_table; zone++) if (number >= (zone_table[zone].number * 100) && number <= zone_table[zone].top) break; if (zone <= top_of_zone_table) { for (i = 0; i < 5; i++) if (zone_table[zone].editor_ids[i] == GET_IDNUM(CH)) break; } else i = 5; } if (i >= 5) COM->arg1 = 0; } else { if (COM->command == 'R') COM->arg2 = MAX(0, real_object(number)); else COM->arg1 = MAX(0, real_object(number)); if (!access_level(CH, LVL_ADMIN) && (number < 300 || number > 699 || (number > 499 && number < 600))) { for (zone = 0; zone <= top_of_zone_table; zone++) if (number >= (zone_table[zone].number * 100) && number <= zone_table[zone].top) break; if (zone <= top_of_zone_table) { for (i = 0; i < 5; i++) if (zone_table[zone].editor_ids[i] == GET_IDNUM(CH)) break; } else i = 5; } if (i >= 5) { if (COM->command == 'R') COM->arg2 = 0; else COM->arg1 = 0; } } } zedit_disp_command_menu(d); break; case ZEDIT_CMD_TYPE: number = atoi(arg); if ((number < 0) || (number > 9) && *arg != 'n') { zedit_disp_type_cmd(d); send_to_char("\r\nInvalid selection. Please try again: ", CH); return; } else { COM->command = get_real_type(arg); if ((COM->command == 'E') || (COM->command == 'G') || (COM->command == 'P') || (COM->command == 'N') || (COM->command == 'C')) COM->if_flag = 1; else COM->if_flag = 0; COM->arg1 = 0; COM->arg2 = 0; COM->arg3 = 0; } zedit_disp_command_menu(d); break; case ZEDIT_IF_FLAG_CMD: number = atoi(arg); if ((number < 1) || (number > 2)) { send_to_char("Invalid selection.\r\n1) Always\r\n2) If last\r\n" "Enter your selection: ", CH); } else { COM->if_flag = COM->if_flag; zedit_disp_command_menu(d); } break; case ZEDIT_ZONE_NAME: if (ZON->name) delete [] ZON->name; ZON->name = str_dup(arg); zedit_disp_data_menu(d); break; case ZEDIT_SECURITY: number = atoi(arg); if (number < 1 || number > 15) { send_to_char("Security rating must range from 1 to 15.\r\nZone security: ", CH); return; } ZON->security = number; zedit_disp_data_menu(d); break; case ZEDIT_ID_LIST: { int t[5] = {0, 0, 0, 0, 0}; if (sscanf(arg, "%d %d %d %d %d\n", &t[0], &t[1], &t[2], &t[3], &t[4]) == 5) { ZON->editor_ids[0] = t[0]; ZON->editor_ids[1] = t[1]; ZON->editor_ids[2] = t[2]; ZON->editor_ids[3] = t[3]; ZON->editor_ids[4] = t[4]; } zedit_disp_data_menu(d); } break; case ZEDIT_CONNECTED: number = atoi(arg); if (number != 0 && number != 1) { send_to_char("Value must be 0 or 1! Zone is connected? ", CH); return; } sprintf(arg, "%s set zone %d to connected %d (was %d)", GET_CHAR_NAME( CH ), ZON->number, number, ZON->connected ); mudlog(arg, CH, LOG_WIZLOG, TRUE); ZON->connected = number; zedit_disp_data_menu(d); break; case ZEDIT_TOP_OF_ZONE: number = atoi(arg); if ((d->edit_number == top_of_zone_table) || (d->edit_number == -1)) if ((number < ZON->number * 100) || (number > (ZON->number * 100 + 499))) { send_to_char(CH, "Value must range from %d to %d\r\n", ZON->number * 100, (ZON->number * 100 + 499)); send_to_char("Enter top of zone: ", CH); return; } else ZON->top = number; else if ((number < ZON->number * 100) || (number > zone_table[d->edit_number + 1].number * 100 - 1)) { send_to_char(CH, "Value must range from %d to %d\r\n", ZON->number * 100, zone_table[d->edit_number + 1].number * 100 - 1); send_to_char("Enter top of zone: ", CH); return; } else ZON->top = number; zedit_disp_data_menu(d); break; case ZEDIT_LIFESPAN: number = atoi(arg); if ((number < 0) || (number > 1440)) { send_to_char("Value must range from 0 to 1440\r\n", CH); send_to_char("Lifespan (in ticks between resets): ", CH); } else { ZON->lifespan = number; zedit_disp_data_menu(d); } break; case ZEDIT_RESET_MODE: number = atoi(arg); if ((number < 0) || (number > 3)) { send_to_char("Invalid choice. Please enter from 0 to 3.\r\n", CH); send_to_char("Enter reset mode: ", CH); return; } else if (number != 0) ZON->reset_mode = number - 1; zedit_disp_data_menu(d); break; case ZEDIT_JURID: number = atoi(arg); if (number < 0 || number > 3) { send_to_char("Invalid choice. Please enter from 0 to 1.\r\n", CH); send_to_char("Enter Juridiction: ", CH); return; } else ZON->juridiction = number; zedit_disp_data_menu(d); break; } }
int main(int argc, char **argv) { opj_dparameters_t parameters; /* decompression parameters */ img_fol_t img_fol; opj_event_mgr_t event_mgr; /* event manager */ opj_image_t *image = NULL; FILE *fsrc = NULL; unsigned char *src = NULL; int file_length; int num_images; int i,imageno; dircnt_t *dirptr = NULL; opj_dinfo_t* dinfo = NULL; /* handle to a decompressor */ opj_cio_t *cio = NULL; opj_codestream_info_t cstr_info; /* Codestream information structure */ char indexfilename[OPJ_PATH_LEN]; /* index file name */ /* configure the event callbacks (not required) */ memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); event_mgr.error_handler = error_callback; event_mgr.warning_handler = warning_callback; event_mgr.info_handler = info_callback; /* set decoding parameters to default values */ opj_set_default_decoder_parameters(¶meters); /* Initialize indexfilename and img_fol */ *indexfilename = 0; memset(&img_fol,0,sizeof(img_fol_t)); /* parse input and get user encoding parameters */ if(parse_cmdline_decoder(argc, argv, ¶meters,&img_fol, indexfilename) == 1) { return 1; } /* Initialize reading of directory */ if(img_fol.set_imgdir==1){ num_images=get_num_images(img_fol.imgdirpath); dirptr=(dircnt_t*)malloc(sizeof(dircnt_t)); if(dirptr){ dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char)); /* Stores at max 10 image file names*/ dirptr->filename = (char**) malloc(num_images*sizeof(char*)); if(!dirptr->filename_buf){ return 1; } for(i=0;i<num_images;i++){ dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN; } } if(load_images(dirptr,img_fol.imgdirpath)==1){ return 1; } if (num_images==0){ fprintf(stdout,"Folder is empty\n"); return 1; } }else{ num_images=1; } /*Encoding image one by one*/ for(imageno = 0; imageno < num_images ; imageno++) { image = NULL; fprintf(stderr,"\n"); if(img_fol.set_imgdir==1){ if (get_next_file(imageno, dirptr,&img_fol, ¶meters)) { fprintf(stderr,"skipping file...\n"); continue; } } /* read the input file and put it in memory */ /* ---------------------------------------- */ fsrc = fopen(parameters.infile, "rb"); if (!fsrc) { fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile); return 1; } fseek(fsrc, 0, SEEK_END); file_length = ftell(fsrc); fseek(fsrc, 0, SEEK_SET); src = (unsigned char *) malloc(file_length); if (fread(src, 1, file_length, fsrc) != (size_t)file_length) { free(src); fclose(fsrc); fprintf(stderr, "\nERROR: fread return a number of element different from the expected.\n"); return 1; } fclose(fsrc); /* decode the code-stream */ /* ---------------------- */ switch(parameters.decod_format) { case J2K_CFMT: { /* JPEG-2000 codestream */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_J2K); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using user parameters */ opj_setup_decoder(dinfo, ¶meters); /* open a byte stream */ cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length); /* decode the stream and fill the image structure */ if (*indexfilename) /* If need to extract codestream information*/ image = opj_decode_with_info(dinfo, cio, &cstr_info); else image = opj_decode(dinfo, cio); if(!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); opj_destroy_decompress(dinfo); opj_cio_close(cio); free(src); return 1; } /* close the byte stream */ opj_cio_close(cio); /* Write the index to disk */ if (*indexfilename) { opj_bool bSuccess; bSuccess = write_index_file(&cstr_info, indexfilename); if (bSuccess) { fprintf(stderr, "Failed to output index file\n"); } } } break; case JP2_CFMT: { /* JPEG 2000 compressed image data */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_JP2); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using the current image and user parameters */ opj_setup_decoder(dinfo, ¶meters); /* open a byte stream */ cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length); /* decode the stream and fill the image structure */ if (*indexfilename) /* If need to extract codestream information*/ image = opj_decode_with_info(dinfo, cio, &cstr_info); else image = opj_decode(dinfo, cio); if(!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); opj_destroy_decompress(dinfo); opj_cio_close(cio); free(src); return 1; } /* close the byte stream */ opj_cio_close(cio); /* Write the index to disk */ if (*indexfilename) { opj_bool bSuccess; bSuccess = write_index_file(&cstr_info, indexfilename); if (bSuccess) { fprintf(stderr, "Failed to output index file\n"); } } } break; case JPT_CFMT: { /* JPEG 2000, JPIP */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_JPT); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using user parameters */ opj_setup_decoder(dinfo, ¶meters); /* open a byte stream */ cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length); /* decode the stream and fill the image structure */ if (*indexfilename) /* If need to extract codestream information*/ image = opj_decode_with_info(dinfo, cio, &cstr_info); else image = opj_decode(dinfo, cio); if(!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); opj_destroy_decompress(dinfo); opj_cio_close(cio); free(src); return 1; } /* close the byte stream */ opj_cio_close(cio); /* Write the index to disk */ if (*indexfilename) { opj_bool bSuccess; bSuccess = write_index_file(&cstr_info, indexfilename); if (bSuccess) { fprintf(stderr, "Failed to output index file\n"); } } } break; default: fprintf(stderr, "skipping file..\n"); continue; } /* free the memory containing the code-stream */ free(src); src = NULL; if(image->color_space == CLRSPC_SYCC) { color_sycc_to_rgb(image); } if(image->icc_profile_buf) { #if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) color_apply_icc_profile(image); #endif free(image->icc_profile_buf); image->icc_profile_buf = NULL; image->icc_profile_len = 0; } /* create output image */ /* ------------------- */ switch (parameters.cod_format) { case PXM_DFMT: /* PNM PGM PPM */ if (imagetopnm(image, parameters.outfile)) { fprintf(stdout,"Outfile %s not generated\n",parameters.outfile); } else { fprintf(stdout,"Generated Outfile %s\n",parameters.outfile); } break; case PGX_DFMT: /* PGX */ if(imagetopgx(image, parameters.outfile)){ fprintf(stdout,"Outfile %s not generated\n",parameters.outfile); } else { fprintf(stdout,"Generated Outfile %s\n",parameters.outfile); } break; case BMP_DFMT: /* BMP */ if(imagetobmp(image, parameters.outfile)){ fprintf(stdout,"Outfile %s not generated\n",parameters.outfile); } else { fprintf(stdout,"Generated Outfile %s\n",parameters.outfile); } break; #ifdef HAVE_LIBTIFF case TIF_DFMT: /* TIFF */ if(imagetotif(image, parameters.outfile)){ fprintf(stdout,"Outfile %s not generated\n",parameters.outfile); } else { fprintf(stdout,"Generated Outfile %s\n",parameters.outfile); } break; #endif /* HAVE_LIBTIFF */ case RAW_DFMT: /* RAW */ if(imagetoraw(image, parameters.outfile)){ fprintf(stdout,"Error generating raw file. Outfile %s not generated\n",parameters.outfile); } else { fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile); } break; case TGA_DFMT: /* TGA */ if(imagetotga(image, parameters.outfile)){ fprintf(stdout,"Error generating tga file. Outfile %s not generated\n",parameters.outfile); } else { fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile); } break; #ifdef HAVE_LIBPNG case PNG_DFMT: /* PNG */ if(imagetopng(image, parameters.outfile)){ fprintf(stdout,"Error generating png file. Outfile %s not generated\n",parameters.outfile); } else { fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile); } break; #endif /* HAVE_LIBPNG */ /* Can happen if output file is TIFF or PNG * and HAVE_LIBTIF or HAVE_LIBPNG is undefined */ default: fprintf(stderr,"Outfile %s not generated\n",parameters.outfile); } /* free remaining structures */ if(dinfo) { opj_destroy_decompress(dinfo); } /* free codestream information structure */ if (*indexfilename) opj_destroy_cstr_info(&cstr_info); /* free image data structure */ opj_image_destroy(image); } return 0; }
int main(int argc, const char *argv[]) { //input parameters FNHOLDER(inputFilename); FNHOLDER(playlistFilename); baseDirName [MAX_FILENAME_LENGTH ]=0; baseFileName[MAX_FILENAME_LENGTH ]=0; currentOutputDirName[MAX_FILENAME_LENGTH ]=0; baseFileExtension[MAX_FILENAME_LENGTH ]=0; baseFileExtension[MAXT_EXT_LENGTH]=0; //either "ts", "aac" or "mp3" int segmentLength, quiet, version,usage; FNHOLDER(tempPlaylistName); //these are used to determine the exact length of the current segment double segment_start_time = 0; unsigned int actual_segment_durations[MAX_SEGMENTS+1]; double packet_time = 0; unsigned int output_index = 1; AVOutputFormat *ofmt=NULL; AVFormatContext *ic = NULL; AVFormatContext *oc; AVStream *in_video_st = NULL; AVStream *in_audio_st = NULL; AVStream *out_video_st = NULL; AVStream *out_audio_st = NULL; AVCodec *codec; unsigned int num_segments = 0; int decode_done; int ret; int i; int listlen; int listofs=1; int persist=0; if ( parseCommandLine(argc, argv,inputFilename, playlistFilename, baseDirName, baseFileName, baseFileExtension, &segmentLength, &listlen, &quiet, &version,&usage,&persist) != 0) return 0; if (usage) printUsage(); if (version) ffmpeg_version(); if (version || usage) return 0; //fprintf(stderr, "Options parsed: inputFilename:%s playlistFilename:%s baseDirName:%s baseFileName:%s baseFileExtension:%s segmentLength:%d\n",inputFilename,playlistFilename,baseDirName,baseFileName,baseFileExtension,segmentLength ); if (listlen>0){ snprintf(tempPlaylistName, MAX_FILENAME_LENGTH, "%s/%s", baseDirName, playlistFilename); strncpy(playlistFilename, tempPlaylistName, MAX_FILENAME_LENGTH); snprintf(tempPlaylistName, MAX_FILENAME_LENGTH, "%s.tmp", playlistFilename); } //if (!quiet) av_log_set_level(AV_LOG_DEBUG); av_register_all(); avformat_network_init(); //just to be safe with later version and be able to handle all kind of input urls while(1) { ret = avformat_open_input(&ic, inputFilename, NULL, NULL); if (ret != 0) { if (persist) { sleep(1); continue; } fprintf(stderr, "Could not open input file %s. Error %d.\n", inputFilename, ret); exit(1); } if (avformat_find_stream_info(ic, NULL) < 0) { fprintf(stderr, "Could not read stream information.\n"); if (persist){ avformat_close_input(&ic); sleep(1); continue; } exit(1); } oc = avformat_alloc_context(); if (!oc) { fprintf(stderr, "Could not allocate output context."); if (persist){ avformat_close_input(&ic); sleep(1); continue; } exit(1); } int in_video_index = -1; int in_audio_index = -1; int out_video_index = -1; int out_audio_index = -1; for (i = 0; i < ic->nb_streams; i++) { switch (ic->streams[i]->codec->codec_type) { case AVMEDIA_TYPE_VIDEO: if (!out_video_st) { in_video_st=ic->streams[i]; in_video_index = i; in_video_st->discard = AVDISCARD_NONE; out_video_st = add_output_stream(oc, in_video_st); out_video_index=out_video_st->index; } break; case AVMEDIA_TYPE_AUDIO: if (!out_audio_st) { in_audio_st=ic->streams[i]; in_audio_index = i; in_audio_st->discard = AVDISCARD_NONE; out_audio_st = add_output_stream(oc, in_audio_st); out_audio_index=out_audio_st->index; } break; default: ic->streams[i]->discard = AVDISCARD_ALL; break; } } if (in_video_index == -1) { fprintf(stderr, "Source stream must have video component.\n"); if (persist){ avformat_close_input(&ic); avformat_free_context(oc); sleep(1); continue; } exit(1); } if (!ofmt) ofmt = av_guess_format("mpegts", NULL, NULL); if (!ofmt) { fprintf(stderr, "Could not find MPEG-TS muxer.\n"); exit(1); } oc->oformat = ofmt; if (oc->oformat->flags & AVFMT_GLOBALHEADER) oc->flags |= CODEC_FLAG_GLOBAL_HEADER; av_dump_format(oc, 0, baseFileName, 1); codec = avcodec_find_decoder(in_video_st->codec->codec_id); if (!codec) { fprintf(stderr, "Could not find video decoder, key frames will not be honored.\n"); } ret = avcodec_open2(in_video_st->codec, codec, NULL); if (ret < 0) { fprintf(stderr, "Could not open video decoder, key frames will not be honored.\n"); } if (listlen>0){ snprintf(currentOutputFileName, MAX_FILENAME_LENGTH, "%s/%s-%u%s", baseDirName, baseFileName, output_index, baseFileExtension); } else { //archive mode localtime_r_ex(&start_time); fillofn(); } if (avio_open(&oc->pb, currentOutputFileName,AVIO_FLAG_WRITE) < 0) { fprintf(stderr, "Could not open '%s'.\n", currentOutputFileName); exit(1); } else if (!quiet) fprintf(stderr, "Starting segment '%s'\n", currentOutputFileName); int r = avformat_write_header(oc, NULL); if (r) { fprintf(stderr, "Could not write mpegts header to first output file.\n"); debugReturnCode(r); exit(1); } int waitfirstpacket=1; time_t first_frame_sec=time(NULL); int iskeyframe=0; double vid_pts2time=(double)in_video_st->time_base.num / in_video_st->time_base.den; //double aud_pts2time=0; //if (in_audio_st) aud_pts2time=(double)in_audio_st->time_base.num / in_audio_st->time_base.den; double prev_packet_time=0; do { AVPacket packet; decode_done = av_read_frame(ic, &packet); if (decode_done < 0) { break; } //a potential memory leak: // if (av_dup_packet(&packet) < 0) { // fprintf(stderr, "Could not duplicate packet."); // av_packet_unref(&packet); // break; // } //get the most recent packet time //this time is used when the time for the final segment is printed. It may not be on the edge of //of a keyframe! if (packet.stream_index == in_video_index) { packet.stream_index = out_video_index; packet_time = (double) packet.pts * vid_pts2time; iskeyframe=packet.flags & AV_PKT_FLAG_KEY; if (iskeyframe && waitfirstpacket) { waitfirstpacket=0; prev_packet_time=packet_time; segment_start_time=packet_time; first_frame_sec=time(NULL); } } else if (packet.stream_index == in_audio_index){ packet.stream_index = out_audio_index; iskeyframe=0; } else { //how this got here?! av_packet_unref(&packet); continue; } if (waitfirstpacket) { av_packet_unref(&packet); continue; } //start looking for segment splits for videos one half second before segment duration expires. This is because the //segments are split on key frames so we cannot expect all segments to be split exactly equally. if (iskeyframe && ((packet_time - segment_start_time) >= (segmentLength - 0.25)) && (time(NULL)!=first_frame_sec)) { //a keyframe near or past segmentLength -> SPLIT avio_flush(oc->pb); avio_close(oc->pb); if (listlen>0){ actual_segment_durations[num_segments] = (unsigned int) rint(prev_packet_time - segment_start_time); num_segments++; if (num_segments>listlen) { //move list to exclude last: snprintf(currentOutputFileName, MAX_FILENAME_LENGTH, "%s/%s-%u%s", baseDirName, baseFileName, listofs, baseFileExtension); unlink (currentOutputFileName); listofs++; num_segments--; memmove(actual_segment_durations,actual_segment_durations+1,num_segments*sizeof(actual_segment_durations[0])); } write_index_file(playlistFilename, tempPlaylistName, segmentLength, num_segments,actual_segment_durations, listofs, baseFileName, baseFileExtension, (num_segments>=MAX_SEGMENTS)); if (num_segments==MAX_SEGMENTS) { fprintf(stderr, "Reached \"hard\" max segment number %u. If this is not live stream increase segment duration. If live segmenting set max list lenth (-m ...)\n", MAX_SEGMENTS); break; } output_index++; snprintf(currentOutputFileName, MAX_FILENAME_LENGTH, "%s/%s-%u%s", baseDirName, baseFileName, output_index, baseFileExtension); } else { //archive mode: localtime_r_ex(&end_time); fixofn(); } if (avio_open(&oc->pb, currentOutputFileName, AVIO_FLAG_WRITE) < 0) { fprintf(stderr, "Could not open '%s'\n", currentOutputFileName); break; } else if (!quiet) fprintf(stderr, "Starting segment '%s'\n", currentOutputFileName); fflush(stderr); segment_start_time = packet_time; first_frame_sec=time(NULL); } if (packet.stream_index == out_video_index) prev_packet_time=packet_time; ret = av_write_frame(oc, &packet); if (ret < 0) { fprintf(stderr, "Warning: Could not write frame of stream.\n"); } else if (ret > 0) { fprintf(stderr, "End of stream requested.\n"); av_packet_unref(&packet); break; } av_packet_unref(&packet); } while (!decode_done); if (in_video_st->codec->codec !=NULL) avcodec_close(in_video_st->codec); if (num_segments<MAX_SEGMENTS) { //make sure all packets are written and then close the last file. avio_flush(oc->pb); av_write_trailer(oc); for (i = 0; i < oc->nb_streams; i++) { av_freep(&oc->streams[i]->codec); av_freep(&oc->streams[i]); } avio_close(oc->pb); av_free(oc); if (num_segments>0){ actual_segment_durations[num_segments] = (unsigned int) rint(packet_time - segment_start_time); if (actual_segment_durations[num_segments] == 0) actual_segment_durations[num_segments] = 1; num_segments++; write_index_file(playlistFilename, tempPlaylistName, segmentLength, num_segments,actual_segment_durations, listofs, baseFileName, baseFileExtension, 1); } else { //archive mode localtime_r_ex(&end_time); fixofn(); } } // struct stat st; // stat(currentOutputFileName, &st); // output_bytes += st.st_size; avformat_close_input(&ic); break; } return 0; }
/**1 output_file = new file() 2 dict = new hash() 3 while (free memory available) 4 do token = next_token() 5 if token not in dict 6 postinglist = addtodict(dict, token) 7 else postinglist = getpostinglist(dict, token) 8 if full(postinglist) 9 postinglist = doublepostinglist(dict, token) 10 addtopostinglist(postinglist, docid(token)) 11 sorted_terms = sortterm(dict) // for merge purpose *12 writeblock(sorted_terms, dict, output_file) */ int build_board_index(char *bname) { char *word; char dirfile[PATH_MAX], docid2path[PATH_MAX], indexfile[PATH_MAX]; char filepath[PATH_MAX]; /* article file path */ char filename[20]; char cachedir[PATH_MAX]; char cachefile[PATH_MAX]; char ndocsfile[PATH_MAX]; DB *dbp; DBT key, data; int ret; int result = -1; FILE *filelist, *fp; struct postinglist *p; unsigned int docid = 1; gzFile cachefp; int gzerr; setboardfile(dirfile, bname, bname); set_brddocid2path_file(docid2path, bname); set_brdindex_file(indexfile, bname); /* Initialize the DB structure.*/ ret = db_create(&dbp, NULL, 0); if (ret != 0) { ERROR("create db hanldle failed"); goto RETURN; } if (dbopen(dbp, docid2path, 1) != 0) { ERROR1("open db %s failed", docid2path); goto RETURN; } if (!(filelist = fopen(dirfile, "r"))) { ERROR1("open file %s failed", dirfile); goto CLEAN_DB; } size_t size = 300000; /* TODO: define this constant */ struct dict_t **bucket = new_postinglist_bucket(size); if (bucket == NULL) { ERROR1("new_dict size=%u failed", size); goto CLEAN_FP; } g_text = malloc(MAX_FILE_SIZE); if (g_text == NULL) { ERROR("malloc failed"); goto CLEAN_MEM; } /* Zero out the DBTs before using them. */ memset(&key, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); key.size = sizeof(unsigned int); key.data = &docid; /* ensure the cache directory exists */ setcachepath(cachedir, bname); f_mkdir(cachedir, 0755); while (fgets(filename, sizeof(filename), filelist)) { filename[strlen(filename) - 1] = '\0'; data.size = strlen(filename) + 1; data.data = filename; setboardfile(filepath, bname, filename); ansi_filter(filepath); if (g_len != 0) { fprintf(stderr, "%d indexing %s\n", docid, filename); /* save to cache file */ setcachefile(cachefile, bname, filename); cachefp = gzopen(cachefile, "wb"); if (cachefp != NULL) { if (gzwrite(cachefp, g_text, g_len) != g_len) ERROR(gzerror(cachefp, &gzerr)); gzclose(cachefp); } g_pos = 0; while ((word = next_token())) { //DEBUG1("%s", word); p = get_postinglist(bucket, size, word); if (p->freq == p->size) /* is full */ double_postinglist(p); addto_postinglist(p, docid); } /* write_docid2path */ dbp->put(dbp, NULL, &key, &data, 0); docid++; } } write_index_file(bucket, size, indexfile); calc_doc_weight(bname, BOARD, docid - 1); set_brdndocs_file(ndocsfile, bname); fp = fopen(ndocsfile, "w"); if (fp == NULL) { ERROR1("fopen %s failed", ndocsfile); goto CLEAN; } fprintf(fp, "%u", docid - 1); fclose(fp); /* it's ok */ result = 0; CLEAN: free(g_text); CLEAN_MEM: free(bucket); CLEAN_FP: fclose(filelist); CLEAN_DB: if (dbp != NULL) dbp->close(dbp, 0); RETURN: return result; }
int main(int argc, char *argv[]) { opj_dparameters_t parameters; /* decompression parameters */ img_fol_t img_fol; opj_event_mgr_t event_mgr; /* event manager */ opj_image_t *image = NULL; FILE *fsrc = NULL, *fout = NULL; unsigned char *src = NULL; int file_length; int num_images; int i,imageno; dircnt_t *dirptr = NULL; opj_dinfo_t* dinfo = NULL; /* handle to a decompressor */ opj_cio_t *cio = NULL; opj_codestream_info_t cstr_info; /* Codestream information structure */ char indexfilename[OPJ_PATH_LEN]; /* index file name */ /* configure the event callbacks (not required) */ memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); event_mgr.error_handler = error_callback; event_mgr.warning_handler = warning_callback; event_mgr.info_handler = info_callback; /* set decoding parameters to default values */ opj_set_default_decoder_parameters(¶meters); /* Initialize indexfilename and img_fol */ *indexfilename = 0; memset(&img_fol,0,sizeof(img_fol_t)); /* parse input and get user encoding parameters */ if(parse_cmdline_decoder(argc, argv, ¶meters,&img_fol, indexfilename) == 1) { return 1; } /* Initialize reading of directory */ if(img_fol.set_imgdir==1){ num_images=get_num_images(img_fol.imgdirpath); dirptr=(dircnt_t*)malloc(sizeof(dircnt_t)); if(dirptr){ dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char)); /* Stores at max 10 image file names*/ dirptr->filename = (char**) malloc(num_images*sizeof(char*)); if(!dirptr->filename_buf){ return 1; } for(i=0;i<num_images;i++){ dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN; } } if(load_images(dirptr,img_fol.imgdirpath)==1){ return 1; } if (num_images==0){ fprintf(stdout,"Folder is empty\n"); return 1; } }else{ num_images=1; } /* */ if (parameters.outfile[0] != 0) { fout = fopen(parameters.outfile,"w"); if (!fout) { fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.outfile); return 1; } } else fout = stdout; /*Encoding image one by one*/ for(imageno = 0; imageno < num_images ; imageno++) { image = NULL; fprintf(stderr,"\n"); if(img_fol.set_imgdir==1){ if (get_next_file(imageno, dirptr,&img_fol, ¶meters)) { fprintf(stderr,"skipping file...\n"); continue; } } /* read the input file and put it in memory */ /* ---------------------------------------- */ fsrc = fopen(parameters.infile, "rb"); if (!fsrc) { fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile); return 1; } fseek(fsrc, 0, SEEK_END); file_length = ftell(fsrc); fseek(fsrc, 0, SEEK_SET); src = (unsigned char *) malloc(file_length); if (fread(src, 1, file_length, fsrc) != (size_t)file_length) { free(src); fclose(fsrc); fclose(fout); fprintf(stderr, "\nERROR: fread return a number of element different from the expected.\n"); return 1; } fclose(fsrc); /* decode the code-stream */ /* ---------------------- */ switch(parameters.decod_format) { case J2K_CFMT: { /* JPEG-2000 codestream */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_J2K); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using user parameters */ opj_setup_decoder(dinfo, ¶meters); /* open a byte stream */ cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length); /* decode the stream and fill the image structure */ if (*indexfilename) /* If need to extract codestream information*/ image = opj_decode_with_info(dinfo, cio, &cstr_info); else image = opj_decode(dinfo, cio); if(!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); opj_destroy_decompress(dinfo); opj_cio_close(cio); fclose(fout); free(src); return 1; } /* dump image */ j2k_dump_image(fout, image); /* dump cp */ j2k_dump_cp(fout, image, ((opj_j2k_t*)dinfo->j2k_handle)->cp); /* close the byte stream */ opj_cio_close(cio); /* Write the index to disk */ if (*indexfilename) { opj_bool bSuccess; bSuccess = write_index_file(&cstr_info, indexfilename); if (bSuccess) { fprintf(stderr, "Failed to output index file\n"); } } } break; case JP2_CFMT: { /* JPEG 2000 compressed image data */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_JP2); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using the current image and user parameters */ opj_setup_decoder(dinfo, ¶meters); /* open a byte stream */ cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length); /* decode the stream and fill the image structure */ if (*indexfilename) /* If need to extract codestream information*/ image = opj_decode_with_info(dinfo, cio, &cstr_info); else image = opj_decode(dinfo, cio); if(!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); opj_destroy_decompress(dinfo); opj_cio_close(cio); fclose(fout); free(src); return 1; } /* dump image */ if(image->icc_profile_buf) { free(image->icc_profile_buf); image->icc_profile_buf = NULL; } j2k_dump_image(fout, image); /* dump cp */ j2k_dump_cp(fout, image, ((opj_jp2_t*)dinfo->jp2_handle)->j2k->cp); /* close the byte stream */ opj_cio_close(cio); /* Write the index to disk */ if (*indexfilename) { opj_bool bSuccess; bSuccess = write_index_file(&cstr_info, indexfilename); if (bSuccess) { fprintf(stderr, "Failed to output index file\n"); } } } break; case JPT_CFMT: { /* JPEG 2000, JPIP */ /* get a decoder handle */ dinfo = opj_create_decompress(CODEC_JPT); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using user parameters */ opj_setup_decoder(dinfo, ¶meters); /* open a byte stream */ cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length); /* decode the stream and fill the image structure */ if (*indexfilename) /* If need to extract codestream information*/ image = opj_decode_with_info(dinfo, cio, &cstr_info); else image = opj_decode(dinfo, cio); if(!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); opj_destroy_decompress(dinfo); opj_cio_close(cio); fclose(fout); free(src); return 1; } /* close the byte stream */ opj_cio_close(cio); /* Write the index to disk */ if (*indexfilename) { opj_bool bSuccess; bSuccess = write_index_file(&cstr_info, indexfilename); if (bSuccess) { fprintf(stderr, "Failed to output index file\n"); } } } break; default: fprintf(stderr, "skipping file..\n"); continue; } /* free the memory containing the code-stream */ free(src); src = NULL; /* free remaining structures */ if(dinfo) { opj_destroy_decompress(dinfo); } /* free codestream information structure */ if (*indexfilename) opj_destroy_cstr_info(&cstr_info); /* free image data structure */ opj_image_destroy(image); } fclose(fout); return EXIT_SUCCESS; }
int main(int argc, char **argv) { double prev_segment_time = 0; unsigned int output_index = 1; AVInputFormat *ifmt; AVOutputFormat *ofmt; AVFormatContext *ic = NULL; AVFormatContext *oc; AVStream *video_st = NULL; AVStream *audio_st = NULL; AVCodec *codec; char *output_filename; char *remove_filename; int video_index = -1; int audio_index = -1; unsigned int first_segment = 1; unsigned int last_segment = 0; int write_index = 1; int decode_done; char *dot; int ret; unsigned int i; int remove_file; struct sigaction act; int opt; int longindex; char *endptr; struct options_t options; static const char *optstring = "i:d:p:m:u:n:ovh?"; static const struct option longopts[] = { { "input", required_argument, NULL, 'i' }, { "duration", required_argument, NULL, 'd' }, { "output-prefix", required_argument, NULL, 'p' }, { "m3u8-file", required_argument, NULL, 'm' }, { "url-prefix", required_argument, NULL, 'u' }, { "num-segments", required_argument, NULL, 'n' }, { "help", no_argument, NULL, 'h' }, { 0, 0, 0, 0 } }; memset(&options, 0 ,sizeof(options)); /* Set some defaults */ options.segment_duration = 10; options.num_segments = 0; do { opt = getopt_long(argc, argv, optstring, longopts, &longindex ); switch (opt) { case 'i': options.input_file = optarg; if (!strcmp(options.input_file, "-")) { options.input_file = "pipe:"; } break; case 'd': options.segment_duration = strtol(optarg, &endptr, 10); if (optarg == endptr || options.segment_duration < 0 || options.segment_duration == -LONG_MAX) { fprintf(stderr, "Segment duration time (%s) invalid\n", optarg); exit(1); } break; case 'p': options.output_prefix = optarg; break; case 'm': options.m3u8_file = optarg; break; case 'u': options.url_prefix = optarg; break; case 'n': options.num_segments = strtol(optarg, &endptr, 10); if (optarg == endptr || options.num_segments < 0 || options.num_segments >= LONG_MAX) { fprintf(stderr, "Maximum number of ts files (%s) invalid\n", optarg); exit(1); } break; case 'h': display_usage(); break; } } while (opt != -1); /* Check required args where set*/ if (options.input_file == NULL) { fprintf(stderr, "Please specify an input file.\n"); exit(1); } if (options.output_prefix == NULL) { fprintf(stderr, "Please specify an output prefix.\n"); exit(1); } if (options.m3u8_file == NULL) { fprintf(stderr, "Please specify an m3u8 output file.\n"); exit(1); } if (options.url_prefix == NULL) { fprintf(stderr, "Please specify a url prefix.\n"); exit(1); } av_register_all(); remove_filename = malloc(sizeof(char) * (strlen(options.output_prefix) + 15)); if (!remove_filename) { fprintf(stderr, "Could not allocate space for remove filenames\n"); exit(1); } output_filename = malloc(sizeof(char) * (strlen(options.output_prefix) + 15)); if (!output_filename) { fprintf(stderr, "Could not allocate space for output filenames\n"); exit(1); } options.tmp_m3u8_file = malloc(strlen(options.m3u8_file) + 2); if (!options.tmp_m3u8_file) { fprintf(stderr, "Could not allocate space for temporary index filename\n"); exit(1); } // Use a dotfile as a temporary file strncpy(options.tmp_m3u8_file, options.m3u8_file, strlen(options.m3u8_file) + 2); dot = strrchr(options.tmp_m3u8_file, '/'); dot = dot ? dot + 1 : options.tmp_m3u8_file; memmove(dot + 1, dot, strlen(dot)); *dot = '.'; ifmt = av_find_input_format("mpegts"); if (!ifmt) { fprintf(stderr, "Could not find MPEG-TS demuxer\n"); exit(1); } ret = avformat_open_input(&ic, options.input_file, ifmt, NULL); if (ret != 0) { fprintf(stderr, "Could not open input file, make sure it is an mpegts file: %d\n", ret); exit(1); } if (avformat_find_stream_info(ic, NULL) < 0) { fprintf(stderr, "Could not read stream information\n"); exit(1); } ofmt = av_guess_format("mpegts", NULL, NULL); if (!ofmt) { fprintf(stderr, "Could not find MPEG-TS muxer\n"); exit(1); } oc = avformat_alloc_context(); if (!oc) { fprintf(stderr, "Could not allocated output context"); exit(1); } oc->oformat = ofmt; for (i = 0; i < ic->nb_streams && (video_index < 0 || audio_index < 0); i++) { switch (ic->streams[i]->codec->codec_type) { case AVMEDIA_TYPE_VIDEO: video_index = i; ic->streams[i]->discard = AVDISCARD_NONE; video_st = add_output_stream(oc, ic->streams[i]); break; case AVMEDIA_TYPE_AUDIO: audio_index = i; ic->streams[i]->discard = AVDISCARD_NONE; audio_st = add_output_stream(oc, ic->streams[i]); break; default: ic->streams[i]->discard = AVDISCARD_ALL; break; } } // Don't print warnings when PTS and DTS are identical. ic->flags |= AVFMT_FLAG_IGNDTS; av_dump_format(oc, 0, options.output_prefix, 1); if (video_st) { codec = avcodec_find_decoder(video_st->codec->codec_id); if (!codec) { fprintf(stderr, "Could not find video decoder %x, key frames will not be honored\n", video_st->codec->codec_id); } if (avcodec_open2(video_st->codec, codec, NULL) < 0) { fprintf(stderr, "Could not open video decoder, key frames will not be honored\n"); } } snprintf(output_filename, strlen(options.output_prefix) + 15, "%s-%u.ts", options.output_prefix, output_index++); if (avio_open(&oc->pb, output_filename, AVIO_FLAG_WRITE) < 0) { fprintf(stderr, "Could not open '%s'\n", output_filename); exit(1); } if (avformat_write_header(oc, NULL)) { fprintf(stderr, "Could not write mpegts header to first output file\n"); exit(1); } write_index = !write_index_file(options, first_segment, last_segment, 0); /* Setup signals */ memset(&act, 0, sizeof(act)); act.sa_handler = &handler; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); do { double segment_time = prev_segment_time; AVPacket packet; if (terminate) { break; } decode_done = av_read_frame(ic, &packet); if (decode_done < 0) { break; } if (av_dup_packet(&packet) < 0) { fprintf(stderr, "Could not duplicate packet"); av_free_packet(&packet); break; } // Use video stream as time base and split at keyframes. Otherwise use audio stream if (packet.stream_index == video_index && (packet.flags & AV_PKT_FLAG_KEY)) { segment_time = packet.pts * av_q2d(video_st->time_base); } else if (video_index < 0) { segment_time = packet.pts * av_q2d(audio_st->time_base); } else { segment_time = prev_segment_time; } if (segment_time - prev_segment_time >= options.segment_duration) { av_write_trailer(oc); // close ts file and free memory avio_flush(oc->pb); avio_close(oc->pb); if (options.num_segments && (int)(last_segment - first_segment) >= options.num_segments - 1) { remove_file = 1; first_segment++; } else { remove_file = 0; } if (write_index) { write_index = !write_index_file(options, first_segment, ++last_segment, 0); } if (remove_file) { snprintf(remove_filename, strlen(options.output_prefix) + 15, "%s-%u.ts", options.output_prefix, first_segment - 1); remove(remove_filename); } snprintf(output_filename, strlen(options.output_prefix) + 15, "%s-%u.ts", options.output_prefix, output_index++); if (avio_open(&oc->pb, output_filename, AVIO_FLAG_WRITE) < 0) { fprintf(stderr, "Could not open '%s'\n", output_filename); break; } // Write a new header at the start of each file if (avformat_write_header(oc, NULL)) { fprintf(stderr, "Could not write mpegts header to first output file\n"); exit(1); } prev_segment_time = segment_time; } ret = av_interleaved_write_frame(oc, &packet); if (ret < 0) { fprintf(stderr, "Warning: Could not write frame of stream\n"); } else if (ret > 0) { fprintf(stderr, "End of stream requested\n"); av_free_packet(&packet); break; } av_free_packet(&packet); } while (!decode_done); av_write_trailer(oc); if (video_st) { avcodec_close(video_st->codec); } for(i = 0; i < oc->nb_streams; i++) { av_freep(&oc->streams[i]->codec); av_freep(&oc->streams[i]); } avio_close(oc->pb); av_free(oc); if (options.num_segments && (int)(last_segment - first_segment) >= options.num_segments - 1) { remove_file = 1; first_segment++; } else { remove_file = 0; } if (write_index) { write_index_file(options, first_segment, ++last_segment, 1); } if (remove_file) { snprintf(remove_filename, strlen(options.output_prefix) + 15, "%s-%u.ts", options.output_prefix, first_segment - 1); remove(remove_filename); } return 0; }
int segment(char *input_file, char* base_dirpath, char* output_index_file, char *base_file_name, char* base_file_extension, int segmentLength, int listlen) { unsigned int output_index = 1; AVOutputFormat *ofmt = NULL; AVFormatContext *ic = NULL; AVFormatContext *oc; AVStream *in_video_st = NULL; AVStream *in_audio_st = NULL; AVStream *out_video_st = NULL; AVStream *out_audio_st = NULL; AVCodec *codec; int ret; int quiet = 0; char currentOutputFileName[MAX_FILENAME_LENGTH] = {0}; double segment_start_time = 0.0; char tmp_output_index_file[MAX_FILENAME_LENGTH] = {0}; unsigned int actual_segment_durations[MAX_SEGMENTS+1]; double packet_time = 0; sprintf(tmp_output_index_file, "%s.tmp", output_index_file); av_register_all(); avformat_network_init(); //just to be safe with later version and be able to handle all kind of input urls AVStream *in_stream = NULL; AVStream *out_stream = NULL; ret = avformat_open_input(&ic, input_file, NULL, NULL); if (ret != 0) { fprintf(stderr, "Could not open input file %s. Error %d.\n", input_file, ret); exit(1); } if (avformat_find_stream_info(ic, NULL) < 0) { fprintf(stderr, "Could not read stream information.\n"); avformat_close_input(&ic); exit(1); } oc = avformat_alloc_context(); if (!oc) { fprintf(stderr, "Could not allocate output context."); avformat_close_input(&ic); exit(1); } int in_video_index = -1; int in_audio_index = -1; int out_video_index = -1; int out_audio_index = -1; int i; int listofs = 1; for (i = 0; i < ic->nb_streams; i++) { switch (ic->streams[i]->codec->codec_type) { case AVMEDIA_TYPE_VIDEO: if (!out_video_st) { in_video_st=ic->streams[i]; in_video_index = i; in_video_st->discard = AVDISCARD_NONE; out_video_st = add_output_stream(oc, in_video_st); out_video_index=out_video_st->index; } break; case AVMEDIA_TYPE_AUDIO: if (!out_audio_st) { in_audio_st=ic->streams[i]; in_audio_index = i; in_audio_st->discard = AVDISCARD_NONE; out_audio_st = add_output_stream(oc, in_audio_st); out_audio_index=out_audio_st->index; } break; default: ic->streams[i]->discard = AVDISCARD_ALL; break; } } if (in_video_index == -1) { fprintf(stderr, "Source stream must have video component.\n"); avformat_close_input(&ic); avformat_free_context(oc); exit(1); } if (!ofmt) ofmt = av_guess_format("mpegts", NULL, NULL); if (!ofmt) { fprintf(stderr, "Could not find MPEG-TS muxer.\n"); exit(1); } oc->oformat = ofmt; if (oc->oformat->flags & AVFMT_GLOBALHEADER) oc->flags |= CODEC_FLAG_GLOBAL_HEADER; av_dump_format(oc, 0, base_file_name, 1); codec = avcodec_find_decoder(in_video_st->codec->codec_id); if (!codec) { fprintf(stderr, "Could not find video decoder, key frames will not be honored.\n"); } ret = avcodec_open2(in_video_st->codec, codec, NULL); if (ret < 0) { fprintf(stderr, "Could not open video decoder, key frames will not be honored.\n"); } snprintf(currentOutputFileName, MAX_FILENAME_LENGTH, "%s/%s-%u%s", base_dirpath, base_file_name, output_index, base_file_extension); if (avio_open(&oc->pb, currentOutputFileName,AVIO_FLAG_WRITE) < 0) { fprintf(stderr, "Could not open '%s'.\n", currentOutputFileName); exit(1); } else if (!quiet) { fprintf(stderr, "Starting segment '%s'\n", currentOutputFileName); } int r = avformat_write_header(oc, NULL); if (r) { fprintf(stderr, "Could not write mpegts header to first output file.\n"); exit(1); } unsigned int num_segments = 0; int decode_done; int waitfirstpacket = 1; time_t first_frame_sec = time(NULL); int iskeyframe = 0; double vid_pts2time = (double)in_video_st->time_base.num / in_video_st->time_base.den; #if USE_H264BSF AVBitStreamFilterContext* h264bsfc = av_bitstream_filter_init("h264_mp4toannexb"); #endif double prev_packet_time = 0; do { AVPacket packet; decode_done = av_read_frame(ic, &packet); if (decode_done < 0) { break; } //get the most recent packet time //this time is used when the time for the final segment is printed. It may not be on the edge of //of a keyframe! if (packet.stream_index == in_video_index) { #if USE_H264BSF av_bitstream_filter_filter(h264bsfc, ic->streams[in_video_index]->codec, NULL, &packet.data, &packet.size, packet.data, packet.size, 0); #endif packet.stream_index = out_video_index; packet_time = (double) packet.pts * vid_pts2time; iskeyframe = packet.flags & AV_PKT_FLAG_KEY; if (iskeyframe && waitfirstpacket) { waitfirstpacket = 0; prev_packet_time = packet_time; segment_start_time = packet_time; first_frame_sec = time(NULL); } } else if (packet.stream_index == in_audio_index){ packet.stream_index = out_audio_index; iskeyframe=0; } else { //how this got here?! av_free_packet(&packet); continue; } if (waitfirstpacket) { av_free_packet(&packet); continue; } //start looking for segment splits for videos one half second before segment duration expires. This is because the //segments are split on key frames so we cannot expect all segments to be split exactly equally. if (iskeyframe && ((packet_time - segment_start_time) >= (segmentLength - 0.25)) ) { //a keyframe near or past segmentLength -> SPLIT printf("key frame packet time=%f, start time=%f\n", packet_time, segment_start_time); avio_flush(oc->pb); avio_close(oc->pb); actual_segment_durations[num_segments] = (unsigned int) rint(prev_packet_time - segment_start_time); num_segments++; if (num_segments > listlen) { //move list to exclude last: snprintf(currentOutputFileName, MAX_FILENAME_LENGTH, "%s/%s-%u%s", base_dirpath, base_file_name, listofs, base_file_extension); unlink (currentOutputFileName); listofs++; num_segments--; memmove(actual_segment_durations,actual_segment_durations+1,num_segments*sizeof(actual_segment_durations[0])); } write_index_file(output_index_file, tmp_output_index_file, segmentLength, num_segments, actual_segment_durations, listofs, base_file_name, base_file_extension, (num_segments >= MAX_SEGMENTS)); if (num_segments == MAX_SEGMENTS) { fprintf(stderr, "Reached \"hard\" max segment number %u. If this is not live stream increase segment duration. If live segmenting set max list lenth (-m ...)\n", MAX_SEGMENTS); break; } output_index++; snprintf(currentOutputFileName, MAX_FILENAME_LENGTH, "%s/%s-%u%s", base_dirpath, base_file_name, output_index, base_file_extension); if (avio_open(&oc->pb, currentOutputFileName, AVIO_FLAG_WRITE) < 0) { fprintf(stderr, "Could not open '%s'\n", currentOutputFileName); break; } else if (!quiet) { fprintf(stderr, "Starting segment '%s'\n", currentOutputFileName); } fflush(stderr); segment_start_time = packet_time; first_frame_sec=time(NULL); } if (packet.stream_index == out_video_index) { prev_packet_time = packet_time; } in_stream = ic->streams[packet.stream_index]; out_stream = oc->streams[packet.stream_index]; packet.pts = av_rescale_q_rnd(packet.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); packet.dts = av_rescale_q_rnd(packet.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); packet.duration = av_rescale_q(packet.duration, in_stream->time_base, out_stream->time_base); packet.pos = -1; ret = av_write_frame(oc, &packet); if (ret < 0) { fprintf(stderr, "Warning: Could not write frame of stream.\n"); } else if (ret > 0) { fprintf(stderr, "End of stream requested.\n"); av_free_packet(&packet); break; } av_free_packet(&packet); } while (!decode_done); if (in_video_st->codec->codec !=NULL) avcodec_close(in_video_st->codec); if (num_segments < MAX_SEGMENTS) { //make sure all packets are written and then close the last file. avio_flush(oc->pb); av_write_trailer(oc); for (i = 0; i < oc->nb_streams; i++) { av_freep(&oc->streams[i]->codec); av_freep(&oc->streams[i]); } avio_close(oc->pb); av_free(oc); if (num_segments>0){ actual_segment_durations[num_segments] = (unsigned int) rint(packet_time - segment_start_time); if (actual_segment_durations[num_segments] == 0) actual_segment_durations[num_segments] = 1; num_segments++; write_index_file(output_index_file, tmp_output_index_file, segmentLength, num_segments, actual_segment_durations, listofs, base_file_name, base_file_extension, 1); } } avformat_close_input(&ic); return 0; }
/** * @TODO */ int build_ann_index(char *bname) { char docid2path[PATH_MAX], indexfile[PATH_MAX]; char annpath[PATH_MAX]; char ndocsfile[PATH_MAX]; int ret; int result = -1; FILE *fp; snprintf(annpath, sizeof(annpath), "data/0Announce/%s", bname); set_anndocid2path_file(docid2path, bname); set_annindex_file(indexfile, bname); /* Initialize the DB structure.*/ ret = db_create(&g_dbp, NULL, 0); if (ret != 0) { ERROR("create db hanldle failed"); goto RETURN; } if (dbopen(g_dbp, docid2path, 1) != 0) { ERROR1("open db %s failed", docid2path); goto RETURN; } g_bucket = new_postinglist_bucket(g_size); if (g_bucket == NULL) { ERROR1("new_postinglist_bucket size=%u failed", g_size); goto CLEAN_DB; } g_text = malloc(MAX_FILE_SIZE); if (g_text == NULL) { ERROR("malloc failed"); goto CLEAN_MEM; } /* Zero out the DBTs before using them. */ memset(&g_key, 0, sizeof(DBT)); memset(&g_data, 0, sizeof(DBT)); g_key.size = sizeof(unsigned int); g_key.data = &g_docid; /* TODO: cache, ensure the cache directory exists */ ann_traverse(annpath, index_file); write_index_file(g_bucket, g_size, indexfile); calc_doc_weight(bname, ANNOUNCE, g_docid - 1); set_annndocs_file(ndocsfile, bname); fp = fopen(ndocsfile, "w"); if (fp == NULL) { ERROR1("fopen %s failed", ndocsfile); goto CLEAN; } fprintf(fp, "%u", g_docid - 1); fclose(fp); /* it's ok */ result = 0; CLEAN: free(g_text); CLEAN_MEM: free(g_bucket); CLEAN_DB: if (g_dbp != NULL) g_dbp->close(g_dbp, 0); RETURN: return result; }
void cache_object_write(struct cache_object *co) { write_cache_file(&co->cc); write_index_file(&co->ci); }
void close_index_file(struct cache_index *idx) { if (!idx->flushed) write_index_file(idx); fclose(idx->idxfile); }
int main(int argc, char **argv) { const char *input; const char *output_prefix; double segment_duration; char *segment_duration_check; const char *index; char *tmp_index; const char *http_prefix; long max_tsfiles = 0; char *max_tsfiles_check; double prev_segment_time = 0; unsigned int output_index = 1; AVInputFormat *ifmt; AVOutputFormat *ofmt; AVFormatContext *ic = NULL; AVFormatContext *oc; AVStream *video_st; AVStream *audio_st; AVCodec *codec; char *output_filename; char *remove_filename; int video_index; int audio_index; unsigned int first_segment = 1; unsigned int last_segment = 0; int write_index = 1; int decode_done; char *dot; int ret; int i; int remove_file; if (argc < 6 || argc > 7) { fprintf(stderr, "Usage: %s <input MPEG-TS file> <segment duration in seconds> <output MPEG-TS file prefix> <output m3u8 index file> <http prefix> [<segment window size>]\n", argv[0]); exit(1); } av_register_all(); input = argv[1]; if (!strcmp(input, "-")) { input = "pipe:"; } segment_duration = strtod(argv[2], &segment_duration_check); if (segment_duration_check == argv[2] || segment_duration == HUGE_VAL || segment_duration == -HUGE_VAL) { fprintf(stderr, "Segment duration time (%s) invalid\n", argv[2]); exit(1); } output_prefix = argv[3]; index = argv[4]; http_prefix=argv[5]; if (argc == 7) { max_tsfiles = strtol(argv[6], &max_tsfiles_check, 10); if (max_tsfiles_check == argv[6] || max_tsfiles < 0 || max_tsfiles >= INT_MAX) { fprintf(stderr, "Maximum number of ts files (%s) invalid\n", argv[6]); exit(1); } } remove_filename = malloc(sizeof(char) * (strlen(output_prefix) + 15)); if (!remove_filename) { fprintf(stderr, "Could not allocate space for remove filenames\n"); exit(1); } output_filename = malloc(sizeof(char) * (strlen(output_prefix) + 15)); if (!output_filename) { fprintf(stderr, "Could not allocate space for output filenames\n"); exit(1); } tmp_index = malloc(strlen(index) + 2); if (!tmp_index) { fprintf(stderr, "Could not allocate space for temporary index filename\n"); exit(1); } strncpy(tmp_index, index, strlen(index) + 2); dot = strrchr(tmp_index, '/'); dot = dot ? dot + 1 : tmp_index; for (i = strlen(tmp_index) + 1; i > dot - tmp_index; i--) { tmp_index[i] = tmp_index[i - 1]; } *dot = '.'; ifmt = av_find_input_format("mpegts"); if (!ifmt) { fprintf(stderr, "Could not find MPEG-TS demuxer\n"); exit(1); } ret = av_open_input_file(&ic, input, ifmt, 0, NULL); if (ret != 0) { fprintf(stderr, "Could not open input file, make sure it is an mpegts file: %d\n", ret); exit(1); } if (av_find_stream_info(ic) < 0) { fprintf(stderr, "Could not read stream information\n"); exit(1); } ofmt = av_guess_format("mpegts", NULL, NULL); if (!ofmt) { fprintf(stderr, "Could not find MPEG-TS muxer\n"); exit(1); } oc = avformat_alloc_context(); if (!oc) { fprintf(stderr, "Could not allocated output context"); exit(1); } oc->oformat = ofmt; video_index = -1; audio_index = -1; for (i = 0; i < ic->nb_streams && (video_index < 0 || audio_index < 0); i++) { switch (ic->streams[i]->codec->codec_type) { case AVMEDIA_TYPE_VIDEO: video_index = i; ic->streams[i]->discard = AVDISCARD_NONE; video_st = add_output_stream(oc, ic->streams[i]); break; case AVMEDIA_TYPE_AUDIO: audio_index = i; ic->streams[i]->discard = AVDISCARD_NONE; audio_st = add_output_stream(oc, ic->streams[i]); break; default: ic->streams[i]->discard = AVDISCARD_ALL; break; } } if (av_set_parameters(oc, NULL) < 0) { fprintf(stderr, "Invalid output format parameters\n"); exit(1); } dump_format(oc, 0, output_prefix, 1); codec = avcodec_find_decoder(video_st->codec->codec_id); if (!codec) { fprintf(stderr, "Could not find video decoder, key frames will not be honored\n"); } if (avcodec_open(video_st->codec, codec) < 0) { fprintf(stderr, "Could not open video decoder, key frames will not be honored\n"); } snprintf(output_filename, strlen(output_prefix) + 15, "%s-%u.ts", output_prefix, output_index++); if (url_fopen(&oc->pb, output_filename, URL_WRONLY) < 0) { fprintf(stderr, "Could not open '%s'\n", output_filename); exit(1); } if (av_write_header(oc)) { fprintf(stderr, "Could not write mpegts header to first output file\n"); exit(1); } write_index = !write_index_file(index, tmp_index, segment_duration, output_prefix, http_prefix, first_segment, last_segment, 0, max_tsfiles); do { double segment_time; AVPacket packet; decode_done = av_read_frame(ic, &packet); if (decode_done < 0) { break; } if (av_dup_packet(&packet) < 0) { fprintf(stderr, "Could not duplicate packet"); av_free_packet(&packet); break; } if (packet.stream_index == video_index && (packet.flags & AV_PKT_FLAG_KEY)) { segment_time = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den; } else if (video_index < 0) { segment_time = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den; } else { segment_time = prev_segment_time; } if (segment_time - prev_segment_time >= segment_duration) { put_flush_packet(oc->pb); url_fclose(oc->pb); if (max_tsfiles && (int)(last_segment - first_segment) >= max_tsfiles - 1) { remove_file = 1; first_segment++; } else { remove_file = 0; } if (write_index) { write_index = !write_index_file(index, tmp_index, segment_duration, output_prefix, http_prefix, first_segment, ++last_segment, 0, max_tsfiles); } if (remove_file) { snprintf(remove_filename, strlen(output_prefix) + 15, "%s-%u.ts", output_prefix, first_segment - 1); remove(remove_filename); } snprintf(output_filename, strlen(output_prefix) + 15, "%s-%u.ts", output_prefix, output_index++); if (url_fopen(&oc->pb, output_filename, URL_WRONLY) < 0) { fprintf(stderr, "Could not open '%s'\n", output_filename); break; } prev_segment_time = segment_time; } ret = av_interleaved_write_frame(oc, &packet); if (ret < 0) { fprintf(stderr, "Warning: Could not write frame of stream\n"); } else if (ret > 0) { fprintf(stderr, "End of stream requested\n"); av_free_packet(&packet); break; } av_free_packet(&packet); } while (!decode_done); av_write_trailer(oc); avcodec_close(video_st->codec); for(i = 0; i < oc->nb_streams; i++) { av_freep(&oc->streams[i]->codec); av_freep(&oc->streams[i]); } url_fclose(oc->pb); av_free(oc); if (max_tsfiles && (int)(last_segment - first_segment) >= max_tsfiles - 1) { remove_file = 1; first_segment++; } else { remove_file = 0; } if (write_index) { write_index_file(index, tmp_index, segment_duration, output_prefix, http_prefix, first_segment, ++last_segment, 1, max_tsfiles); } if (remove_file) { snprintf(remove_filename, strlen(output_prefix) + 15, "%s-%u.ts", output_prefix, first_segment - 1); remove(remove_filename); } return 0; }
// Read VCF file void vcf_file::scan_file(const string &chr, const string &exclude_chr, bool force_write_index) { bool filter_by_chr = (chr != ""); bool exclude_by_chr = (exclude_chr != ""); string index_filename = filename + ".vcfidx"; bool could_read_index_file = false; if (force_write_index == false) could_read_index_file = read_index_file(index_filename); string CHROM, last_CHROM=""; int POS, last_POS = -1; if (could_read_index_file == false) { printLOG("Building new index file.\n"); string line, CHROM, last_CHROM = ""; streampos filepos; char c; N_entries=0; N_indv = 0; while (!feof()) { filepos = get_filepos(); c = peek(); if ((c == '\n') || (c == '\r')) { read_line(line); continue; } else if (c == EOF) break; if (c == '#') { read_line(line); if (line[1] == '#') { // Meta information parse_meta(line); } else { // Must be header information: #CHROM POS ID REF ALT QUAL FILTER INFO (FORMAT NA00001 NA00002 ... ) parse_header(line); } } else { // Must be a data line read_CHROM_and_POS_and_skip_remainder_of_line(CHROM, POS); if (last_CHROM != CHROM) { printLOG("\tScanning Chromosome: " + CHROM + "\n"); last_CHROM = CHROM; } if (POS == last_POS) { one_off_warning("\tWarning - file contains entries with the same position. This is not supported by vcftools, and may cause unexpected behaviour.\n"); } last_POS = POS; entry_file_locations.push_back(filepos); N_entries++; } } write_index_file(index_filename); } printLOG("File contains " + int2str(N_entries) + " entries and " + int2str(N_indv) + " individuals.\n"); vector<string> meta_lines = meta; meta.resize(0); for (unsigned int ui=0; ui<meta_lines.size(); ui++) parse_meta(meta_lines[ui]); has_genotypes = (N_indv > 0); bool already_found_required_chr = false; bool already_filtered_required_chr = false; if ((exclude_by_chr == true) || (filter_by_chr == true)) { printLOG("Filtering by chromosome.\n"); for (unsigned int ui=0; ui<N_entries; ui++) { if (already_found_required_chr == true) { printLOG("Skipping Remainder.\n"); entry_file_locations.erase(entry_file_locations.begin()+ui, entry_file_locations.end()); break; } if (already_filtered_required_chr == true) { printLOG("Skipping Remainder.\n"); break; } set_filepos(entry_file_locations[ui]); read_CHROM_only(CHROM); if (last_CHROM != CHROM) { printLOG("\tChromosome: " + CHROM + "\n"); if ((filter_by_chr == true) && (last_CHROM == chr)) already_found_required_chr = true; if ((exclude_by_chr == true) && (last_CHROM == exclude_chr)) already_filtered_required_chr = true; last_CHROM = CHROM; } if ((exclude_by_chr == true) && (CHROM == exclude_chr)) { entry_file_locations[ui] = -1; continue; } if ((filter_by_chr == true) && (CHROM != chr)) { entry_file_locations[ui] = -1; continue; } } sort(entry_file_locations.begin(), entry_file_locations.end()); while((entry_file_locations.size() > 0) && (entry_file_locations[0] < 0)) entry_file_locations.pop_front(); N_entries = entry_file_locations.size(); printLOG("Keeping " + int2str(N_entries) + " entries on specified chromosomes.\n"); } include_indv.clear(); include_indv.resize(N_indv, true); include_entry.clear(); include_entry.resize(N_entries, true); include_genotype.clear(); include_genotype.resize(N_entries, vector<bool>(N_indv, true)); }