void compile() { #pragma omp parallel for schedule(dynamic, 1) for(int channel = 0; channel < JAKMUSE_NUMCHANNELS; ++channel) { auto& seqs = g_channel_sequences[channel]; auto& gen = g_generators[channel]; for(auto& seq : seqs) { auto& params = seq.params; auto& notes = seq.notes; process_params(params, gen); for(auto& note : notes) { unsigned scale = gen.NewNote(note.frequency); unsigned numSamples = JAKMUSE_SAMPLES_PER_SECOND / scale * note.length; for(size_t i = 0; i < numSamples; ++i) { pwm_t sample = gen(); g_channels[channel].push_back(sample); } } } } // compute g_maxChannelLen g_maxChannelLen = 0; for(auto&& chan : g_channels) { g_maxChannelLen = std::max(g_maxChannelLen, chan.size()); } }
/** * @ingroup dac_sink * * Writes the received samples to the dac output buffer * */ int work(void **inp, void **out) { int rcv_samples; int n; rcv_samples = get_input_samples(0); if (!rcv_samples) { return 0; } if (check_blen && check_blen != rcv_samples) { moderror_msg("Expected %d samples but got %d\n", check_blen, rcv_samples); return -1; } if (process_params()) { return -1; } vec_mult_c_r((complex_t*) inp[0],out_buffer,amplitude,rcv_samples); if (enable_dac) { n = rtdal_dac_send(dac,out_buffer,rcv_samples,blocking); } else { n = rcv_samples; } modinfo_msg("send %d samples amplitude %g\n",n,amplitude); if (n != rcv_samples) { moderror_msg("Sent %d/%d samples\n",n,rcv_samples); return -1; } return 0; }
/** * @ingroup dac_source * * Writes the received samples to the dac output buffer * */ int work(void **inp, void **out) { int n; if (!stream_started) { rtdal_dac_start_rx_stream(dac); stream_started=1; } if (process_params()) { return -1; } if (!nsamples) { return 0; } if (!out[0]) { moderror("Output interface not ready\n"); return -1; } if (cnt<wait_packets) { cnt++; modinfo_msg("not receiving ts=%d\n",oesr_tstamp(ctx)); return 0; } n = rtdal_dac_recv(dac,out[0],nsamples,blocking); modinfo_msg("ts=%d, recv %d samples\n",oesr_tstamp(ctx),n); if (n != nsamples) { moderror_msg("Recv %d/%d samples\n",n,nsamples); return -1; } return nsamples; }
/** * @ingroup dac_source * * \param rate Sets DA converter sampling rateuency */ int initialize() { var_t pm; pm = oesr_var_param_get(ctx, "board"); if (!pm) { moderror("Parameter board undefined\n"); return -1; } if (oesr_var_param_get_value(ctx, pm, board, 128) == -1) { moderror("Error getting board value\n"); return -1; } pm = oesr_var_param_get(ctx, "args"); if (pm) { if (oesr_var_param_get_value(ctx, pm, args, 128) == -1) { moderror("Error getting board value\n"); return -1; } } else { bzero(args,128); } blocking=0; param_get_int_name("blocking",&blocking); wait_packets=0; param_get_int_name("wait_packets",&wait_packets); nsamples_id = param_id("nsamples"); if (!nsamples_id) { moderror("Parameter nsamples not found\n"); return -1; } rate_id = param_id("rate"); if (!rate_id) { moderror("Parameter rate not found\n"); return -1; } freq_id = param_id("freq"); if (!freq_id) { moderror("Parameter freq not found\n"); return -1; } gain_id = param_id("gain"); dac = rtdal_dac_open(board,args); if (!dac) { moderror_msg("Initiating DAC %s (args=%s)\n",board,args); return -1; } if (process_params()) { moderror("Setting parameters\n"); return -1; } return 0; }
int main(int argc, char ** argv) { struct thread_data * data; int rv; pthread_t thread; int index = 1; setlocale(LC_CTYPE, ""); if (!freerdp_global_init()) { printf("Error initializing freerdp\n"); return 1; } freerdp_chanman_init(); dfb_init(&argc, &argv); dfb_kb_init(); while (1) { data = (struct thread_data *) malloc(sizeof(struct thread_data)); data->settings = (rdpSet *) malloc(sizeof(rdpSet)); data->chan_man = freerdp_chanman_new(); rv = process_params(data->settings, data->chan_man, argc, argv, &index); if (rv == 0) { g_thread_count++; printf("starting thread %d to %s:%d\n", g_thread_count, data->settings->server, data->settings->tcp_port_rdp); pthread_create(&thread, 0, thread_func, data); } else { free(data->settings); freerdp_chanman_free(data->chan_man); free(data); break; } } while (g_thread_count > 0) { sleep(1); } freerdp_chanman_uninit(); freerdp_global_finish(); return 0; }
/** * @ingroup dac_sink * * \param rate Sets DA converter sampling rateuency */ int initialize() { var_t pm; pm = oesr_var_param_get(ctx, "board"); if (!pm) { moderror("Parameter board undefined\n"); return -1; } if (oesr_var_param_get_value(ctx, pm, board, 128) == -1) { moderror("Error getting board value\n"); return -1; } pm = oesr_var_param_get(ctx, "args"); if (pm) { if (oesr_var_param_get_value(ctx, pm, args, 128) == -1) { moderror("Error getting board value\n"); return -1; } } else { bzero(args,128); } check_blen=0; param_get_int_name("check_blen",&check_blen); enable_dac=1; param_get_int_name("enable_dac",&enable_dac); rate_id = param_id("rate"); if (!rate_id) { moderror("Parameter rate not found\n"); return -1; } freq_id = param_id("freq"); if (!freq_id) { moderror("Parameter freq not found\n"); return -1; } gain_id = param_id("gain"); amp_id = param_id("amplitude"); blocking=0; param_get_int_name("blocking",&blocking); if (!enable_dac) { modinfo("Warning: DAC is disabled\n"); } dac = rtdal_dac_open(board,args); return process_params(); }
static atf_error_t controlled_main(int argc, char **argv, atf_error_t (*add_tcs_hook)(atf_tp_t *), int *exitcode) { atf_error_t err; struct params p; atf_tp_t tp; char **raw_config; err = process_params(argc, argv, &p); if (atf_is_error(err)) goto out; err = handle_srcdir(&p); if (atf_is_error(err)) goto out_p; raw_config = atf_map_to_charpp(&p.m_config); if (raw_config == NULL) { err = atf_no_memory_error(); goto out_p; } err = atf_tp_init(&tp, (const char* const*)raw_config); atf_utils_free_charpp(raw_config); if (atf_is_error(err)) goto out_p; err = add_tcs_hook(&tp); if (atf_is_error(err)) goto out_tp; if (p.m_do_list) { list_tcs(&tp); INV(!atf_is_error(err)); *exitcode = EXIT_SUCCESS; } else { err = run_tc(&tp, &p, exitcode); } out_tp: atf_tp_fini(&tp); out_p: params_fini(&p); out: return err; }
void editor::run(int argc, char **argv) { #ifdef ENABLE_GTK_BACKEND gtk_init(&argc, &argv); #endif if(!process_params(argc, argv)) { exit(0); } #ifdef ENABLE_GUI if(state.config.gui_enabled) gui.window_create("editor_main"); #endif configure(); #ifdef ENABLE_GUI if(state.config.gui_enabled) { editor_command_scene_reset(); gui.run(); } #endif }
static PLI_INT32 sys_writemem_calltf(ICARUS_VPI_CONST PLI_BYTE8*name) { int addr; FILE*file; char*fname = 0; unsigned cnt; s_vpi_value value; vpiHandle callh = vpi_handle(vpiSysTfCall, 0); vpiHandle argv = vpi_iterate(vpiArgument, callh); vpiHandle mitem = 0; vpiHandle start_item = 0; vpiHandle stop_item = 0; int start_addr, stop_addr, addr_incr; int min_addr, max_addr; // Not used in this routine. /*======================================== Get parameters */ get_mem_params(argv, callh, name, &fname, &mitem, &start_item, &stop_item); if (fname == 0) return 0; /*======================================== Process parameters */ if (process_params(mitem, start_item, stop_item, callh, name, &start_addr, &stop_addr, &addr_incr, &min_addr, &max_addr)) { free(fname); return 0; } /* Open the data file. */ file = fopen(fname, "w"); if (file == 0) { vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh), (int)vpi_get(vpiLineNo, callh)); vpi_printf("%s: Unable to open %s for writing.\n", name, fname); free(fname); return 0; } if (strcmp(name,"$writememb")==0) value.format = vpiBinStrVal; else value.format = vpiHexStrVal; /*======================================== Write memory file */ cnt = 0; for(addr=start_addr; addr!=stop_addr+addr_incr; addr+=addr_incr, ++cnt) { vpiHandle word_index; if (cnt%16 == 0) fprintf(file, "// 0x%08x\n", cnt); word_index = vpi_handle_by_index(mitem, addr); assert(word_index); vpi_get_value(word_index, &value); fprintf(file, "%s\n", value.value.str); } fclose(file); free(fname); return 0; }
static PLI_INT32 sys_readmem_calltf(ICARUS_VPI_CONST PLI_BYTE8*name) { int code, wwid, addr; FILE*file; char *fname = 0; s_vpi_value value; vpiHandle callh = vpi_handle(vpiSysTfCall, 0); vpiHandle argv = vpi_iterate(vpiArgument, callh); vpiHandle mitem = 0; vpiHandle start_item = 0; vpiHandle stop_item = 0; /* start_addr and stop_addr are the parameters given to $readmem in the Verilog code. When not specified, start_addr is equal to the lower of the [left,right]_addr and stop_addr is equal to the higher of the [left,right]_addr. */ int start_addr, stop_addr, addr_incr; /* min_addr and max_addr are equal to start_addr and stop_addr if start_addr<stop_addr or vice versa if not... */ int min_addr, max_addr; /* This is the number of words that we need from the memory. */ unsigned word_count; /*======================================== Get parameters */ get_mem_params(argv, callh, name, &fname, &mitem, &start_item, &stop_item); if (fname == 0) return 0; /*======================================== Process parameters */ if (process_params(mitem, start_item, stop_item, callh, name, &start_addr, &stop_addr, &addr_incr, &min_addr, &max_addr)) { free(fname); return 0; } /* Open the data file. */ file = fopen(fname, "r"); /* Check to see if we have other directories to look for this file. */ if (file == 0 && sl_count > 0 && fname[0] != '/') { unsigned idx; char path[4096]; for (idx = 0; idx < sl_count; idx += 1) { snprintf(path, sizeof(path), "%s/%s", search_list[idx], fname); path[sizeof(path)-1] = 0; if ((file = fopen(path, "r"))) break; } } if (file == 0) { vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh), (int)vpi_get(vpiLineNo, callh)); vpi_printf("%s: Unable to open %s for reading.\n", name, fname); free(fname); return 0; } /* We need this many words from the file. */ word_count = max_addr-min_addr+1; wwid = vpi_get(vpiSize, vpi_handle_by_index(mitem, min_addr)); /* variable that will be used by the lexer to pass values back to this code */ value.format = vpiVectorVal; value.value.vector = calloc((wwid+31)/32, sizeof(s_vpi_vecval)); /* Configure the readmem lexer */ if (strcmp(name,"$readmemb") == 0) sys_readmem_start_file(file, 1, wwid, value.value.vector); else sys_readmem_start_file(file, 0, wwid, value.value.vector); /*======================================== Read memory file */ /* Run through the input file and store the new contents in the memory */ addr = start_addr; while ((code = readmemlex()) != 0) { switch (code) { case MEM_ADDRESS: addr = value.value.vector->aval; if (addr < min_addr || addr > max_addr) { vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh), (int)vpi_get(vpiLineNo, callh)); vpi_printf("%s(%s): address (0x%x) is out of range " "[0x%x:0x%x]\n", name, fname, addr, start_addr, stop_addr); goto bailout; } /* if there is an address in the memory file, then turn off any possible warnings about not having enough words to load the memory. This is standard behavior from 1364-2005. */ word_count = 0; break; case MEM_WORD: if (addr >= min_addr && addr <= max_addr) { vpiHandle word_index; word_index = vpi_handle_by_index(mitem, addr); assert(word_index); vpi_put_value(word_index, &value, 0, vpiNoDelay); if (word_count > 0) word_count -= 1; } else { vpi_printf("WARNING: %s:%d: ", vpi_get_str(vpiFile, callh), (int)vpi_get(vpiLineNo, callh)); vpi_printf("%s(%s): Too many words in the file for the " "requested range [%d:%d].\n", name, fname, start_addr, stop_addr); goto bailout; } addr += addr_incr; break; case MEM_ERROR: vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh), (int)vpi_get(vpiLineNo, callh)); vpi_printf("%s(%s): Invalid input character: %s\n", name, fname, readmem_error_token); goto bailout; break; default: assert(0); break; } } /* Print a warning if there are not enough words in the data file. */ if (word_count > 0) { vpi_printf("WARNING: %s:%d: ", vpi_get_str(vpiFile, callh), (int)vpi_get(vpiLineNo, callh)); vpi_printf("%s(%s): Not enough words in the file for the " "requested range [%d:%d].\n", name, fname, start_addr, stop_addr); } bailout: free(value.value.vector); free(fname); fclose(file); destroy_readmem_lexor(); return 0; }
// generates code to implement node's action static void implement_node(ast_node node){ if (node != NULL){ if (node->node_type == ROOT){ process_root(node); } // generate code for assignment operator else if (node->node_type == OP_ASSIGN){ process_assign(node); } // generate code for negate operator else if (node->node_type == OP_NEG) { process_negate(node); } // generate code for +, -, *, /, %, =, !=, <, <=, >, >= else if (node->node_type > 0 && node->node_type <= 16 && node->node_type != 14 && node->node_type != 15){ process_math(node); } else if (node->node_type == OP_INC){ process_inc(node, "1"); } else if (node->node_type == OP_DEC){ process_inc(node, "-1"); } else if (node->node_type == IF_STMT){ process_if(node); } else if (node->node_type == IF_ELSE_STMT){ process_ifelse(node); } else if (node->node_type == CMPD){ process_cmpd(node); } else if (node->node_type == WHILE_STMT){ process_while(node); } else if (node->node_type == DO_WHILE_STMT){ process_dowhile(node); } else if (node->node_type == OP_AND){ process_and(node); } else if (node->node_type == OP_OR){ process_or(node); } else if (node->node_type == FOR_STRT || node->node_type == FOR_COND || node->node_type == FOR_UPDT){ process_for_header(node); } else if (node->node_type == FOR_STMT){ process_for(node); } else if (node->node_type == READ_STMT){ process_read(node); } else if (node->node_type == PRINT_STMT){ process_print(node); } else if (node->node_type == RETURN_STMT){ process_return(node); } else if (node->node_type == FUNCDEC){ process_function(node); } else if (node->node_type == PARAMS){ process_params(node); } else if (node->node_type == INT_TYPE || node->node_type == DOUBLE_TYPE){ process_vardec(node); } else if (node->node_type == CALL){ process_call(node); } else if (node->node_type == IDENT){ process_id(node); } else if (node->node_type == ARRAY){ process_array(node); } } }
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int rv; int index = 1; wfInfo * wfi; WSADATA wsa_data; WNDCLASSEX wnd_cls; if (WSAStartup(0x101, &wsa_data) != 0) { return 1; } g_done_event = CreateEvent(0, 1, 0, 0); #if defined(WITH_DEBUG) || defined(_DEBUG) create_console(); #endif if (!freerdp_global_init()) { printf("Error initializing freerdp\n"); return 1; } freerdp_chanman_init(); g_default_cursor = LoadCursor(NULL, IDC_ARROW); wnd_cls.cbSize = sizeof(WNDCLASSEX); wnd_cls.style = CS_HREDRAW | CS_VREDRAW; wnd_cls.lpfnWndProc = wf_event_proc; wnd_cls.cbClsExtra = 0; wnd_cls.cbWndExtra = 0; wnd_cls.hIcon = LoadIcon(NULL, IDI_APPLICATION); wnd_cls.hCursor = g_default_cursor; wnd_cls.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wnd_cls.lpszMenuName = NULL; wnd_cls.lpszClassName = g_wnd_class_name; wnd_cls.hInstance = hInstance; wnd_cls.hIconSm = LoadIcon(NULL, IDI_APPLICATION); RegisterClassEx(&wnd_cls); g_hInstance = hInstance; if (!CreateThread(NULL, 0, kbd_thread_func, NULL, 0, NULL)) printf("error creating keyboard handler thread"); while (1) { wfi = (wfInfo *) malloc(sizeof(wfInfo)); memset(wfi, 0, sizeof(wfInfo)); wfi->settings = (rdpSet *) malloc(sizeof(rdpSet)); wfi->chan_man = freerdp_chanman_new(); wfi->clrconv = (HCLRCONV) malloc(sizeof(CLRCONV)); memset(wfi->clrconv, 0, sizeof(CLRCONV)); wfi->clrconv->alpha = 1; wfi->clrconv->palette = NULL; rv = process_params(wfi, __argc, __argv, &index); if (rv) { freerdp_chanman_free(wfi->chan_man); free(wfi->settings); free(wfi); break; } if (CreateThread(NULL, 0, thread_func, wfi, 0, NULL) != 0) { g_thread_count++; } } if (g_thread_count > 0) WaitForSingleObject(g_done_event, INFINITE); else MessageBox(GetConsoleWindow(), L"Failed to start wfreerdp.\n\nPlease check the debug output.", L"FreeRDP Error", MB_ICONSTOP); freerdp_chanman_uninit(); freerdp_global_finish(); WSACleanup(); return 0; }
int main(int argc, char ** argv) { struct thread_data * data; int rv; pthread_t thread; int index = 1; char *home = getenv("HOME"); if (home) { static char resourcefile[512]; strncat(resourcefile, home, strlen(home)); resourcefile[512-1] = (char)0; strcat(resourcefile, "/.directfbrc"); resourcefile[512-1] = (char)0; char *display = getenv("DISPLAY"); #if defined(__unix) || defined(__linux) char *graphics = "fbdev"; #elif defined(__APPLE__) char *graphics = "opengl"; #else char *graphics = "gdi"; #endif if (display) graphics = "x11"; static char buffer[128]; strcat(buffer, "system="); strcat(buffer, graphics); strcat(buffer, "\ndepth=32\nmode=1024x768\nautoflip-window\nforce-windowed\n"); FILE *fp; fp = fopen(resourcefile, "wx"); /* "x" assures no overwrite of an existing resource file */ if (fp != NULL) { fputs((char *)(&buffer), fp); fclose(fp); printf("INFO: created default DirectFB resource file: %s\n", resourcefile); } } else { printf("WARNING: HOME variable not set, unable to create a default DirectFB ~/.directfbrc resource file\n"); } setlocale(LC_CTYPE, ""); if (!freerdp_global_init()) { printf("Error initializing freerdp\n"); return 1; } freerdp_chanman_init(); dfb_init(&argc, &argv); dfb_kb_init(); freerdp_sem_create(&g_sem, 0); while (1) { data = (struct thread_data *) xmalloc(sizeof(struct thread_data)); data->settings = (rdpSet *) xmalloc(sizeof(rdpSet)); data->chan_man = freerdp_chanman_new(); rv = process_params(data->settings, data->chan_man, argc, argv, &index); if (rv == 0) { g_thread_count++; printf("starting thread %d to %s:%d\n", g_thread_count, data->settings->server, data->settings->tcp_port_rdp); pthread_create(&thread, 0, thread_func, data); } else { free(data->settings); freerdp_chanman_free(data->chan_man); free(data); break; } } while (g_thread_count > 0) { DEBUG("main thread, waiting for all threads to exit"); freerdp_sem_wait(&g_sem); DEBUG("main thread, all threads did exit"); } freerdp_chanman_uninit(); freerdp_global_finish(); return 0; }
// Add the given case method into the given match method wrapper and check the // are compatible. // Returns: match case for worker method or NULL on error. static ast_t* add_case_method(ast_t* match_method, ast_t* case_method) { assert(match_method != NULL); assert(case_method != NULL); // We need default capabality and return value if not provided explicitly. if(ast_id(case_method) == TK_FUN) fun_defaults(case_method); AST_GET_CHILDREN(match_method, match_cap, match_id, match_t_params, match_params, match_ret_type, match_question); AST_GET_CHILDREN(case_method, case_cap, case_id, case_t_params, case_params, case_ret_type, case_question, case_body, case_docstring, case_guard); bool ok = true; if(ast_id(case_method) != ast_id(match_method)) { ast_error(case_method, "cannot mix fun and be cases in a single match method"); ast_error(match_method, "clashing method here"); ok = false; } if(ast_id(case_method) == TK_FUN) { if(ast_id(case_cap) != ast_id(match_cap)) { ast_error(case_cap, "differing receiver capabilities on case methods"); ast_error(match_cap, "clashing capability here"); ok = false; } if(ast_id(match_ret_type) == TK_NONE) { // Use case method return type. ast_replace(&match_ret_type, case_ret_type); } else { // Union this case method's return type with the existing match one. REPLACE(&match_ret_type, NODE(TK_UNIONTYPE, TREE(match_ret_type) TREE(case_ret_type))); } } if(ast_id(case_question) == TK_QUESTION) // If any case throws the match does too. ast_setid(match_question, TK_QUESTION); if(!process_t_params(match_t_params, case_t_params)) ok = false; ast_t* pattern = process_params(match_params, case_params); if(!ok || pattern == NULL) { ast_free(pattern); return NULL; } // Extract case body and guard condition (if any) to avoid copying. ast_t* body = ast_from(case_body, TK_NONE); ast_swap(case_body, body); ast_t* guard = ast_from(case_guard, TK_NONE); ast_swap(case_guard, guard); // Make match case. BUILD(match_case, pattern, NODE(TK_CASE, AST_SCOPE TREE(pattern) TREE(case_guard) TREE(case_body))); return match_case; }
int main(int argc, char ** argv) { int rv; xfInfo * xfi; pthread_t thread; int index = 1; char reason_msg[ERRINFO_BUFFER_SIZE]; setlocale(LC_CTYPE, ""); if (argc == 1) { out_args(); return 0; } if (!freerdp_global_init()) { printf("Error initializing freerdp\n"); return 1; } freerdp_chanman_init(); freerdp_sem_create(&g_sem, 0); while (1) { xfi = (xfInfo *) malloc(sizeof(xfInfo)); memset(xfi, 0, sizeof(xfInfo)); xfi->settings = (rdpSet *) malloc(sizeof(rdpSet)); xfi->chan_man = freerdp_chanman_new(); xfi->clrconv = (HCLRCONV) malloc(sizeof(CLRCONV)); memset(xfi->clrconv, 0, sizeof(CLRCONV)); xfi->clrconv->alpha = 1; xfi->clrconv->palette = NULL; rv = process_params(xfi, argc, argv, &index); if (rv) { free(xfi->settings); freerdp_chanman_free(xfi->chan_man); free(xfi); break; } DEBUG_X11("starting thread %d to %s:%d", g_thread_count, xfi->settings->server, xfi->settings->tcp_port_rdp); if (pthread_create(&thread, 0, thread_func, xfi) == 0) { g_thread_count++; } } if (g_thread_count > 0) { DEBUG_X11("main thread, waiting for all threads to exit"); freerdp_sem_wait(&g_sem); DEBUG_X11("main thread, all threads did exit"); } freerdp_chanman_uninit(); freerdp_global_finish(); if (g_error_code) return g_error_code; else if (g_disconnect_reason) { printf("disconnect: %s\n", freerdp_str_disconnect_reason(g_disconnect_reason, reason_msg, ERRINFO_BUFFER_SIZE)); } return exit_code_from_disconnect_reason(g_disconnect_reason); }
/** * The main program * * Parameters: * - int argc => The number of arguments passed * - char** args => The arguments list * * Return: * - int => The result of the execution */ int main(int argc, char** args) { /* ##### Process parameters and get filter ##### */ int filter = process_params(argc, args); /* ##### Network structures ##### */ // Initialize the client socket struct sockaddr_in destination; int client_socket = init_socket(args[1], &destination); // Parameters for the packet transmission struct packet to_server; struct packet from_server; socklen_t destination_length = (socklen_t)sizeof(struct sockaddr); /* ##### Audio reader parameters ##### */ // Some more variables that we'll need for reading audio files int sample_rate, sample_size, channels; int write_init_audio = 0; /* ##### Timeout parameters ##### */ int nb; fd_set watch_over; struct timeval timeout; /* ##### Filter parameters ##### */ // For volume filter int volume_value; // For echo filter int nb_buffers_per_echo = 0, nb_samples_per_buffer, current_buffer_position, to_read_position; char* echo_buffer; char volume_buffer[BUFFER_SIZE]; /* ################################################## Sending the filename ################################################## */ // The first packet to send is the filename create_packet(&to_server, P_FILENAME, args[2]); // Send the packet containing the filename if (sendto(client_socket, &to_server, sizeof(struct packet), 0, (struct sockaddr*)&destination, destination_length) == -1) { perror("Error during the sending of the filename packet"); return 1; } /* ################################################## Talk with the server ################################################## */ do { // Clear and reinitialize the fd set FD_ZERO(&watch_over); FD_SET(client_socket, &watch_over); timeout.tv_sec = 0; timeout.tv_usec = TIMEOUT_CLIENT; // 200ms nb = select(client_socket+1, &watch_over, NULL, NULL, &timeout); // Clear packets clear_packet(&to_server); clear_packet(&from_server); // If error during the select if (nb < 0) { perror("Can't attach the select to the file descriptor"); return 1; } // Just request the same packet if timeout reached if (nb == 0) { to_server.type = P_REQ_SAME_PACKET; if (sendto(client_socket, &to_server, sizeof(struct packet), 0, (struct sockaddr*)&destination, destination_length) == -1) { perror("Can't request same packet"); return 1; } } // If open, just act normally if (FD_ISSET(client_socket, &watch_over)) { // Wait a packet if (recvfrom(client_socket, &from_server, sizeof(struct packet), 0, (struct sockaddr*)&destination, &destination_length) != -1) { // In function of the type of the packet received switch (from_server.type) { // --------------- An server error happened on the server --------------- case P_ERR_TRANSMISSION: case P_SERVER_ERROR: // Display the error printf("%s\n", from_server.message); // Close connection close_connection(client_socket, "Closing due to server error", 0); break; // --------------- The first response from the server is received --------------- case P_FILE_HEADER: // Get the informations about the audio file sample_rate = *((int*)(from_server.message)); sample_size = *((int*)(from_server.message + BUFFER_SPACE)); channels = *((int*)(from_server.message + 2*BUFFER_SPACE)); // ----- Filters initialisation ----- switch (filter) { // If none do nothing case F_NONE: break; // If mono, just force the channel to one case F_MONO: channels = 1; break; // If volume, get the value of the filter parameter case F_VOLUME: volume_value = atoi(args[4]); nb_samples_per_buffer = BUFFER_SIZE/(sample_size/8); break; // If echo, allocate the echo buffer case F_ECHO: // Calculate the number of bytes needed for one second nb_buffers_per_echo = (ECHO_IN_SCDS * sample_rate * (sample_size/8)) / BUFFER_SIZE; // Allocate the table of buffers echo_buffer = malloc(nb_buffers_per_echo * BUFFER_SIZE); // The buffer position and the buffer to read put to 0 current_buffer_position = 0; to_read_position = 0; break; // If speed case F_SPEED: // Multiply the framerate sample_rate = sample_rate * atoi(args[4]); break; // If unknown default: close_connection(client_socket, "Unknown filter", write_init_audio); break; } // Initialize the write end write_init_audio = aud_writeinit(sample_rate, sample_size, channels); // If an error happened if (write_init_audio < 1) { // If echo filter, free the buffer if (filter == F_ECHO) free(echo_buffer); // Close the connection close_connection(client_socket, "Error at getting the audio output device", 0); } // If everything's ok, request the first block clear_packet(&to_server); to_server.type = P_REQ_NEXT_BLOCK; // Send the request if (sendto(client_socket, &to_server, sizeof(struct packet), 0, (struct sockaddr*)&destination, destination_length) == -1) { // If echo filter, free the buffer if (filter == F_ECHO) free(echo_buffer); // Close the connection close_connection(client_socket, "Error at requesting the first block", write_init_audio); } break; // --------------- A block is received, read it --------------- case P_BLOCK: // Read the music on the audio output (in function of the filter passed) switch (filter) { // If none, mono or speed case F_NONE: case F_MONO: case F_SPEED: if (write(write_init_audio, from_server.message, BUFFER_SIZE) == -1) close_connection(client_socket, "Error at writing a block on audio output", write_init_audio); break; // If echo case F_ECHO: // Read the content of the buffer received if (write(write_init_audio, from_server.message, BUFFER_SIZE) == -1) { // Echo filter so free the buffer free(echo_buffer); // Close connection close_connection(client_socket, "Error at writing a block on audio output", write_init_audio); } // Then put this buffer into the echo buffer if the buffer isn't full if (current_buffer_position < nb_buffers_per_echo) { memcpy((echo_buffer + current_buffer_position*BUFFER_SIZE), from_server.message, BUFFER_SIZE); ++current_buffer_position; } // If the echo buffer is full else { // Read the current buffer position if (write(write_init_audio, (echo_buffer + to_read_position*BUFFER_SIZE), BUFFER_SIZE) == -1) { // Echo filter so free the buffer free(echo_buffer); // Close connection close_connection(client_socket, "Error at writing an echo block on audio output", write_init_audio); } // And replace it with the new one memcpy((echo_buffer + to_read_position*BUFFER_SIZE), from_server.message, BUFFER_SIZE); // Increment the flag to_read_position = (to_read_position+1)%nb_buffers_per_echo; } break; // If upper or lower volume case F_VOLUME: // Clear the temporary buffer memset(volume_buffer, 0, BUFFER_SIZE); // Variables used in the loop int i; // The increment var and a temporary value int tmp; // Temporary var // Get each sample and multiply its value for (i = 0; i < nb_samples_per_buffer; ++i) { // Multiply the value of the sample, get a double value tmp = *((int*)(from_server.message + i*sizeof(int))) * volume_value; // Then store it in the temporary buffer *((int*)(volume_buffer + i*sizeof(int))) = tmp; } // And in the end, read the whole buffer if (write(write_init_audio, volume_buffer, BUFFER_SIZE) == -1) close_connection(client_socket, "Error at writing a volume changed block on audio output", write_init_audio); break; // If an unknown filter, error! default: close_connection(client_socket, "Filter passed unknown", write_init_audio); break; } // End of filter's switch // If everything's ok, request the next block clear_packet(&to_server); to_server.type = P_REQ_NEXT_BLOCK; // Send the request if (sendto(client_socket, &to_server, sizeof(struct packet), 0, (struct sockaddr*)&destination, destination_length) == -1) { // If echo filter, free the buffer if (filter == F_ECHO) free(echo_buffer); // Close connection close_connection(client_socket, "Error at requesting a block", write_init_audio); } break; // --------------- The last block is received, read it --------------- case P_EOF: // Read the music on the audio output (in function of the filter passed) switch (filter) { // If none, mono or speed case F_NONE: case F_MONO: case F_SPEED: if (write(write_init_audio, from_server.message, BUFFER_SIZE) == -1) close_connection(client_socket, "Error at writing a block on audio output", write_init_audio); break; // If echo case F_ECHO: // Read the content of the buffer received if (write(write_init_audio, from_server.message, BUFFER_SIZE) == -1) { // Echo filter so free the buffer free(echo_buffer); // Close connection close_connection(client_socket, "Error at writing a block on audio output", write_init_audio); } // And in the end, just read the whole echo buffer left if (write(write_init_audio, (echo_buffer + to_read_position*BUFFER_SIZE), ((current_buffer_position - to_read_position)*BUFFER_SIZE)) == -1) { // Echo filter so free the buffer free(echo_buffer); // Close connection close_connection(client_socket, "Error at writing the last echo block on audio output", write_init_audio); } // Free the echo_buffer in the end free(echo_buffer); break; // If upper or lower volume case F_VOLUME: // Clear the temporary buffer memset(volume_buffer, 0, BUFFER_SIZE); // Variables used in the loop int i; // The increment var and a temporary value int tmp; // Temporary var // Get each sample and multiply its value for (i = 0; i < nb_samples_per_buffer; ++i) { // Multiply the value of the sample, get a double value tmp = *((int*)(from_server.message + i*sizeof(int))) * volume_value; // Then store it in the temporary buffer *((int*)(volume_buffer + i*sizeof(int))) = tmp; } // And in the end, read the whole buffer if (write(write_init_audio, volume_buffer, BUFFER_SIZE) == -1) close_connection(client_socket, "Error at writing a volume changed block on audio output", write_init_audio); break; // If an unknown filter, error! default: close_connection(client_socket, "Filter passed unknown", write_init_audio); break; } // If everything's ok, send the last packet clear_packet(&to_server); // Close the connection close_connection(client_socket, "The file was correctly read, close the connection, bye", write_init_audio); break; // --------------- Unknown type --------------- default: close_connection(client_socket, "Packet type unknown", write_init_audio); break; } } } // If an error during the receiving of a packet else { // If echo filter, free the buffer (only if it has been initialized) if ((filter == F_ECHO) && (nb_buffers_per_echo > 0)) free(echo_buffer); // Close connection perror("Error during the receiving of a packet, the server may be busy"); return 0; } } while (from_server.type != P_CLOSE_TRANSMISSION); // Close the connection close_connection(client_socket, "The reading is done, close connection now", write_init_audio); // If everything's was ok (but the server is normally just waiting for clients) return 0; }