int main(int argc, char **argv) { struct option long_options[] = { // These options don't set a flag {"help", no_argument, NULL, 'h'}, {"alternate", no_argument, NULL, 'A'}, {"effective", required_argument, NULL, 'f'}, {"duration", required_argument, NULL, 'd'}, {"initial-size", required_argument, NULL, 'i'}, {"num-threads", required_argument, NULL, 't'}, {"range", required_argument, NULL, 'r'}, {"seed", required_argument, NULL, 'S'}, {"update-rate", required_argument, NULL, 'u'}, {"move-rate", required_argument, NULL, 'a'}, {"snapshot-rate", required_argument, NULL, 's'}, {"lock-alg", required_argument, NULL, 'x'}, {NULL, 0, NULL, 0} }; ht_intset_t *set; int i, c, size; val_t last = 0; val_t val = 0; unsigned long reads, effreads, updates, effupds, moves, moved, snapshots, snapshoted, aborts, aborts_locked_read, aborts_locked_write, aborts_validate_read, aborts_validate_write, aborts_validate_commit, aborts_invalid_memory, max_retries; thread_data_t *data; pthread_t *threads; pthread_attr_t attr; barrier_t barrier; struct timeval start, end; struct timespec timeout; int duration = DEFAULT_DURATION; int initial = DEFAULT_INITIAL; int nb_threads = DEFAULT_NB_THREADS; long range = DEFAULT_RANGE; int seed = DEFAULT_SEED; int update = DEFAULT_UPDATE; int load_factor = DEFAULT_LOAD; int move = DEFAULT_MOVE; int snapshot = DEFAULT_SNAPSHOT; int unit_tx = DEFAULT_ELASTICITY; int alternate = DEFAULT_ALTERNATE; int effective = DEFAULT_EFFECTIVE; sigset_t block_set; while(1) { i = 0; c = getopt_long(argc, argv, "hAf:d:i:t:r:S:u:a:s:l:x:", long_options, &i); if(c == -1) break; if(c == 0 && long_options[i].flag == 0) c = long_options[i].val; switch(c) { case 0: /* Flag is automatically set */ break; case 'h': printf("intset -- STM stress test " "(linked list)\n" "\n" "Usage:\n" " intset [options...]\n" "\n" "Options:\n" " -h, --help\n" " Print this message\n" " -A, --Alternate\n" " Consecutive insert/remove target the same value\n" " -f, --effective <int>\n" " update txs must effectively write (0=trial, 1=effective, default=" XSTR(DEFAULT_EFFECTIVE) ")\n" " -d, --duration <int>\n" " Test duration in milliseconds (0=infinite, default=" XSTR(DEFAULT_DURATION) ")\n" " -i, --initial-size <int>\n" " Number of elements to insert before test (default=" XSTR(DEFAULT_INITIAL) ")\n" " -t, --thread-num <int>\n" " Number of threads (default=" XSTR(DEFAULT_NB_THREADS) ")\n" " -r, --range <int>\n" " Range of integer values inserted in set (default=" XSTR(DEFAULT_RANGE) ")\n" " -S, --seed <int>\n" " RNG seed (0=time-based, default=" XSTR(DEFAULT_SEED) ")\n" " -u, --update-rate <int>\n" " Percentage of update transactions (default=" XSTR(DEFAULT_UPDATE) ")\n" " -a , --move-rate <int>\n" " Percentage of move transactions (default=" XSTR(DEFAULT_MOVE) ")\n" " -s , --snapshot-rate <int>\n" " Percentage of snapshot transactions (default=" XSTR(DEFAULT_SNAPSHOT) ")\n" " -l , --load-factor <int>\n" " Ratio of keys over buckets (default=" XSTR(DEFAULT_LOAD) ")\n" " -x, --unit-tx (default=1)\n" " Use unit transactions\n" " 0 = non-protected,\n" " 1 = normal transaction,\n" " 2 = read unit-tx,\n" " 3 = read/add unit-tx,\n" " 4 = read/add/rem unit-tx,\n" " 5 = all recursive unit-tx,\n" " 6 = harris lock-free\n" ); exit(0); case 'A': alternate = 1; break; case 'f': effective = atoi(optarg); break; case 'd': duration = atoi(optarg); break; case 'i': initial = atoi(optarg); break; case 't': nb_threads = atoi(optarg); break; case 'r': range = atol(optarg); break; case 'S': seed = atoi(optarg); break; case 'u': update = atoi(optarg); break; case 'a': move = atoi(optarg); break; case 's': snapshot = atoi(optarg); break; case 'l': load_factor = atoi(optarg); break; case 'x': unit_tx = atoi(optarg); break; case '?': printf("Use -h or --help for help\n"); exit(0); default: exit(1); } } assert(duration >= 0); assert(initial >= 0); assert(nb_threads > 0); assert(range > 0 && range >= initial); assert(update >= 0 && update <= 100); assert(move >= 0 && move <= update); assert(snapshot >= 0 && snapshot <= (100-update)); assert(load_factor >= 1); printf("Set type : hash table\n"); printf("Duration : %d\n", duration); printf("Initial size : %d\n", initial); printf("Nb threads : %d\n", nb_threads); printf("Value range : %ld\n", range); printf("Seed : %d\n", seed); printf("Update rate : %d\n", update); printf("Load factor : %d\n", load_factor); printf("Move rate : %d\n", move); printf("Update rate : %d\n", update); printf("Lock alg. : %d\n", unit_tx); printf("Alternate : %d\n", alternate); printf("effective : %d\n", effective); printf("Type sizes : int=%d/long=%d/ptr=%d/word=%d\n", (int)sizeof(int), (int)sizeof(long), (int)sizeof(void *), (int)sizeof(uintptr_t)); timeout.tv_sec = duration / 1000; timeout.tv_nsec = (duration % 1000) * 1000000; if ((data = (thread_data_t *)malloc(nb_threads * sizeof(thread_data_t))) == NULL) { perror("malloc"); exit(1); } if ((threads = (pthread_t *)malloc(nb_threads * sizeof(pthread_t))) == NULL) { perror("malloc"); exit(1); } if (seed == 0) srand((int)time(0)); else srand(seed); maxhtlength = (unsigned int) initial / load_factor; set = ht_new(); stop = 0; /* Populate set */ printf("Adding %d entries to set\n", initial); i = 0; //maxhtlength = (int) (initial / load_factor); while (i < initial) { val = (rand() % range) + 1; if (ht_add(set, val, 0)) { last = val; i++; } } size = ht_size(set); printf("Set size : %d\n", size); printf("Bucket amount: %d\n", maxhtlength); printf("Load : %d\n", load_factor); /* Access set from all threads */ barrier_init(&barrier, nb_threads + 1); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < nb_threads; i++) { printf("Creating thread %d\n", i); data[i].first = last; data[i].range = range; data[i].update = update; data[i].load_factor = load_factor; data[i].move = move; data[i].snapshot = snapshot; data[i].unit_tx = unit_tx; data[i].alternate = alternate; data[i].effective = effective; data[i].nb_add = 0; data[i].nb_added = 0; data[i].nb_remove = 0; data[i].nb_removed = 0; data[i].nb_move = 0; data[i].nb_moved = 0; data[i].nb_snapshot = 0; data[i].nb_snapshoted = 0; data[i].nb_contains = 0; data[i].nb_found = 0; data[i].nb_aborts = 0; data[i].nb_aborts_locked_read = 0; data[i].nb_aborts_locked_write = 0; data[i].nb_aborts_validate_read = 0; data[i].nb_aborts_validate_write = 0; data[i].nb_aborts_validate_commit = 0; data[i].nb_aborts_invalid_memory = 0; data[i].max_retries = 0; data[i].seed = rand(); data[i].set = set; data[i].barrier = &barrier; if (pthread_create(&threads[i], &attr, test, (void *)(&data[i])) != 0) { fprintf(stderr, "Error creating thread\n"); exit(1); } } pthread_attr_destroy(&attr); /* Start threads */ barrier_cross(&barrier); printf("STARTING...\n"); gettimeofday(&start, NULL); if (duration > 0) { nanosleep(&timeout, NULL); } else { sigemptyset(&block_set); sigsuspend(&block_set); } AO_store_full(&stop, 1); gettimeofday(&end, NULL); printf("STOPPING...\n"); /* Wait for thread completion */ for (i = 0; i < nb_threads; i++) { if (pthread_join(threads[i], NULL) != 0) { fprintf(stderr, "Error waiting for thread completion\n"); exit(1); } } duration = (end.tv_sec * 1000 + end.tv_usec / 1000) - (start.tv_sec * 1000 + start.tv_usec / 1000); aborts = 0; aborts_locked_read = 0; aborts_locked_write = 0; aborts_validate_read = 0; aborts_validate_write = 0; aborts_validate_commit = 0; aborts_invalid_memory = 0; reads = 0; effreads = 0; updates = 0; effupds = 0; moves = 0; moved = 0; snapshots = 0; snapshoted = 0; max_retries = 0; for (i = 0; i < nb_threads; i++) { printf("Thread %d\n", i); printf(" #add : %lu\n", data[i].nb_add); printf(" #added : %lu\n", data[i].nb_added); printf(" #remove : %lu\n", data[i].nb_remove); printf(" #removed : %lu\n", data[i].nb_removed); printf(" #contains : %lu\n", data[i].nb_contains); printf(" #found : %lu\n", data[i].nb_found); printf(" #move : %lu\n", data[i].nb_move); printf(" #moved : %lu\n", data[i].nb_moved); printf(" #snapshot : %lu\n", data[i].nb_snapshot); printf(" #snapshoted : %lu\n", data[i].nb_snapshoted); printf(" #aborts : %lu\n", data[i].nb_aborts); printf(" #lock-r : %lu\n", data[i].nb_aborts_locked_read); printf(" #lock-w : %lu\n", data[i].nb_aborts_locked_write); printf(" #val-r : %lu\n", data[i].nb_aborts_validate_read); printf(" #val-w : %lu\n", data[i].nb_aborts_validate_write); printf(" #val-c : %lu\n", data[i].nb_aborts_validate_commit); printf(" #inv-mem : %lu\n", data[i].nb_aborts_invalid_memory); printf(" Max retries : %lu\n", data[i].max_retries); aborts += data[i].nb_aborts; aborts_locked_read += data[i].nb_aborts_locked_read; aborts_locked_write += data[i].nb_aborts_locked_write; aborts_validate_read += data[i].nb_aborts_validate_read; aborts_validate_write += data[i].nb_aborts_validate_write; aborts_validate_commit += data[i].nb_aborts_validate_commit; aborts_invalid_memory += data[i].nb_aborts_invalid_memory; reads += data[i].nb_contains; effreads += data[i].nb_contains + (data[i].nb_add - data[i].nb_added) + (data[i].nb_remove - data[i].nb_removed) + (data[i].nb_move - data[i].nb_moved) + data[i].nb_snapshoted; updates += (data[i].nb_add + data[i].nb_remove); effupds += data[i].nb_removed + data[i].nb_added + data[i].nb_moved; moves += data[i].nb_move; moved += data[i].nb_moved; snapshots += data[i].nb_snapshot; snapshoted += data[i].nb_snapshoted; size += data[i].nb_added - data[i].nb_removed; if (max_retries < data[i].max_retries) max_retries = data[i].max_retries; } printf("Set size : %d (expected: %d)\n", ht_size(set), size); printf("Duration : %d (ms)\n", duration); printf("#txs : %lu (%f / s)\n", reads + updates + moves + snapshots , (reads + updates + moves + snapshots) * 1000.0 / duration); printf("#read txs : "); if (effective) { printf("%lu (%f / s)\n", effreads, effreads * 1000.0 / duration); printf(" #contains : %lu (%f / s)\n", reads, reads * 1000.0 / duration); } else printf("%lu (%f / s)\n", reads, reads * 1000.0 / duration); printf("#eff. upd rate: %f \n", 100.0 * effupds / (effupds + effreads)); printf("#update txs : "); if (effective) { printf("%lu (%f / s)\n", effupds, effupds * 1000.0 / duration); printf(" #upd trials : %lu (%f / s)\n", updates, updates * 1000.0 / duration); } else printf("%lu (%f / s)\n", updates, updates * 1000.0 / duration); printf("#move txs : %lu (%f / s)\n", moves, moves * 1000.0 / duration); printf(" #moved : %lu (%f / s)\n", moved, moved * 1000.0 / duration); printf("#snapshot txs : %lu (%f / s)\n", snapshots, snapshots * 1000.0 / duration); printf(" #snapshoted : %lu (%f / s)\n", snapshoted, snapshoted * 1000.0 / duration); printf("#aborts : %lu (%f / s)\n", aborts, aborts * 1000.0 / duration); printf(" #lock-r : %lu (%f / s)\n", aborts_locked_read, aborts_locked_read * 1000.0 / duration); printf(" #lock-w : %lu (%f / s)\n", aborts_locked_write, aborts_locked_write * 1000.0 / duration); printf(" #val-r : %lu (%f / s)\n", aborts_validate_read, aborts_validate_read * 1000.0 / duration); printf(" #val-w : %lu (%f / s)\n", aborts_validate_write, aborts_validate_write * 1000.0 / duration); printf(" #val-c : %lu (%f / s)\n", aborts_validate_commit, aborts_validate_commit * 1000.0 / duration); printf(" #inv-mem : %lu (%f / s)\n", aborts_invalid_memory, aborts_invalid_memory * 1000.0 / duration); printf("Max retries : %lu\n", max_retries); /* Delete set */ ht_delete(set); free(threads); free(data); return 0; }
fapi::ReturnCode fapiDelay(uint64_t i_nanoSeconds, uint64_t i_simCycles) { FAPI_DBG( INFO_MRK "delay %lld nanosec", i_nanoSeconds ); nanosleep( 0, i_nanoSeconds ); return fapi::FAPI_RC_SUCCESS; }
/* like any C program, program's execution begins in main */ int main(int argc, char* argv[]) { int i; /* loop counter */ struct timespec delay; /* used for wasting time */ struct requests_queue* requests = NULL; /* pointer to requests queue */ struct handler_threads_pool* handler_threads = NULL; /* list of handler threads */ /* create the requests queue */ requests = init_requests_queue(&request_mutex, &got_request); assert(requests); /* create the handler threads list */ handler_threads = init_handler_threads_pool(&request_mutex, &got_request, requests); assert(handler_threads); /* create the request-handling threads */ for (i=0; i<NUM_HANDLER_THREADS; i++) { add_handler_thread(handler_threads); } /* run a loop that generates requests */ for (i=0; i<600; i++) { int num_requests; // number of requests waiting to be handled. int num_threads; // number of active handler threads. add_request(requests, i); num_requests = get_requests_number(requests); num_threads = get_handler_threads_number(handler_threads); /* if there are too many requests on the queue, spawn new threads */ /* if there are few requests and too many handler threads, cancel */ /* a handler thread. */ if (num_requests > HIGH_REQUESTS_WATERMARK && num_threads < MAX_NUM_HANDLER_THREADS) { printf("main: adding thread: '%d' requests, '%d' threads\n", num_requests, num_threads); add_handler_thread(handler_threads); } if (num_requests < LOW_REQUESTS_WATERMARK && num_threads > NUM_HANDLER_THREADS) { printf("main: deleting thread: '%d' requests, '%d' threads\n", num_requests, num_threads); delete_handler_thread(handler_threads); } /* pause execution for a little bit, to allow */ /* other threads to run and handle some requests. */ if (rand() > 3*(RAND_MAX/4)) { /* this is done about 25% of the time */ delay.tv_sec = 0; delay.tv_nsec = 1; nanosleep(&delay, NULL); } } /* modify the flag to tell the handler threads no */ /* new requests will be generated. */ { int rc; rc = pthread_mutex_lock(&request_mutex); done_creating_requests = 1; rc = pthread_cond_broadcast(&got_request); rc = pthread_mutex_unlock(&request_mutex); } /* cleanup */ delete_handler_threads_pool(handler_threads); delete_requests_queue(requests); printf("Glory, we are done.\n"); return 0; }
static void delay(struct timespec time) { nanosleep(&time, NULL); }
int main(int argc, char **argv) { char byte='a'; struct timespec tp= {0, 100}; int count=0; foo_caddy_t *foo; /* Initialize the event library */ opal_init(&argc, &argv); /* setup for threads */ opal_event_use_threads(); /* create a new base */ my_base = orte_event_base_create(); /* launch a progress thread on that base*/ pipe(progress_thread_pipe); OBJ_CONSTRUCT(&lock, opal_mutex_t); OBJ_CONSTRUCT(&cond, opal_condition_t); OBJ_CONSTRUCT(&progress_thread, opal_thread_t); progress_thread.t_run = progress_engine; if (OPAL_SUCCESS != opal_thread_start(&progress_thread)) { fprintf(stderr, "Unable to start progress thread\n"); orte_event_base_finalize(my_base); exit(1); } /* wait a little while - reflects reality in an async system */ while (count < 100) { nanosleep(&tp, NULL); count++; } count=0; /* make a dummy event */ fprintf(stderr, "activating the write_event"); foo = OBJ_NEW(foo_caddy_t); opal_event_set(my_base, &foo->write_event, -1, 0, send_handler, foo); /* activate it. */ opal_event_active(&foo->write_event, EV_WRITE, 1); /* wait for it to trigger */ while (!fd_written && count < 1000) { if (0 == (count % 100)) { fprintf(stderr, "Waiting...\n"); } nanosleep(&tp, NULL); count++; } /* stop the thread */ OPAL_ACQUIRE_THREAD(&lock, &cond, &active); progress_thread_stop = true; OPAL_RELEASE_THREAD(&lock, &cond, &active); opal_fd_write(progress_thread_pipe[1], 1, &byte); opal_thread_join(&progress_thread, NULL); /* release the base */ fprintf(stderr, "Cleaning up\n"); opal_finalize(); fprintf(stderr, "Cleanup completed\n"); return 0; }
/** * Initialisation of the Aptina MT9V117 CMOS sensor * (1/6 inch VGA, bottom camera) */ void mt9v117_init(void) { struct timespec tim; char test[2]; /* Start PWM 9 (Which probably is the clock of the MT9V117) */ int pwm9 = open("/sys/class/pwm/pwm_9/run", O_WRONLY | O_CREAT | O_TRUNC, 0666); write(pwm9, "0", 1); write(pwm9, "1", 1); close(pwm9); tim.tv_sec = 0; tim.tv_nsec = 50000000; nanosleep(&tim, NULL); /* We open the i2c-0 (because else I needed to convert the strace) */ int fd_i2c = open("/dev/i2c-0", O_RDWR); if (fd_i2c < 0) { printf("[MT9V117] Could not open i2c-0\n"); return; } if (ioctl(fd_i2c, 0x703, 0x5d) < 0) { printf("[MT9V117] Could not change the i2c address to 0x5d\n"); return; } /* First reset the device */ write_reg(fd_i2c, "\x00\x1a\x00\x01", 4); write_reg(fd_i2c, "\x00\x1a\x00\x00", 4); tim.tv_sec = 0; tim.tv_nsec = 100000000; nanosleep(&tim, NULL); /* Now initialize the device */ write_reg(fd_i2c, "\x30\x1a\x10\xd0", 4); write_reg(fd_i2c, "\x31\xc0\x14\x04", 4); write_reg(fd_i2c, "\x3e\xd8\x87\x9c", 4); write_reg(fd_i2c, "\x30\x42\x20\xe1", 4); write_reg(fd_i2c, "\x30\xd4\x80\x20", 4); write_reg(fd_i2c, "\x30\xc0\x00\x26", 4); write_reg(fd_i2c, "\x30\x1a\x10\xd4", 4); write_reg(fd_i2c, "\xa8\x02\x00\xd3", 4); write_reg(fd_i2c, "\xc8\x78\x00\xa0", 4); write_reg(fd_i2c, "\xc8\x76\x01\x40", 4); write_reg(fd_i2c, "\xbc\x04\x00\xfc", 4); write_reg(fd_i2c, "\xbc\x38\x00\x7f", 4); write_reg(fd_i2c, "\xbc\x3a\x00\x7f", 4); write_reg(fd_i2c, "\xbc\x3c\x00\x7f", 4); write_reg(fd_i2c, "\xbc\x04\x00\xf4", 4); _write(fd_i2c, "\x09\x82\x00\x01", 4); _write(fd_i2c, "\x09\x8a\x70\x00", 4); _write(fd_i2c, "\xf0\x00\x72\xcf\xff\x00\x3e\xd0\x92\x00\x71\xcf\xff\xff\xf2\x18\xb1\x10\x92\x05\xb1\x11\x92\x04\xb1\x12\x70\xcf\xff\x00\x30\xc0\x90\x00\x7f\xe0\xb1\x13\x70\xcf\xff\xff\xe7\x1c\x88\x36\x09\x0f\x00\xb3", 50); _write(fd_i2c, "\xf0\x30\x69\x13\xe1\x80\xd8\x08\x20\xca\x03\x22\x71\xcf\xff\xff\xe5\x68\x91\x35\x22\x0a\x1f\x80\xff\xff\xf2\x18\x29\x05\x00\x3e\x12\x22\x11\x01\x21\x04\x0f\x81\x00\x00\xff\xf0\x21\x8c\xf0\x10\x1a\x22", 50); _write(fd_i2c, "\xf0\x60\x10\x44\x12\x20\x11\x02\xf7\x87\x22\x4f\x03\x83\x1a\x20\x10\xc4\xf0\x09\xba\xae\x7b\x50\x1a\x20\x10\x84\x21\x45\x01\xc1\x1a\x22\x10\x44\x70\xcf\xff\x00\x3e\xd0\xb0\x60\xb0\x25\x7e\xe0\x78\xe0", 50); _write(fd_i2c, "\xf0\x90\x71\xcf\xff\xff\xf2\x18\x91\x12\x72\xcf\xff\xff\xe7\x1c\x8a\x57\x20\x04\x0f\x80\x00\x00\xff\xf0\xe2\x80\x20\xc5\x01\x61\x20\xc5\x03\x22\xb1\x12\x71\xcf\xff\x00\x3e\xd0\xb1\x04\x7e\xe0\x78\xe0", 50); _write(fd_i2c, "\xf0\xc0\x70\xcf\xff\xff\xe7\x1c\x88\x57\x71\xcf\xff\xff\xf2\x18\x91\x13\xea\x84\xb8\xa9\x78\x10\xf0\x03\xb8\x89\xb8\x8c\xb1\x13\x71\xcf\xff\x00\x30\xc0\xb1\x00\x7e\xe0\xc0\xf1\x09\x1e\x03\xc0\xc1\xa1", 50); _write(fd_i2c, "\xf0\xf0\x75\x08\x76\x28\x77\x48\xc2\x40\xd8\x20\x71\xcf\x00\x03\x20\x67\xda\x02\x08\xae\x03\xa0\x73\xc9\x0e\x25\x13\xc0\x0b\x5e\x01\x60\xd8\x06\xff\xbc\x0c\xce\x01\x00\xd8\x00\xb8\x9e\x0e\x5a\x03\x20", 50); _write(fd_i2c, "\xf1\x20\xd9\x01\xd8\x00\xb8\x9e\x0e\xb6\x03\x20\xd9\x01\x8d\x14\x08\x17\x01\x91\x8d\x16\xe8\x07\x0b\x36\x01\x60\xd8\x07\x0b\x52\x01\x60\xd8\x11\x8d\x14\xe0\x87\xd8\x00\x20\xca\x02\x62\x00\xc9\x03\xe0", 50); _write(fd_i2c, "\xf1\x50\xc0\xa1\x78\xe0\xc0\xf1\x08\xb2\x03\xc0\x76\xcf\xff\xff\xe5\x40\x75\xcf\xff\xff\xe5\x68\x95\x17\x96\x40\x77\xcf\xff\xff\xe5\x42\x95\x38\x0a\x0d\x00\x01\x97\x40\x0a\x11\x00\x40\x0b\x0a\x01\x00", 50); _write(fd_i2c, "\xf1\x80\x95\x17\xb6\x00\x95\x18\xb7\x00\x76\xcf\xff\xff\xe5\x44\x96\x20\x95\x15\x08\x13\x00\x40\x0e\x1e\x01\x20\xd9\x00\x95\x15\xb6\x00\xff\xa1\x75\xcf\xff\xff\xe7\x1c\x77\xcf\xff\xff\xe5\x46\x97\x40", 50); _write(fd_i2c, "\xf1\xb0\x8d\x16\x76\xcf\xff\xff\xe5\x48\x8d\x37\x08\x0d\x00\x81\x96\x40\x09\x15\x00\x80\x0f\xd6\x01\x00\x8d\x16\xb7\x00\x8d\x17\xb6\x00\xff\xb0\xff\xbc\x00\x41\x03\xc0\xc0\xf1\x0d\x9e\x01\x00\xe8\x04", 50); _write(fd_i2c, "\xf1\xe0\xff\x88\xf0\x0a\x0d\x6a\x01\x00\x0d\x8e\x01\x00\xe8\x7e\xff\x85\x0d\x72\x01\x00\xff\x8c\xff\xa7\xff\xb2\xd8\x00\x73\xcf\xff\xff\xf2\x40\x23\x15\x00\x01\x81\x41\xe0\x02\x81\x20\x08\xf7\x81\x34", 50); _write(fd_i2c, "\xf2\x10\xa1\x40\xd8\x00\xc0\xd1\x7e\xe0\x53\x51\x30\x34\x20\x6f\x6e\x5f\x73\x74\x61\x72\x74\x5f\x73\x74\x72\x65\x61\x6d\x69\x6e\x67\x20\x25\x64\x20\x25\x64\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 50); _write(fd_i2c, "\xf2\x40\xff\xff\xe8\x28\xff\xff\xf0\xe8\xff\xff\xe8\x08\xff\xff\xf1\x54", 18); _write(fd_i2c, "\x09\x8e\x00\x00", 4); _write(fd_i2c, "\xe0\x00\x05\xd8", 4); _write(fd_i2c, "\xe0\x02\x04\x03", 4); _write(fd_i2c, "\xe0\x04\x00\x43\x01\x04", 6); // Do while succeeded? _write(fd_i2c, "\x00\x40\x80\x01", 4); while (test[0] != 0xFF || test[1] != 0XF8) { tim.tv_sec = 0; tim.tv_nsec = 100000000; nanosleep(&tim, NULL); write(fd_i2c, "\x00\x40", 2); read(fd_i2c, test, 2); printf("Da: %X%X\n", test[0], test[1]); /*if(test[1] == 0XFB) { // restart all over?? mt9v117_init(); return; }*/ } _write(fd_i2c, "\xac\x40\x00\x00\xc3\x50", 6); write_reg(fd_i2c, "\xa4\x04\x00\x00", 4); //write(fd_i2c, "\x00\x30", 2); //read(fd_i2c, "\x04\x00", 2); write_reg(fd_i2c, "\x00\x30\x06\x01", 4); write_reg(fd_i2c, "\xc8\x00\x00\x0c", 4); //0x0008 write_reg(fd_i2c, "\xc8\x02\x00\x10", 4); write_reg(fd_i2c, "\xc8\x04\x01\xf3", 4); //0x01f5 write_reg(fd_i2c, "\xc8\x06\x02\x97", 4); write_reg(fd_i2c, "\xc8\x08\x01\x11", 4); write_reg(fd_i2c, "\xc8\x0a\x00\xa4", 4); write_reg(fd_i2c, "\xc8\x0c\x02\xfa", 4); write_reg(fd_i2c, "\xc8\x12\x00\x31", 4); write_reg(fd_i2c, "\xc8\x14\x01\xe3", 4); //0x00f3 write_reg(fd_i2c, "\xc8\x28\x00\x03", 4); //0x0007 write_reg(fd_i2c, "\xc8\x4c\x02\x80", 4); write_reg(fd_i2c, "\xc8\x4e\x01\xe0", 4); //240 (0x00f0) write_reg(fd_i2c, "\xc8\x50\x03", 3); write_reg(fd_i2c, "\xc8\x54\x02\x80", 4); //320 (0x0140) write_reg(fd_i2c, "\xc8\x56\x01\xe0", 4); //240 (0x00f0) write_reg(fd_i2c, "\xc8\xec\x00\x00", 4); write_reg(fd_i2c, "\xc8\xee\x00\x00", 4); write_reg(fd_i2c, "\xc8\xf0\x02\x7f", 4); //0x013f write_reg(fd_i2c, "\xc8\xf2\x01\xdf", 4); //0x00ef write_reg(fd_i2c, "\xc8\xf4\x00\x02", 4); write_reg(fd_i2c, "\xc8\xf6\x00\x02", 4); write_reg(fd_i2c, "\xc8\xf8\x00\x7f", 4); //0x003f write_reg(fd_i2c, "\xc8\xfa\x00\x5f", 4); //0x002f write_reg(fd_i2c, "\xc8\x10\x03\x52", 4); //0x0400 (0x045e??) write_reg(fd_i2c, "\xc8\x0e\x01\xff", 4); //0x0140 (0x0143??) write_reg(fd_i2c, "\xc8\x16\x00\xd4", 4); //0x00b0 (0x00a1??) write_reg(fd_i2c, "\xc8\x18\x00\xfe", 4); //0x00d3 (0x00c1??) write_reg(fd_i2c, "\xc8\x1a\x00\x01", 4); write_reg(fd_i2c, "\xc8\x1c\x00\x02", 4); //0x0001 write_reg(fd_i2c, "\xc8\x1e\x00\x01", 4); write_reg(fd_i2c, "\xc8\x20\x00\x02", 4); //0x0001 write(fd_i2c, "\xc8\x58", 2); read(fd_i2c, test, 2); write_reg(fd_i2c, "\xc8\x58\x00\x18", 4); write_reg(fd_i2c, "\xdc\x00\x28", 3); // Dow while succeeded? _write(fd_i2c, "\x00\x40\x80\x02", 4); test[0] = 0; test[1] = 0; while (test[0] != 0xFF || test[1] != 0XF8) { tim.tv_sec = 0; tim.tv_nsec = 100000000; nanosleep(&tim, NULL); write(fd_i2c, "\x00\x40", 2); read(fd_i2c, test, 2); printf("Dt: %X%X\n", test[0], test[1]); } printf("Done!\n"); close(fd_i2c); }
static void *consumer_thread( void *arg ) { // Identify the arg consumer_sdl self = arg; // Get the consumer mlt_consumer consumer = &self->parent; // Get the properties mlt_properties consumer_props = MLT_CONSUMER_PROPERTIES( consumer ); // Video thread pthread_t thread; // internal intialization int init_audio = 1; int init_video = 1; mlt_frame frame = NULL; mlt_properties properties = NULL; int duration = 0; int64_t playtime = 0; struct timespec tm = { 0, 100000 }; // int last_position = -1; pthread_mutex_lock( &self->refresh_mutex ); self->refresh_count = 0; pthread_mutex_unlock( &self->refresh_mutex ); // Loop until told not to while( self->running ) { // Get a frame from the attached producer frame = mlt_consumer_rt_frame( consumer ); // Ensure that we have a frame if ( frame ) { // Get the frame properties properties = MLT_FRAME_PROPERTIES( frame ); // Get the speed of the frame double speed = mlt_properties_get_double( properties, "_speed" ); // Get refresh request for the current frame int refresh = mlt_properties_get_int( consumer_props, "refresh" ); // Clear refresh mlt_events_block( consumer_props, consumer_props ); mlt_properties_set_int( consumer_props, "refresh", 0 ); mlt_events_unblock( consumer_props, consumer_props ); // Play audio init_audio = consumer_play_audio( self, frame, init_audio, &duration ); // Determine the start time now if ( self->playing && init_video ) { // Create the video thread pthread_create( &thread, NULL, video_thread, self ); // Video doesn't need to be initialised any more init_video = 0; } // Set playtime for this frame mlt_properties_set_int( properties, "playtime", playtime ); while ( self->running && speed != 0 && mlt_deque_count( self->queue ) > 15 ) nanosleep( &tm, NULL ); // Push this frame to the back of the queue if ( self->running && speed ) { pthread_mutex_lock( &self->video_mutex ); if ( self->is_purge && speed == 1.0 ) { mlt_frame_close( frame ); self->is_purge = 0; } else { mlt_deque_push_back( self->queue, frame ); pthread_cond_broadcast( &self->video_cond ); } pthread_mutex_unlock( &self->video_mutex ); // Calculate the next playtime playtime += ( duration * 1000 ); } else if ( self->running ) { pthread_mutex_lock( &self->refresh_mutex ); if ( ( refresh == 0 && self->refresh_count <= 0 ) || self->refresh_count > 1 ) { consumer_play_video( self, frame ); pthread_cond_wait( &self->refresh_cond, &self->refresh_mutex ); } mlt_frame_close( frame ); self->refresh_count --; pthread_mutex_unlock( &self->refresh_mutex ); } else { mlt_frame_close( frame ); frame = NULL; } // Optimisation to reduce latency if ( frame && speed == 1.0 ) { // TODO: disabled due to misbehavior on parallel-consumer // if ( last_position != -1 && last_position + 1 != mlt_frame_get_position( frame ) ) // mlt_consumer_purge( consumer ); // last_position = mlt_frame_get_position( frame ); } else { mlt_consumer_purge( consumer ); // last_position = -1; } } } // Kill the video thread if ( init_video == 0 ) { pthread_mutex_lock( &self->video_mutex ); pthread_cond_broadcast( &self->video_cond ); pthread_mutex_unlock( &self->video_mutex ); pthread_join( thread, NULL ); } while( mlt_deque_count( self->queue ) ) mlt_frame_close( mlt_deque_pop_back( self->queue ) ); self->audio_avail = 0; return NULL; }
/** Attempt to acquire a lock based on a lockfile, waiting LOCKPOLLINTERVAL milliseconds between polls and timing out after timeout seconds, thereafter forcibly attempting to obtain the lock if force is non-zero. Returns 1 on success, 0 on failure. To release the lock the lockfile must be unlinked. A unique temporary file named by appending characters to the lockfile name is used; any pre-existing file of the same name is subject to deletion. */ static int acquire_lock_file(const std::string &lockfile_str, const int timeout, int force) { int fd, timed_out = 0; int ret = 0; /* early exit returns failure */ struct timespec pollint; struct timeval start, end; double elapsed; struct stat statbuf; const char * const lockfile = lockfile_str.c_str(); /* (Re)create a unique file and check that it has one only link. */ const std::string linkfile_str = gen_unique_nfs_filename(lockfile); const char * const linkfile = linkfile_str.c_str(); (void)unlink(linkfile); /* OK to not use CLO_EXEC here because fishd is single threaded */ if ((fd = open(linkfile, O_CREAT|O_RDONLY, 0600)) == -1) { debug(1, L"acquire_lock_file: open: %s", strerror(errno)); goto done; } /* Don't need to check exit status of close on read-only file descriptors */ close(fd); if (stat(linkfile, &statbuf) != 0) { debug(1, L"acquire_lock_file: stat: %s", strerror(errno)); goto done; } if (statbuf.st_nlink != 1) { debug(1, L"acquire_lock_file: number of hardlinks on unique " L"tmpfile is %d instead of 1.", (int)statbuf.st_nlink); goto done; } if (gettimeofday(&start, NULL) != 0) { debug(1, L"acquire_lock_file: gettimeofday: %s", strerror(errno)); goto done; } end = start; pollint.tv_sec = 0; pollint.tv_nsec = LOCKPOLLINTERVAL * 1000000; do { /* Try to create a hard link to the unique file from the lockfile. This will only succeed if the lockfile does not already exist. It is guaranteed to provide race-free semantics over NFS which the alternative of calling open(O_EXCL|O_CREAT) on the lockfile is not. The lock succeeds if the call to link returns 0 or the link count on the unique file increases to 2. */ if (link(linkfile, lockfile) == 0 || (stat(linkfile, &statbuf) == 0 && statbuf.st_nlink == 2)) { /* Successful lock */ ret = 1; break; } elapsed = end.tv_sec + end.tv_usec/1000000.0 - (start.tv_sec + start.tv_usec/1000000.0); /* The check for elapsed < 0 is to deal with the unlikely event that after the loop is entered the system time is set forward past the loop's end time. This would otherwise result in a (practically) infinite loop. */ if (timed_out || elapsed >= timeout || elapsed < 0) { if (timed_out == 0 && force) { /* Timed out and force was specified - attempt to remove stale lock and try a final time */ (void)unlink(lockfile); timed_out = 1; continue; } else { /* Timed out and final try was unsuccessful or force was not specified */ debug(1, L"acquire_lock_file: timed out " L"trying to obtain lockfile %s using " L"linkfile %s", lockfile, linkfile); break; } } nanosleep(&pollint, NULL); } while (gettimeofday(&end, NULL) == 0); done: /* The linkfile is not needed once the lockfile has been created */ (void)unlink(linkfile); return ret; }
int main( int argc, char *argv[]) { int c = 0; int ret_val = 0; int port = 0; char network[128]; char *file = NULL; char *iface = NULL; char *mcast_addr = NULL; int bfd = 0; network[0] = '\0'; #ifdef UDPTEST int sockfd = 0; #else pgm_error_t* pgm_err = NULL; pgm_sock_t *pgm_sock; pthread_t nak_thread; #endif while((c = getopt(argc, argv, ":hm:i:p:f:")) != -1) { switch (c) { case 'm': mcast_addr = optarg; break; case 'i': iface = optarg; break; case 'p': port = atoi(optarg); break; case 'h': case '?': print_usage(); break; default: print_usage(); break; } } if(optind != argc-1) { PRINT_ERR("Please provide the path to a file you want to send!"); ret_val = -1; goto ret_error; } else { file = argv[optind]; } if (iface) { char *ifaddr = pftp_inet_iftoa(iface); if (strlen(ifaddr) > 0) { strncat(network, ifaddr, 128); strncat(network, ";", 128); } } if (mcast_addr) { strncat(network, mcast_addr, 128); } else { strncat(network, PFTP_DEFAULT_MCAST_ADDR, 128); } #ifdef UDPTEST struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(PFTP_DEFAULT_MCAST_ADDR); servaddr.sin_port = port ? htons(port) : htons(PFTP_UDP_PORT); #else if (0 != pftp_create(1, network, port, &pgm_sock)) { ret_val = -1; goto ret_error; } int pgm_status; /* Start NAK receiver thread */ m_run_receiver = 1; pthread_create(&nak_thread, NULL, nak_routine, (void*)pgm_sock); #endif char buf[PGMBUF_SIZE]; buf[0] = '\0'; struct stat fstat; if (-1 == stat(file, &fstat)) { PRINT_ERR("Couldn't stat file: %s", strerror(errno)); ret_val = -1; goto ret_error; } char *fname = strrchr(file, '/'); if (!fname) { fname = file; } else { fname = fname+1; } memset(buf, 0, PGMBUF_SIZE); snprintf(buf, PGMBUF_SIZE, CMD_SEND_FILE" %ld %s", fstat.st_size, fname); PRINT_DBG("Sending file with command: %s", buf); size_t bytes_written; int bytes_read; #ifdef UDPTEST bytes_written = sendto(sockfd, buf, strlen(buf)+1, 0, (struct sockaddr*)&servaddr, sizeof(servaddr)); if (bytes_written != strlen(buf)+1) { PRINT_ERR("Couldn't send file transfer command! %s", strerror(errno)); ret_val = -1; goto ret_error; } #else pgm_status = pgm_status = pgm_send(pgm_sock, buf, strlen(buf)+1, &bytes_written); if (pgm_status != PGM_IO_STATUS_NORMAL) { PRINT_ERR("Couldn't send file transfer command!"); ret_val = -1; goto ret_error; } #endif bfd = open(file, O_RDONLY); if (bfd < 0) { PRINT_ERR("Couldn't open file for reading! %s", strerror(errno)); ret_val = -1; goto ret_error; } int fds = 0; fd_set writefds; fd_set readfds; bytes_read = read(bfd, buf, PGMBUF_SIZE); while (bytes_read > 0) { #ifdef UDPTEST bytes_written = sendto(sockfd, buf, bytes_read, 0, (struct sockaddr*)&servaddr, sizeof(servaddr)); #else struct timeval tv; pgm_status = pgm_send(pgm_sock, buf, bytes_read, &bytes_written); //PRINT_DBG("pgm_status: %d", pgm_status); switch (pgm_status) { case PGM_IO_STATUS_NORMAL : { #endif if (bytes_written != bytes_read) { PRINT_ERR("Error sending file!"); ret_val = -1; goto ret_error; } bytes_read = read(bfd, buf, PGMBUF_SIZE); #ifdef UDPTEST struct timespec ts = {0, 35000}; nanosleep(&ts, NULL); #else } break; case PGM_IO_STATUS_TIMER_PENDING: { socklen_t optlen = sizeof(tv); pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_TIME_REMAIN, &tv, &optlen); if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000)) break; goto block; } case PGM_IO_STATUS_RATE_LIMITED : { socklen_t optlen = sizeof(tv); pgm_getsockopt (pgm_sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv, &optlen); if (0 == (tv.tv_sec * 1000) + ((tv.tv_usec + 500) / 1000)) break; /* No accidental fallthrough! */ } case PGM_IO_STATUS_CONGESTION : case PGM_IO_STATUS_WOULD_BLOCK : block: { FD_ZERO(&writefds); pgm_select_info(pgm_sock, NULL, &writefds, &fds); fds = select(fds, NULL, &writefds, NULL, pgm_status == PGM_IO_STATUS_WOULD_BLOCK ? NULL : &tv); } break; default: PRINT_ERR("Send error!"); ret_val = -1; goto ret_error; break; } #endif } #ifndef UDPTEST pthread_mutex_lock(&m_pftp_mutex); m_run_receiver = 0; pthread_mutex_unlock(&m_pftp_mutex); pthread_join(nak_thread, NULL); pthread_mutex_destroy(&m_pftp_mutex); #endif goto ret_good; ret_error: PRINT_DBG("Exit error"); goto ret; ret_good: PRINT_DBG("Exit good"); ret: if (bfd > 0) close(bfd); #ifdef UDPTEST if (sockfd > 0) close(sockfd); #else if (pgm_sock) { pftp_stop(pgm_sock); } #endif return ret_val; }
int main(int argc, char *argv[]) { int ch; time_t secs = 0, t; char *cp; long nsecs = 0; struct timespec rqtp; int i; if (pledge("stdio", NULL) == -1) err(1, "pledge"); signal(SIGALRM, alarmh); while ((ch = getopt(argc, argv, "")) != -1) switch(ch) { default: usage(); } argc -= optind; argv += optind; if (argc != 1) usage(); cp = *argv; while ((*cp != '\0') && (*cp != '.')) { if (!isdigit((unsigned char)*cp)) usage(); t = (secs * 10) + (*cp++ - '0'); if (t / 10 != secs) /* oflow */ return (EINVAL); secs = t; } /* Handle fractions of a second */ if (*cp == '.') { cp++; for (i = 100000000; i > 0; i /= 10) { if (*cp == '\0') break; if (!isdigit((unsigned char)*cp)) usage(); nsecs += (*cp++ - '0') * i; } /* * We parse all the way down to nanoseconds * in the above for loop. Be pedantic about * checking the rest of the argument. */ while (*cp != '\0') { if (!isdigit((unsigned char)*cp++)) usage(); } } rqtp.tv_sec = secs; rqtp.tv_nsec = nsecs; if ((secs > 0) || (nsecs > 0)) if (nanosleep(&rqtp, NULL)) err(1, NULL); return (0); }
void *os_sound_start_thread(void *_ca) { jcall_t *ca = (jcall_t*)_ca; char data_in[512]; #ifdef USE_PCM char data_in_dec[1024]; #endif int have_more = 0; int timestamp = 0; int i; mblk_t *mp; struct timeval pkt_in_time, pkt_out_time, sleeptime; struct timespec sleepns; printf("rtp reading thread started\n"); while (ca->enable_audio != -1) { #if !MINIMIZE_COPYING do { memset(data_in, 0, 160); i = rtp_session_recv_with_ts(ca->rtp_session, data_in, 160, timestamp, &have_more); if (i>0) { #ifdef USE_PCM if (ca->payload==8) /* A-Law */ alaw_dec(data_in, data_in_dec, 160); if (ca->payload==0) /* Mu-Law */ mulaw_dec(data_in, data_in_dec, 160); write(fd, data_in_dec, i*2); #else write(fd, data_in, i); #endif } } while(have_more); #else /* MINIMIZE_COPYING */ if ( (mp=rtp_session_recvm_with_ts(ca->rtp_session,timestamp))!=NULL) { int len=mp->b_cont->b_wptr-mp->b_cont->b_rptr; gettimeofday(&pkt_in_time, 0); if (ca->enable_audio != -1) { #ifdef USE_PCM if (ca->payload==8) /* A-Law */ alaw_dec(mp->b_cont->b_rptr, data_in_dec, len); if (ca->payload==0) /* Mu-Law */ mulaw_dec(mp->b_cont->b_rptr, data_in_dec, len); write(fd, data_in_dec, len*2); #else write(fd, mp->b_cont->b_rptr, len); #endif } if (ca->enable_audio == -1) dbgbpt1(); freemsg(mp); gettimeofday(&pkt_out_time, 0); /* compute the time we spent processing the packet */ tvsub(&pkt_out_time, &pkt_in_time); } #endif sleeptime.tv_usec = 10000; sleeptime.tv_sec = 0; tvsub(&sleeptime, &pkt_out_time); TIMEVAL_TO_TIMESPEC(&sleeptime, &sleepns); #if !BLOCKING_MODE if (ca->enable_audio != -1) nanosleep(&sleepns, 0); #endif timestamp += 160; } printf("rtp reading thread stopping\n"); dbgbpt2(); return NULL; }
int main (int argc, char **argv) { UProfContext *context; UProfReport *report; int i; uprof_init (&argc, &argv); context = uprof_context_new ("Simple context"); DBG_PRINTF ("start full timer (rdtsc = %" G_GUINT64_FORMAT ")\n", uprof_get_system_counter ()); UPROF_TIMER_START (context, full_timer); for (i = 0; i < 2; i ++) { struct timespec delay; UPROF_COUNTER_INC (context, loop0_counter); DBG_PRINTF ("start simple timer (rdtsc = %" G_GUINT64_FORMAT ")\n", uprof_get_system_counter ()); UPROF_TIMER_START (context, loop0_timer); DBG_PRINTF (" <delay: 1/2 sec>\n"); delay.tv_sec = 0; delay.tv_nsec = 1000000000/2; nanosleep (&delay, NULL); UPROF_TIMER_START (context, loop0_sub_timer); DBG_PRINTF (" <timing sub delay: 1/4 sec>\n"); delay.tv_sec = 0; delay.tv_nsec = 1000000000/4; nanosleep (&delay, NULL); UPROF_TIMER_STOP (context, loop0_sub_timer); UPROF_TIMER_STOP (context, loop0_timer); DBG_PRINTF ("stop simple timer (rdtsc = %" G_GUINT64_FORMAT ")\n", uprof_get_system_counter ()); } for (i = 0; i < 4; i ++) { struct timespec delay; UPROF_COUNTER_INC (context, loop1_counter); DBG_PRINTF ("start simple timer (rdtsc = %" G_GUINT64_FORMAT ")\n", uprof_get_system_counter ()); UPROF_TIMER_START (context, loop1_timer); DBG_PRINTF (" <delay: 1/4 sec>\n"); delay.tv_sec = 0; delay.tv_nsec = 1000000000/4; nanosleep (&delay, NULL); UPROF_TIMER_START (context, loop1_sub_timer); DBG_PRINTF (" <timing sub delay: 1/2 sec>\n"); delay.tv_sec = 0; delay.tv_nsec = 1000000000/2; nanosleep (&delay, NULL); UPROF_TIMER_STOP (context, loop1_sub_timer); UPROF_TIMER_STOP (context, loop1_timer); DBG_PRINTF ("stop simple timer (rdtsc = %" G_GUINT64_FORMAT ")\n", uprof_get_system_counter ()); } DBG_PRINTF ("stop full timer (rdtsc = %" G_GUINT64_FORMAT ")\n", uprof_get_system_counter ()); UPROF_TIMER_STOP (context, full_timer); report = uprof_report_new ("Simple report"); uprof_report_add_statistic (report, "Special thingy", "This is a particularly interesting thingy"); uprof_report_add_statistic_attribute (report, "Special thingy", "Thingy A value", "Thingy A\nvalue", "The real A value of thingys", UPROF_ATTRIBUTE_TYPE_WORD, a_values_cb, NULL); uprof_report_add_statistic_attribute (report, "Special thingy", "Thingy B value", "Thingy B\nvalue", "The real B value of thingys", UPROF_ATTRIBUTE_TYPE_WORD, b_values_cb, NULL); uprof_report_add_statistic (report, "Special dobble", "This is a particularly interesting dobble"); uprof_report_add_statistic_attribute (report, "Special dobble", "Dobble value", "Dobble\nvalue", "The real value of dobbles", UPROF_ATTRIBUTE_TYPE_FLOAT, dobbles_cb, NULL); uprof_report_add_timers_attribute (report, "Time in seconds", "Time in\nseconds", "The time elapsed in seconds", UPROF_ATTRIBUTE_TYPE_INT, seconds_column_cb, NULL); uprof_report_add_counters_attribute (report, "Double count", "Double\ncount", "The count doubled", UPROF_ATTRIBUTE_TYPE_INT, double_count_cb, NULL); uprof_report_add_counters_attribute (report, "Tripple count", "Tripple\ncount", "The count trippled", UPROF_ATTRIBUTE_TYPE_INT, tripple_count_cb, NULL); uprof_report_add_context (report, context); uprof_report_print (report); uprof_report_unref (report); uprof_context_unref (context); return 0; }
void ook_transmit(const char *filename, int mod) { FILE *fd = fopen(filename, "r"); char cmd; int arg; int ret; struct timespec ts; if (!fd) { printf("ERROR: Unable to open data file\n"); return; } /* Calculate total tx time for calibration */ float took = 0; struct timeval start, stop; gettimeofday(&start, NULL); while (!feof(fd)) { fscanf(fd, "%c%d\n", &cmd, &arg); //printf("%c %d\n", cmd, arg); switch (cmd) { case 'N': if (arg == 0) { continue; } //printf("Sleep for %ld\n", ts.tv_nsec); //for (int X = 0; X < arg/162; X ++) { // ACCESS(CM_GP0DIV) = (0x5a << 24) + mod + (X/8)%3 - 1 ; // Going for 0.077 //} ts.tv_sec = 0; ts.tv_nsec = arg - 80000; ret = nanosleep(&ts, NULL); if (ret != 0) { printf("Warning nanosleep returned != 0: %d\n", ret); perror("nanosleep"); return; } continue; case 'S': if (arg) { //printf("TX 1\n"); askHigh(); } else { //printf("TX 0\n"); askLow(); } continue; default: printf("ERROR: Invalid command in data file: %c\n", cmd); return; } } gettimeofday(&stop, NULL); took = (stop.tv_sec - start.tv_sec) * 1e6; took += (stop.tv_usec - start.tv_usec); took /= 1e6; printf("Transmission took %10.5f\n", took); fclose(fd); return; }
int main(int argc, char *argv[]) { struct udev *udev; static const struct option options[] = { { "lock-media", no_argument, NULL, 'l' }, { "unlock-media", no_argument, NULL, 'u' }, { "eject-media", no_argument, NULL, 'e' }, { "debug", no_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, {} }; bool eject = false; bool lock = false; bool unlock = false; const char *node = NULL; int fd = -1; int cnt; int rc = 0; udev = udev_new(); if (udev == NULL) goto exit; log_open(); udev_set_log_fn(udev, log_fn); while (1) { int option; option = getopt_long(argc, argv, "deluh", options, NULL); if (option == -1) break; switch (option) { case 'l': lock = true; break; case 'u': unlock = true; break; case 'e': eject = true; break; case 'd': debug = true; log_set_max_level(LOG_DEBUG); udev_set_log_priority(udev, LOG_DEBUG); break; case 'h': printf("Usage: cdrom_id [options] <device>\n" " --lock-media lock the media (to enable eject request events)\n" " --unlock-media unlock the media\n" " --eject-media eject the media\n" " --debug debug to stderr\n" " --help print this help text\n\n"); goto exit; default: rc = 1; goto exit; } } node = argv[optind]; if (!node) { log_error("no device\n"); fprintf(stderr, "no device\n"); rc = 1; goto exit; } srand((unsigned int)getpid()); for (cnt = 20; cnt > 0; cnt--) { struct timespec duration; fd = open(node, O_RDONLY|O_NONBLOCK|(is_mounted(node) ? 0 : O_EXCL)); if (fd >= 0 || errno != EBUSY) break; duration.tv_sec = 0; duration.tv_nsec = (100 * 1000 * 1000) + (rand() % 100 * 1000 * 1000); nanosleep(&duration, NULL); } if (fd < 0) { log_debug("unable to open '%s'\n", node); fprintf(stderr, "unable to open '%s'\n", node); rc = 1; goto exit; } log_debug("probing: '%s'\n", node); /* same data as original cdrom_id */ if (cd_capability_compat(udev, fd) < 0) { rc = 1; goto exit; } /* check for media - don't bail if there's no media as we still need to * to read profiles */ cd_media_compat(udev, fd); /* check if drive talks MMC */ if (cd_inquiry(udev, fd) < 0) goto work; /* read drive and possibly current profile */ if (cd_profiles(udev, fd) != 0) goto work; /* at this point we are guaranteed to have media in the drive - find out more about it */ /* get session/track info */ cd_media_toc(udev, fd); /* get writable media state */ cd_media_info(udev, fd); work: /* lock the media, so we enable eject button events */ if (lock && cd_media) { log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (lock)\n"); media_lock(udev, fd, true); } if (unlock && cd_media) { log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (unlock)\n"); media_lock(udev, fd, false); } if (eject) { log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (unlock)\n"); media_lock(udev, fd, false); log_debug("START_STOP_UNIT (eject)\n"); media_eject(udev, fd); } printf("ID_CDROM=1\n"); if (cd_cd_rom) printf("ID_CDROM_CD=1\n"); if (cd_cd_r) printf("ID_CDROM_CD_R=1\n"); if (cd_cd_rw) printf("ID_CDROM_CD_RW=1\n"); if (cd_dvd_rom) printf("ID_CDROM_DVD=1\n"); if (cd_dvd_r) printf("ID_CDROM_DVD_R=1\n"); if (cd_dvd_rw) printf("ID_CDROM_DVD_RW=1\n"); if (cd_dvd_ram) printf("ID_CDROM_DVD_RAM=1\n"); if (cd_dvd_plus_r) printf("ID_CDROM_DVD_PLUS_R=1\n"); if (cd_dvd_plus_rw) printf("ID_CDROM_DVD_PLUS_RW=1\n"); if (cd_dvd_plus_r_dl) printf("ID_CDROM_DVD_PLUS_R_DL=1\n"); if (cd_dvd_plus_rw_dl) printf("ID_CDROM_DVD_PLUS_RW_DL=1\n"); if (cd_bd) printf("ID_CDROM_BD=1\n"); if (cd_bd_r) printf("ID_CDROM_BD_R=1\n"); if (cd_bd_re) printf("ID_CDROM_BD_RE=1\n"); if (cd_hddvd) printf("ID_CDROM_HDDVD=1\n"); if (cd_hddvd_r) printf("ID_CDROM_HDDVD_R=1\n"); if (cd_hddvd_rw) printf("ID_CDROM_HDDVD_RW=1\n"); if (cd_mo) printf("ID_CDROM_MO=1\n"); if (cd_mrw) printf("ID_CDROM_MRW=1\n"); if (cd_mrw_w) printf("ID_CDROM_MRW_W=1\n"); if (cd_media) printf("ID_CDROM_MEDIA=1\n"); if (cd_media_mo) printf("ID_CDROM_MEDIA_MO=1\n"); if (cd_media_mrw) printf("ID_CDROM_MEDIA_MRW=1\n"); if (cd_media_mrw_w) printf("ID_CDROM_MEDIA_MRW_W=1\n"); if (cd_media_cd_rom) printf("ID_CDROM_MEDIA_CD=1\n"); if (cd_media_cd_r) printf("ID_CDROM_MEDIA_CD_R=1\n"); if (cd_media_cd_rw) printf("ID_CDROM_MEDIA_CD_RW=1\n"); if (cd_media_dvd_rom) printf("ID_CDROM_MEDIA_DVD=1\n"); if (cd_media_dvd_r) printf("ID_CDROM_MEDIA_DVD_R=1\n"); if (cd_media_dvd_ram) printf("ID_CDROM_MEDIA_DVD_RAM=1\n"); if (cd_media_dvd_rw) printf("ID_CDROM_MEDIA_DVD_RW=1\n"); if (cd_media_dvd_plus_r) printf("ID_CDROM_MEDIA_DVD_PLUS_R=1\n"); if (cd_media_dvd_plus_rw) printf("ID_CDROM_MEDIA_DVD_PLUS_RW=1\n"); if (cd_media_dvd_plus_rw_dl) printf("ID_CDROM_MEDIA_DVD_PLUS_RW_DL=1\n"); if (cd_media_dvd_plus_r_dl) printf("ID_CDROM_MEDIA_DVD_PLUS_R_DL=1\n"); if (cd_media_bd) printf("ID_CDROM_MEDIA_BD=1\n"); if (cd_media_bd_r) printf("ID_CDROM_MEDIA_BD_R=1\n"); if (cd_media_bd_re) printf("ID_CDROM_MEDIA_BD_RE=1\n"); if (cd_media_hddvd) printf("ID_CDROM_MEDIA_HDDVD=1\n"); if (cd_media_hddvd_r) printf("ID_CDROM_MEDIA_HDDVD_R=1\n"); if (cd_media_hddvd_rw) printf("ID_CDROM_MEDIA_HDDVD_RW=1\n"); if (cd_media_state != NULL) printf("ID_CDROM_MEDIA_STATE=%s\n", cd_media_state); if (cd_media_session_next > 0) printf("ID_CDROM_MEDIA_SESSION_NEXT=%d\n", cd_media_session_next); if (cd_media_session_count > 0) printf("ID_CDROM_MEDIA_SESSION_COUNT=%d\n", cd_media_session_count); if (cd_media_session_count > 1 && cd_media_session_last_offset > 0) printf("ID_CDROM_MEDIA_SESSION_LAST_OFFSET=%llu\n", cd_media_session_last_offset); if (cd_media_track_count > 0) printf("ID_CDROM_MEDIA_TRACK_COUNT=%d\n", cd_media_track_count); if (cd_media_track_count_audio > 0) printf("ID_CDROM_MEDIA_TRACK_COUNT_AUDIO=%d\n", cd_media_track_count_audio); if (cd_media_track_count_data > 0) printf("ID_CDROM_MEDIA_TRACK_COUNT_DATA=%d\n", cd_media_track_count_data); exit: if (fd >= 0) close(fd); udev_unref(udev); log_close(); return rc; }
bool vis::MpdAudioSource::read(pcm_stereo_sample *buffer, const uint32_t buffer_size) { // try to re-open the stream if it has been closed if (m_mpd_fifo_fd < 0) { open_mpd_fifo(); } auto buffer_size_bytes = static_cast<size_t>(sizeof(pcm_stereo_sample) * buffer_size); size_t bytes_left = buffer_size_bytes; if (m_mpd_fifo_fd >= 0) { auto attempts = 0; memset(buffer, 0, buffer_size_bytes); while (bytes_left > 0) { // Read buffer int64_t bytes_read = ::read(m_mpd_fifo_fd, buffer, bytes_left); // No bytes left if (bytes_read == 0) { VIS_LOG(vis::LogLevel::WARN, "Could not read any bytes"); return false; } // Error reading file. Since non-blocking is set, it's possible // there's not enough data yet if (bytes_read == -1) { auto error_code = errno; // EAGAIN means data is not ready yet if (error_code == EAGAIN) { // Try up to k_read_attempts before quiting if (attempts > k_read_attempts) { VIS_LOG(vis::LogLevel::WARN, "Could not finish reading " "buffer, bytes read: %d " "buffer size: ", bytes_read, buffer_size_bytes); // zero out buffer memset(buffer, 0, buffer_size_bytes); ::close(m_mpd_fifo_fd); m_mpd_fifo_fd = -1; return false; } nanosleep(&k_read_attempt_sleep_timespec, nullptr); ++attempts; } else { VIS_LOG(vis::LogLevel::WARN, "Error reading file: %d %s", error_code, strerror(error_code)); } } // Bytes were read fine, continue until buffer is full else { bytes_left -= static_cast<size_t>(bytes_read); } } // Success fully read entire buffer return true; } return false; }
int main(int argc, char *argv[]) { struct timespec ts,ts1; int i,ncpu; int idcpu; unsigned long freq[8]; XEvent event; char gov[20]; char drv[20],*ptr,*endptr; char prg[LN_PATH]; ts.tv_sec=0; ts.tv_nsec=DELAY; prg[0]=0; idcpu=0; for(i=0;i<MAX_CPU;i++) freq[i]=0; if(argc >1) { for (i=1; i<=argc; i++) { if (!strcmp(argv[i], "-v")) { printf(WMCPUFREQ_VERSION); exit(0); } if (!strcmp(argv[i], "-exe")) { if(strlen(argv[i+1]) < LN_PATH ) strcpy(prg,argv[i+1]); break; } if (!strcmp(argv[i], "-cpuid")) { if(strlen(argv[i+1]) < LN_PATH ) idcpu=strtol(argv[i+1],&endptr,0); printf("cpuid= %d \n",idcpu); break; } printf("only -v, -exe, -cpuid supported \n"); exit(0); } } /* basic checks */ if ( idcpu < 0 ) { printf("cpuid < 0 \n"); exit(-1); } /* get driver name (guess all cpu have the same driver) */ ptr=cpufreq_get_driver(cpu); if(!ptr) { printf("no driver found \n"); exit(-1); } strcpy(drv,ptr); cpufreq_put_driver(ptr); /* get number of cpu (0=cpu0, 1=cpu1 ...) */ ncpu=-1; for(i=0;i<MAX_CPU;i++) { if( cpufreq_cpu_exists(idcpu+i) ==0) { printf("cpuid %d found\n",idcpu+i); ncpu=i; } } switch ( ncpu ) { case -1: printf("no cpuid found \n"); exit(-1); case 0: wm_xpm=wmcpufreq_master_xpm_1; wm_bits=wmcpufreq_mask_bits_1; break; case 1: wm_xpm=wmcpufreq_master_xpm_2; wm_bits=wmcpufreq_mask_bits_2; break; case 2: wm_xpm=wmcpufreq_master_3; wm_bits=wmcpufreq_mask_3_bits; break; case 3: wm_xpm=wmcpufreq_master_3; wm_bits=wmcpufreq_mask_3_bits; break; default: printf("no yet implemented: cpuid %d \n",ncpu); exit(-1); break; } /* guess every cpu has the same limits */ if(cpufreq_get_hardware_limits(cpu, &f_min, &f_max)) { printf("can't determine hardware limits \n"); exit(-1); } openXwindow(argc,argv, wm_xpm, (char*)wm_bits, wmcpufreq_mask_width, wmcpufreq_mask_height); while(1) { /* Process any pending X events */ while(XPending(display)) { XNextEvent(display, &event); switch(event.type) { case Expose: RedrawWindow(); break; case ButtonPress: if(strlen(prg)) execCommand(prg); break; case ButtonRelease: break; } } RedrawWindow(); /* get info */ for(i=0;i<=ncpu;i++) freq[i]=cpufreq_get_freq_kernel(i+idcpu); policy=cpufreq_get_policy(cpu); strcpy(gov,policy->governor); max=policy->max; min=policy->min; cpufreq_put_policy(policy); /* show info */ show_mhz(freq,ncpu); if (ncpu==0) show_driver(drv); show_governor(gov); /* delay */ nanosleep(&ts,&ts1); } }
/* * timer thread * * Modes: * - clock_nanosleep based * - cyclic timer based * * Clock: * - CLOCK_MONOTONIC * - CLOCK_REALTIME * - CLOCK_MONOTONIC_HR * - CLOCK_REALTIME_HR * */ void *timerthread(void *param) { struct thread_param *par = param; struct sched_param schedp; sigset_t sigset; struct timespec now, next, interval; struct thread_stat *stat = par->stats; int policy = par->prio ? SCHED_FIFO : SCHED_OTHER; int err; #ifdef __UNSUPPORTED struct itimerval itimer; struct sigevent sigev; timer_t timer; struct itimerspec tspec; #endif #if (INGO_TRACE + TGLX_TRACE) int stopped = 0; #endif interval.tv_sec = par->interval / USEC_PER_SEC; interval.tv_nsec = (par->interval % USEC_PER_SEC) * 1000; #if INGO_TRACE system("echo 1 > /proc/sys/kernel/trace_all_cpus"); system("echo 1 > /proc/sys/kernel/trace_enabled"); system("echo 1 > /proc/sys/kernel/trace_freerunning"); system("echo 0 > /proc/sys/kernel/trace_print_at_crash"); system("echo 1 > /proc/sys/kernel/trace_user_triggered"); system("echo 0 > /proc/sys/kernel/trace_user_trigger_irq"); system("echo 0 > /proc/sys/kernel/trace_verbose"); system("echo 0 > /proc/sys/kernel/preempt_thresh"); system("echo 0 > /proc/sys/kernel/wakeup_timing"); system("echo 0 > /proc/sys/kernel/preempt_max_latency"); #endif stat->tid = gettid(); sigemptyset(&sigset); sigaddset(&sigset, par->signal); sigprocmask(SIG_BLOCK, &sigset, NULL); #ifdef __UNSUPPORTED if (par->mode == MODE_CYCLIC) { sigev.sigev_notify = SIGEV_THREAD_ID | SIGEV_SIGNAL; sigev.sigev_signo = par->signal; sigev.sigev_notify_thread_id = stat->tid; timer_create(par->clock, &sigev, &timer); tspec.it_interval = interval; } #endif memset(&schedp, 0, sizeof(schedp)); schedp.sched_priority = par->prio; err = pthread_setschedparam(pthread_self(), policy, &schedp); #ifdef __XENO__ if (err) { fprintf(stderr, "pthread_setschedparam: %s\n" "(modprobe xeno_posix?)\n", strerror(err)); test_shutdown = 1; return (void *) 1; } #endif /* Get current time */ next = start; next.tv_sec++; #ifdef __UNSUPPORTED if (par->mode == MODE_CYCLIC) { if (par->timermode == TIMER_ABSTIME) tspec.it_value = next; else { tspec.it_value.tv_nsec = 0; tspec.it_value.tv_sec = 1; } timer_settime(timer, par->timermode, &tspec, NULL); } if (par->mode == MODE_SYS_ITIMER) { itimer.it_value.tv_sec = 1; itimer.it_value.tv_usec = 0; itimer.it_interval.tv_sec = interval.tv_sec; itimer.it_interval.tv_usec = interval.tv_nsec / 1000; setitimer (ITIMER_REAL, &itimer, NULL); } #endif stat->threadstarted++; #if (INGO_TRACE + TGLX_TRACE) gettimeofday(0,(struct timezone *)1); #endif while (!test_shutdown) { long diff; #ifdef __UNSUPPORTED int sigs; #endif /* Wait for next period */ switch (par->mode) { #ifdef __UNSUPPORTED case MODE_CYCLIC: case MODE_SYS_ITIMER: if (sigwait(&sigset, &sigs) < 0) goto out; break; #endif case MODE_CLOCK_NANOSLEEP: if (par->timermode == TIMER_ABSTIME) clock_nanosleep(par->clock, TIMER_ABSTIME, &next, NULL); else { clock_gettime(par->clock, &now); clock_nanosleep(par->clock, TIMER_RELTIME, &interval, NULL); next.tv_sec = now.tv_sec + interval.tv_sec; next.tv_nsec = now.tv_nsec + interval.tv_nsec; tsnorm(&next); } break; #ifdef __UNSUPPORTED case MODE_SYS_NANOSLEEP: clock_gettime(par->clock, &now); nanosleep(&interval, NULL); next.tv_sec = now.tv_sec + interval.tv_sec; next.tv_nsec = now.tv_nsec + interval.tv_nsec; tsnorm(&next); break; #endif } clock_gettime(par->clock, &now); diff = calcdiff(now, next); if (diff < stat->min) stat->min = diff; if (diff > stat->max) { stat->max = diff; #if IPIPE_TRACE if (stat->traced) xntrace_user_freeze(diff, 0); #endif } stat->avg += (double) diff; #if (INGO_TRACE + TGLX_TRACE) if (!stopped && (diff > tracelimit)) { stopped++; gettimeofday(0,0); test_shutdown++; } #endif stat->act = diff; stat->cycles++; if (par->bufmsk) stat->values[stat->cycles & par->bufmsk] = diff; next.tv_sec += interval.tv_sec; next.tv_nsec += interval.tv_nsec; tsnorm(&next); if (par->max_cycles && par->max_cycles == stat->cycles) break; } #ifdef __UNSUPPORTED out: if (par->mode == MODE_CYCLIC) timer_delete(timer); if (par->mode == MODE_SYS_ITIMER) { itimer.it_value.tv_sec = 0; itimer.it_value.tv_usec = 0; itimer.it_interval.tv_sec = 0; itimer.it_interval.tv_usec = 0; setitimer (ITIMER_REAL, &itimer, NULL); } #endif /* switch to normal */ schedp.sched_priority = 0; pthread_setschedparam(pthread_self(), SCHED_OTHER, &schedp); stat->threadstarted = -1; return NULL; }
static int csr(int fd, struct uart_t *u, struct termios *ti) { struct timespec tm = {0, 10000000}; /* 10ms - be generous */ static int csr_seq = 0; /* Sequence number of command */ int divisor; int err; struct CSR_Get_Build_ID cmd1; struct CSR_Get_Build_ID_Event cce; struct CSR_Set_UART_Speed cmd2; /* Try to read the build ID of the CSR chip */ cmd1.bcc.channel = 0xc2; /* first+last+channel=BCC */ cmd1.bcc.type = __htob16(0x0000); /* type = GET-REQ */ cmd1.bcc.len = __htob16(5 + 4); /* ??? */ cmd1.bcc.seq_num = __htob16(csr_seq); /* seq num */ csr_seq++; cmd1.bcc.var_id = __htob16(0x2819); /* var_id = CSR_CMD_BUILD_ID */ cmd1.bcc.status = __htob16(0x0000); /* status = STATUS_OK */ /* CSR BCC payload */ memset(cmd1.data, 0, sizeof(cmd1.data)); /* Send command */ err = hci_exec_cmd1(fd, HCI_C_CSR_COMMAND, &cmd1, sizeof(cmd1), ALL_EVENTS_MASK, HCI_SKIP_STATUS); if (err) return err; do { #if 0 // it's here in original code /* Send command */ err = hci_exec_cmd(fd, &cmd1, ALL_EVENTS_MASK, HCI_SKIP_STATUS, NULL); if (err) return err; #endif err = hci_recv_event(fd, &cce, sizeof(cce), 20); if (err < 0) { return err; } } while (cce.hci.EventCode != 0xFF); /* Display that to user */ BTINFO("CSR build ID 0x%02X-0x%02X\n", cce.data[12], cce.data[11]); /* Now, create the command that will set the UART speed */ cmd2.bcc.channel = 0xc2; cmd2.bcc.type = __htob16(0x0002); // SET-REQ cmd2.bcc.len = __htob16(5 + 4); cmd2.bcc.seq_num = __htob16(csr_seq); csr_seq++; cmd2.bcc.var_id = __htob16(0x6802); // CONFIG_UART cmd2.bcc.status = __htob16(0x0000); // STATUS_OK switch (u->speed) { case 9600: divisor = 0x0027; break; /* Various speeds ommited */ case 57600: divisor = 0x00EC; break; case 115200: divisor = 0x01D8; break; /* For Brainbox Pcmcia cards */ case 460800: divisor = 0x075F; break; case 921600: divisor = 0x0EBF; break; default: /* Safe default */ divisor = 0x01D8; u->speed = 115200; break; } /* No parity, one stop bit -> divisor |= 0x0000; */ cmd2.speed = __htob16(divisor); memset(cmd2.extra, 0, sizeof(cmd2.extra)); err = hci_exec_cmd1(fd, HCI_C_CSR_COMMAND, &cmd2, sizeof(cmd2), ALL_EVENTS_MASK, HCI_SKIP_STATUS); if (err) return err; #if 0 // no wait for response in original code do { err = hci_recv_event(fd, &cce, sizeof(cce), 20); if (err < 0) { return err; } } while (cce.hci.EventCode != 0xFF); #endif nanosleep(&tm, NULL); return 0; }
static void *video_thread( void *arg ) { // Identify the arg consumer_sdl self = arg; // Obtain time of thread start struct timeval now; int64_t start = 0; int64_t elapsed = 0; struct timespec tm; mlt_frame next = NULL; mlt_properties properties = NULL; double speed = 0; // Get real time flag int real_time = mlt_properties_get_int( self->properties, "real_time" ); // Get the current time gettimeofday( &now, NULL ); // Determine start time start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec; while ( self->running ) { // Pop the next frame pthread_mutex_lock( &self->video_mutex ); next = mlt_deque_pop_front( self->queue ); while ( next == NULL && self->running ) { pthread_cond_wait( &self->video_cond, &self->video_mutex ); next = mlt_deque_pop_front( self->queue ); } pthread_mutex_unlock( &self->video_mutex ); if ( !self->running || next == NULL ) break; // Get the properties properties = MLT_FRAME_PROPERTIES( next ); // Get the speed of the frame speed = mlt_properties_get_double( properties, "_speed" ); // Get the current time gettimeofday( &now, NULL ); // Get the elapsed time elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start; // See if we have to delay the display of the current frame if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running ) { // Obtain the scheduled playout time int64_t scheduled = mlt_properties_get_int( properties, "playtime" ); // Determine the difference between the elapsed time and the scheduled playout time int64_t difference = scheduled - elapsed; // Smooth playback a bit if ( real_time && ( difference > 20000 && speed == 1.0 ) ) { tm.tv_sec = difference / 1000000; tm.tv_nsec = ( difference % 1000000 ) * 500; nanosleep( &tm, NULL ); } // Show current frame if not too old if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( self->queue ) < 2 ) ) consumer_play_video( self, next ); // If the queue is empty, recalculate start to allow build up again if ( real_time && ( mlt_deque_count( self->queue ) == 0 && speed == 1.0 ) ) { gettimeofday( &now, NULL ); start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000; } } // This frame can now be closed mlt_frame_close( next ); next = NULL; } if ( next != NULL ) mlt_frame_close( next ); mlt_consumer_stopped( &self->parent ); return NULL; }
static int swave(int fd, struct uart_t *u, struct termios *ti) { struct timespec tm = {0, 500000}; int err; struct Swave_Set_UART_Speed cmd; struct Swave_Event cce; struct Swave_Soft_Reset cmd1; // Silicon Wave set baud rate command // see HCI Vendor Specific Interface from Silicon Wave // first send a "param access set" command to set the // appropriate data fields in RAM. Then send a "HCI Reset // Subcommand", e.g. "soft reset" to make the changes effective. cmd.subcmd = 0x01; // param sub command cmd.tag = 0x11; // tag 17 = 0x11 = HCI Transport Params cmd.length = 0x03; // length of the parameter following cmd.flow = 0x01; // HCI Transport flow control enable cmd.type = 0x01; // HCI Transport Type = UART switch (u->speed) { case 19200: cmd.speed = 0x03; break; case 38400: cmd.speed = 0x02; break; case 57600: cmd.speed = 0x01; break; case 115200: cmd.speed = 0x00; break; default: u->speed = 115200; cmd.speed = 0x00; break; } /* Send command */ err = hci_exec_cmd1(fd, HCI_C_SWAVE_COMMAND, &cmd, sizeof(cmd), ALL_EVENTS_MASK, HCI_SKIP_STATUS); if (err) return err; nanosleep(&tm, NULL); do { err = hci_recv_event(fd, &cce, sizeof(cce), 20); if (err < 0) { return err; } } while (cce.hci.EventCode != 0xFF); cmd1.subcmd = 0x03; // param sub command err = hci_exec_cmd1(fd, HCI_C_SWAVE_COMMAND, &cmd1, sizeof(cmd1), ALL_EVENTS_MASK, HCI_SKIP_STATUS); if (err) return err; nanosleep(&tm, NULL); // now the uart baud rate on the silicon wave module is set and effective. // change our own baud rate as well. Then there is a reset event comming in // on the *new* baud rate. This is *undocumented*! The packet looks like this: // 04 FF 01 0B (which would make that a confirmation of 0x0B = "Param // subcommand class". So: change to new baud rate, read with timeout, parse // data, error handling. BTW: all param access in Silicon Wave is done this way. // Maybe this code would belong in a seperate file, or at least code reuse... return 0; }
int main(int argc, char **argv) { int ok; if(argc < 2) { printf("Enter latency tolerancy in millisec\n"); return 0; } int thres_time = PERIOD_NS + (MILLISEC * atoi(*(argv+1))); printf("Latency threshold set to +%d\n", thres_time); bool fifo = argc == 2; printf("main: getpid()=%d, gettid()=%d\n", getpid(), gettid()); if (fifo) { struct sched_param param; param.sched_priority = PRIORITY; ok = sched_setscheduler(gettid(), SCHED_FIFO, ¶m); printf("sched_setscheduler = %d\n", ok); } else { ok = setpriority(PRIO_PROCESS, 0 /* self */, -19); printf("setpriority = %d\n", ok); } #ifdef USE_TIMER timer_t timerid; struct sigevent ev; #endif clockid_t clockid; clockid = CLOCK_MONOTONIC; #ifdef USE_TIMER ev.sigev_notify = SIGEV_THREAD; ev.sigev_signo = 0; ev.sigev_value.sival_int = 0; ev.sigev_notify_function = notify_function; ev.sigev_notify_attributes = NULL; //ev.sigev_notify_thread_id = 0; ok = timer_create(clockid, &ev, &timerid); //printf("timer_create ok=%d, timerid=%p\n", ok, timerid); #endif ok = clock_gettime(CLOCK_MONOTONIC, &previous); //printf("clock_gettime ok=%d\n", ok); #ifdef USE_TIMER int flags = 0; struct itimerspec new_; struct itimerspec old; new_.it_interval.tv_sec = 0; new_.it_interval.tv_nsec = PERIOD_NS; new_.it_value.tv_sec = 0; new_.it_value.tv_nsec = PERIOD_NS; #endif int seconds = (int) (((long long) PERIOD_NS * (long long) MAX_COUNT) / 1000000000LL); printf("please wait %d seconds\n", seconds); #ifdef USE_TIMER ok = timer_settime(timerid, flags, &new_, &old); //printf("timer_settime ok=%d\n", ok); sleep(seconds + 1); ok = timer_delete(timerid); //printf("\ntimer_delete ok=%d\n", ok); #else struct timespec delay; delay.tv_sec = 0; delay.tv_nsec = PERIOD_NS; for (count = 0; count < MAX_COUNT; ++count) { { android::ScopedTrace(ATRACE_TAG, "nanosleep"); nanosleep(&delay, NULL); } struct timespec ts; { android::ScopedTrace(ATRACE_TAG, "clock_gettime"); ok = clock_gettime(CLOCK_MONOTONIC, &ts); } if (0 == ok) { unsigned delta_sec = ts.tv_sec - previous.tv_sec; int delta_ns = ts.tv_nsec - previous.tv_nsec; if (delta_ns < 0) { delta_ns += 1000000000; --delta_sec; } if(delta_ns > thres_time) { printf("[%d] Iterations passed\n", count); printf("delta exceeding at %lu.%09lu\n", delta_sec, delta_ns); return -1; } struct timespec delta_x; delta_x.tv_sec = delta_sec; delta_x.tv_nsec = delta_ns; delta_ts[count] = delta_x; previous = ts; ATRACE_INT("cycle_us", delta_ns / 1000); } } #endif printf("expected samples: %d, actual samples: %d\n", MAX_COUNT, count); qsort(delta_ts, count, sizeof(struct timespec), compar); printf("99.8%% CDF, ideal is all ~%d ns:\n", PERIOD_NS); int i; for (i = (count * 998) / 1000; i < count; ++i) { printf("%lu.%09lu\n", delta_ts[i].tv_sec, delta_ts[i].tv_nsec); } return EXIT_SUCCESS; }
void * thread_read_write (void *arg) { struct thread_info *info = (struct thread_info *) arg; int i, ret; int id, fd; /* for request */ u_int32_t reqx, reqy; unsigned long boffset, nblock; struct sockaddr_in *serv_addr; struct key_request_packet kreq; /* for read */ u_int32_t resx, resy; struct sockaddr_in addr; socklen_t addrlen; struct key_response_packet kresp; int kresperr, krespsuberr, krespkeylen; struct timeval start, end, res; double time; int success; unsigned long send_count, read_count; id = info->id; memset (&info->stats, 0, sizeof (struct horus_stats)); send_count = read_count = 0; fd = socket (PF_INET, SOCK_DGRAM, 0); if (fd < 0) { printf ("thread[%d]: Unable to open socket!: %s\n", id, strerror (errno)); return NULL; } serv_addr = info->serv_addr; boffset = info->boffset; nblock = info->nblock; memset (&kreq, 0, sizeof (kreq)); reqx = info->level; kreq.x = htonl (reqx); strncpy (kreq.filename, info->filename, sizeof (kreq.filename)); if (benchmark || horus_verbose) printf ("thread[%d]: server %s:%d bsize %d boffset %lu nblock %lu\n", id, info->server, ntohs (serv_addr->sin_port), HORUS_BLOCK_SIZE, boffset, nblock); if (spinwait) { fcntl (fd, F_SETFL, O_NONBLOCK); printf ("thread[%d]: spinwait: usleep %d nanosleep %ld " "nsend %d nread %d\n", id, useconds, nanoseconds, nsend, nread); } if (benchmark) gettimeofday (&start, NULL); for (i = 0; i < nblock; i++) { reqy = boffset + i; kreq.y = htonl (reqy); success = 0; send_count = nsend; do { ret = sendto (fd, &kreq, sizeof (key_request_packet), 0, (struct sockaddr *) serv_addr, sizeof (struct sockaddr_in)); send_count--; if (ret != sizeof (key_request_packet)) { if (horus_debug) printf ("thread[%d]: sendto(): failed: %d " "send_count: %ld\n", id, ret, send_count); info->stats.sendfail++; continue; } else { if (horus_debug) printf ("thread[%d]: request %d,%d send_count: %ld\n", id, reqx, reqy, send_count); } read_count = nread; do { if (spinwait) { if (useconds) usleep (useconds); if (nanoseconds) { struct timespec nanospec; nanospec.tv_sec = 0; nanospec.tv_nsec = nanoseconds; nanosleep (&nanospec, NULL); } } addrlen = sizeof (struct sockaddr_in); ret = recvfrom (fd, &kresp, sizeof (key_response_packet), 0, (struct sockaddr *) &addr, &addrlen); read_count--; if (ret != sizeof (key_response_packet)) { if (horus_debug) printf ("thread[%d]: recvfrom(): failed: %d " "read_count: %ld\n", id, ret, read_count); info->stats.recvfail++; continue; } else { if (horus_debug) printf ("thread[%d]: recvfrom(): received %d\n", id, ret); resx = ntohl (kresp.x); resy = ntohl (kresp.y); if (resx == reqx && resy == reqy) success++; else { if (horus_debug) printf ("thread[%d]: mismatch: " "req: %d,%d: resp: %d,%d\n", id, reqx, reqy, resx, resy); info->stats.resmismatch++; } } } while (! success && read_count > 0); } while (! success && send_count > 0); info->stats.sendretry += nsend - send_count - 1; info->stats.recvretry += nread - read_count - 1; if (! success) { if (horus_verbose) printf ("thread[%d]: give up K_%d,%d: resend: %lu reread: %lu\n", id, reqx, reqy, send_count, read_count); info->stats.giveup++; continue; } info->stats.success++; kresperr = (int) ntohs (kresp.err); krespsuberr = (int) ntohs (kresp.suberr); krespkeylen = (int) ntohl (kresp.key_len); horus_stats_record (&info->stats, kresperr, krespsuberr); if (horus_verbose && ! benchmark) { if (kresperr) printf ("thread[%d]: err = %d : %s\n", id, kresperr, horus_strerror (kresperr)); if (krespsuberr) printf ("thread[%d]: suberr = %d : %s\n", id, krespsuberr, strerror (krespsuberr)); if (! kresperr) printf ("thread[%d]: key_%d,%d: key_%d,%d/%d = %s\n", id, reqx, reqy, resx, resy, krespkeylen, print_key (kresp.key, krespkeylen)); } if (simulate && ! kresperr) { char key[HORUS_MAX_KEY_LEN]; size_t key_len; int simx, simy; unsigned long sboffset, snblock; u_int32_t *kht_block_size; int j; assert (reqx == resx && reqy == resy); simx = info->leaf_level; kht_block_size = info->kht_block_size; sboffset = resy * (kht_block_size[resx] / kht_block_size[simx]); snblock = kht_block_size[resx]; if (resx == info->leaf_level) { info->stats.keycalculated = info->stats.success; } else { for (j = 0; j < snblock; j++) { simy = sboffset + j; key_len = sizeof (key); horus_block_key (key, &key_len, simx, simy, kresp.key, krespkeylen, resx, resy, kht_block_size); info->stats.keycalculated++; if (horus_verbose && ! benchmark) printf ("thread[%d]: simulated: K_%d,%d = %s\n", id, simx, simy, print_key (key, key_len)); } } } } if (benchmark) gettimeofday (&end, NULL); close (fd); if (benchmark) { timeval_sub (&end, &start, &res); time = res.tv_sec + res.tv_usec * 0.000001; info->timeval = res; printf ("thread[%d]: %llu/%lu keys in %f secs ( %f q/s\n", id, info->stats.success, nblock, time, info->stats.success/time); if (simulate) printf ("thread[%d]: %llu keys calculated in %f secs ( %f q/s\n", id, info->stats.keycalculated, time, info->stats.keycalculated/time); } else if (horus_verbose) { printf ("thread[%d]: %llu/%lu keys processed.\n", id, info->stats.success, nblock); if (simulate) printf ("thread[%d]: %llu keys calculated\n", id, info->stats.keycalculated); } return NULL; }
/* * Helper thread to periodically poll the video sources and enqueue the * generated frames directed to the remote party to the channel's queue. * Using a separate thread also helps because the encoding can be * computationally expensive so we don't want to starve the main thread. */ static void *video_thread(void *arg) { struct video_desc *env = arg; int count = 0; char save_display[128] = ""; int i; /* integer variable used as iterator */ /* if sdl_videodriver is set, override the environment. Also, * if it contains 'console' override DISPLAY around the call to SDL_Init * so we use the console as opposed to the x11 version of aalib */ if (!ast_strlen_zero(env->sdl_videodriver)) { /* override */ const char *s = getenv("DISPLAY"); setenv("SDL_VIDEODRIVER", env->sdl_videodriver, 1); if (s && !strcasecmp(env->sdl_videodriver, "aalib-console")) { ast_copy_string(save_display, s, sizeof(save_display)); unsetenv("DISPLAY"); } } sdl_setup(env); if (!ast_strlen_zero(save_display)) { setenv("DISPLAY", save_display, 1); } ast_mutex_init(&env->dec_lock); /* used to sync decoder and renderer */ if (grabber_open(&env->out)) { ast_log(LOG_WARNING, "cannot open local video source\n"); } if (env->out.device_num) { env->out.devices[env->out.device_primary].status_index |= IS_PRIMARY | IS_SECONDARY; } /* even if no device is connected, we must call video_out_init, * as some of the data structures it initializes are * used in get_video_frames() */ video_out_init(env); /* Writes intial status of the sources. */ if (env->gui) { for (i = 0; i < env->out.device_num; i++) { print_message(env->gui->thumb_bd_array[i].board, src_msgs[env->out.devices[i].status_index]); } } for (;;) { struct timespec t = { 0, 50000000 }; /* XXX 20 times/sec */ struct ast_frame *p, *f; struct ast_channel *chan; int fd; char *caption = NULL, buf[160]; /* determine if video format changed */ if (count++ % 10 == 0) { if (env->out.sendvideo && env->out.devices) { snprintf(buf, sizeof(buf), "%s %s %dx%d @@ %dfps %dkbps", env->out.devices[env->out.device_primary].name, env->codec_name, env->enc_in.w, env->enc_in.h, env->out.fps, env->out.bitrate / 1000); } else { sprintf(buf, "hold"); } caption = buf; } /* manage keypad events */ /* XXX here we should always check for events, * otherwise the drag will not work */ if (env->gui) eventhandler(env, caption); /* sleep for a while */ nanosleep(&t, NULL); if (env->in) { struct video_dec_desc *v = env->in; /* * While there is something to display, call the decoder and free * the buffer, possibly enabling the receiver to store new data. */ while (v->dec_in_dpy) { struct fbuf_t *tmp = v->dec_in_dpy; /* store current pointer */ /* decode the frame, but show it only if not frozen */ if (v->d_callbacks->dec_run(v, tmp) && !env->frame_freeze) show_frame(env, WIN_REMOTE); tmp->used = 0; /* mark buffer as free */ tmp->ebit = 0; ast_mutex_lock(&env->dec_lock); if (++v->dec_in_dpy == &v->dec_in[N_DEC_IN]) /* advance to next, circular */ v->dec_in_dpy = &v->dec_in[0]; if (v->dec_in_cur == NULL) /* receiver was idle, enable it... */ v->dec_in_cur = tmp; /* using the slot just freed */ else if (v->dec_in_dpy == v->dec_in_cur) /* this was the last slot */ v->dec_in_dpy = NULL; /* nothing more to display */ ast_mutex_unlock(&env->dec_lock); } } if (env->shutdown) break; f = get_video_frames(env, &p); /* read and display */ if (!f) continue; chan = env->owner; if (chan == NULL) { /* drop the chain of frames, nobody uses them */ while (f) { struct ast_frame *g = AST_LIST_NEXT(f, frame_list); ast_frfree(f); f = g; } continue; } ast_channel_lock(chan); /* AST_LIST_INSERT_TAIL is only good for one frame, cannot use here */ if (ast_channel_readq(chan).first == NULL) { ast_channel_readq(chan).first = f; } else { ast_channel_readq(chan).last->frame_list.next = f; } ast_channel_readq(chan).last = p; /* * more or less same as ast_queue_frame, but extra * write on the alertpipe to signal frames. */ if (ast_channel_alertable(chan)) { for (p = f; p; p = AST_LIST_NEXT(p, frame_list)) { if (ast_channel_alert(chan)) { ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d: %s!\n", ast_channel_name(chan), f->frametype, f->subclass, strerror(errno)); } } ast_channel_unlock(chan); } /* thread terminating, here could call the uninit */ /* uninitialize the local and remote video environments */ env->in = dec_uninit(env->in); video_out_uninit(env); if (env->gui) env->gui = cleanup_sdl(env->gui, env->out.device_num); ast_mutex_destroy(&env->dec_lock); env->shutdown = 0; return NULL; } static void copy_geometry(struct fbuf_t *src, struct fbuf_t *dst) { if (dst->w == 0) dst->w = src->w; if (dst->h == 0) dst->h = src->h; } /*! initialize the video environment. * Apart from the formats (constant) used by sdl and the codec, * we use enc_in as the basic geometry. */ static void init_env(struct video_desc *env) { struct fbuf_t *c = &(env->out.loc_src_geometry); /* local source */ struct fbuf_t *ei = &(env->enc_in); /* encoder input */ struct fbuf_t *ld = &(env->loc_dpy); /* local display */ struct fbuf_t *rd = &(env->rem_dpy); /* remote display */ int i; /* integer working as iterator */ c->pix_fmt = PIX_FMT_YUV420P; /* default - camera format */ ei->pix_fmt = PIX_FMT_YUV420P; /* encoder input */ if (ei->w == 0 || ei->h == 0) { ei->w = 352; ei->h = 288; } ld->pix_fmt = rd->pix_fmt = PIX_FMT_YUV420P; /* sdl format */ /* inherit defaults */ copy_geometry(ei, c); /* camera inherits from encoder input */ copy_geometry(ei, rd); /* remote display inherits from encoder input */ copy_geometry(rd, ld); /* local display inherits from remote display */ /* fix the size of buffers for small windows */ for (i = 0; i < env->out.device_num; i++) { env->src_dpy[i].pix_fmt = PIX_FMT_YUV420P; env->src_dpy[i].w = SRC_WIN_W; env->src_dpy[i].h = SRC_WIN_H; } /* now we set the default coordinates for the picture in picture frames inside the env_in buffers, those can be changed by dragging the picture in picture with left click */ env->out.pip_x = ei->w - ei->w/3; env->out.pip_y = ei->h - ei->h/3; } /*! * The first call to the video code, called by oss_new() or similar. * Here we initialize the various components we use, namely SDL for display, * ffmpeg for encoding/decoding, and a local video source. * We do our best to progress even if some of the components are not * available. */ void console_video_start(struct video_desc *env, struct ast_channel *owner) { ast_log(LOG_WARNING, "env %p chan %p\n", env, owner); if (env == NULL) /* video not initialized */ return; env->owner = owner; /* work even if no owner is specified */ if (env->vthread) return; /* already initialized, nothing to do */ init_env(env); env->out.enc = map_config_video_format(env->codec_name); ast_log(LOG_WARNING, "start video out %s %dx%d\n", env->codec_name, env->enc_in.w, env->enc_in.h); /* * Register all codecs supported by the ffmpeg library. * We only need to do it once, but probably doesn't * harm to do it multiple times. */ avcodec_init(); avcodec_register_all(); av_log_set_level(AV_LOG_ERROR); /* only report errors */ if (env->out.fps == 0) { env->out.fps = 15; ast_log(LOG_WARNING, "fps unset, forcing to %d\n", env->out.fps); } if (env->out.bitrate == 0) { env->out.bitrate = 65000; ast_log(LOG_WARNING, "bitrate unset, forcing to %d\n", env->out.bitrate); } /* create the thread as detached so memory is freed on termination */ ast_pthread_create_detached_background(&env->vthread, NULL, video_thread, env); }
char*l="-\\|/";main(int c,char**v){int i=0,p;struct timespec s;if(c<2||kill(p=atoi(v[1],0)))exit(1);s.tv_sec=0;s.tv_nsec=1<<20;for(;!kill(p,0);){dprintf(1,"%c\b",l[++i&3]);nanosleep(&s,0);};dprintf(1," ");}
static void *xmi_random_thread(void *input) { unsigned long int temp_number; struct timespec sleep_time = {.tv_sec = (time_t) SLEEP_TIME,.tv_nsec = 0}; int rv; #if DEBUG == 2 fprintf(stdout,"Entering xmi_random_thread\n"); #endif //for loop keeps running until killed by xmi_end_random_acquisition for (;;) { //lock #if DEBUG == 2 fprintf(stdout,"Before lock in thread\n"); #endif rv=pthread_mutex_lock(&xmi_random_mutex); #if DEBUG == 2 fprintf(stdout,"After lock in thread: %i\n",rv); #endif if (xmi_numbers_in_memory < MAX_NUMBERS) { rv=pthread_mutex_unlock(&xmi_random_mutex); /* //open the random device if ((random_devicePtr=fopen(RANDOM_DEVICE,"r")) == NULL) { fprintf(stderr,"Could not open " RANDOM_DEVICE " for reading: continuing...\n"); nanosleep(&sleep_time,NULL); continue; }*/ #if DEBUG == 2 fprintf(stdout,"Before fread\n"); #endif if (fread(&temp_number,sizeof(unsigned long int),1,random_devicePtr) == 1) { rv=pthread_mutex_lock(&xmi_random_mutex); xmi_random_numbers[xmi_numbers_in_memory++]=temp_number; rv=pthread_mutex_unlock(&xmi_random_mutex); #if DEBUG == 2 fprintf(stdout,"Found a new number: %lu\n",temp_number); #endif } // fclose(random_devicePtr); } else { rv=pthread_mutex_unlock(&xmi_random_mutex); } #if DEBUG == 2 fprintf(stdout,"Before nanosleep: %i\n",rv); #endif nanosleep(&sleep_time,NULL); #if DEBUG == 2 fprintf(stdout,"After nanosleep\n"); #endif } //this line should never be reached return NULL; } int xmi_start_random_acquisition_dev(void) { #if DEBUG == 2 fprintf(stdout,"Entering xmi_start_random_acquisition\n"); #endif if (xmi_random_active == 1) { fprintf(stderr,"Random number acquisition already active\n"); return 0; } xmi_numbers_in_memory = 0; //allocate memory for the random_numbers xmi_random_numbers = (unsigned long int*) malloc(sizeof(unsigned long int)*MAX_NUMBERS); if (xmi_random_numbers == NULL) { fprintf(stderr,"Could not allocate memory for the random numbers\n"); return 0; } //open random device if ((random_devicePtr=fopen(RANDOM_DEVICE,"r")) == NULL) { fprintf(stderr,"Could not open " RANDOM_DEVICE " for reading\n"); return 0; } //initialize mutex pthread_mutex_init(&xmi_random_mutex,NULL); //start the thread if (pthread_create(&xmi_random_pthread_t, NULL, xmi_random_thread,NULL) != 0) { fprintf(stderr,"Could not create thread xmi_random_thread\n"); return 0; } xmi_random_active = 1; return 1; }
/* * open a socket to the specified host and port */ int open_socket(const char *host, u_int16 port) { struct hostent *infh; struct sockaddr_in sa_in; int sh, ret, err = 0; #define TSLEEP (50*1000) /* 50 milliseconds */ int loops = (GBL_CONF->connect_timeout * 10e5) / TSLEEP; DEBUG_MSG("open_socket -- [%s]:[%d]", host, port); /* prepare the structures */ memset((char*)&sa_in, 0, sizeof(sa_in)); sa_in.sin_family = AF_INET; sa_in.sin_port = htons(port); #if !defined(OS_WINDOWS) struct timespec tm; tm.tv_sec = 0; tm.tv_nsec = (TSLEEP * 1000); #endif /* resolve the hostname */ if ( (infh = gethostbyname(host)) != NULL ) memcpy(&sa_in.sin_addr, infh->h_addr, infh->h_length); else { if ( inet_aton(host, (struct in_addr *)&sa_in.sin_addr.s_addr) == 0 ) return -ENOADDRESS; } /* open the socket */ if ( (sh = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -EFATAL; /* set nonblocking socket */ set_blocking(sh, 0); do { /* connect to the server */ ret = connect(sh, (struct sockaddr *)&sa_in, sizeof(sa_in)); /* connect is in progress... */ if (ret < 0) { err = GET_SOCK_ERRNO(); if (err == EINPROGRESS || err == EALREADY || err == EWOULDBLOCK || err == EAGAIN) { /* sleep a quirk of time... */ DEBUG_MSG("open_socket: connect() retrying: %d", err); #if !defined(OS_WINDOWS) nanosleep(&tm, NULL); #else usleep(TSLEEP); #endif } } else { /* there was an error or the connect was successful */ break; } } while(loops--); /* * we cannot recall get_sock_errno because under windows * calling it twice would not return the same result */ err = ret < 0 ? err : 0; /* reached the timeout */ if (ret < 0 && (err == EINPROGRESS || err == EALREADY || err == EAGAIN)) { DEBUG_MSG("open_socket: connect() timeout: %d", err); close_socket(sh); return -ETIMEOUT; } /* error while connecting */ if (ret < 0 && err != EISCONN) { DEBUG_MSG("open_socket: connect() error: %d", err); close_socket(sh); return -EINVALID; } DEBUG_MSG("open_socket: connect() connected."); /* reset the state to blocking socket */ set_blocking(sh, 1); DEBUG_MSG("open_socket: %d", sh); return sh; }
int JThread::Start() { int status; if (!mutexinit) { if (!runningmutex.IsInitialized()) { if (runningmutex.Init() < 0) return ERR_JTHREAD_CANTINITMUTEX; } if (!continuemutex.IsInitialized()) { if (continuemutex.Init() < 0) return ERR_JTHREAD_CANTINITMUTEX; } if (!continuemutex2.IsInitialized()) { if (continuemutex2.Init() < 0) return ERR_JTHREAD_CANTINITMUTEX; } mutexinit = true; } runningmutex.Lock(); if (running) { runningmutex.Unlock(); return ERR_JTHREAD_ALREADYRUNNING; } runningmutex.Unlock(); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); continuemutex.Lock(); status = pthread_create(&threadid,&attr,TheThread,this); pthread_attr_destroy(&attr); if (status != 0) { continuemutex.Unlock(); return ERR_JTHREAD_CANTSTARTTHREAD; } /* Wait until 'running' is set */ runningmutex.Lock(); while (!running) { runningmutex.Unlock(); struct timespec req,rem; req.tv_sec = 0; req.tv_nsec = 1000000; nanosleep(&req,&rem); runningmutex.Lock(); } runningmutex.Unlock(); continuemutex.Unlock(); continuemutex2.Lock(); continuemutex2.Unlock(); return 0; }
void fd_runtime_run(void* arg) { FDRuntime* self = FD_RUNTIME(arg); struct timespec interval, remainder; interval.tv_sec = 0; interval.tv_nsec = 49910000; //~50ms; unsigned short int x; int errorCode = 0; gboolean firstRun = TRUE; int captureState = CAPTURE_WAITING; //int lastCaptureState = -1; gboolean samplingStarted = FALSE; TriggerMode lastTriggerMode = (TriggerMode) -1; while (!fd_runtime_getdeviceisconnected(self)) { sched_yield(); nanosleep(&interval, &remainder); sched_yield(); } while (captureState != LIBUSB_ERROR_NO_DEVICE && !fd_runtime_getstoprunning(self)) { pthread_mutex_lock(&FD_DEVICE(self->device)->deviceMutex); for (x = 0; x < COMMAND_COUNT; x++) { if (self->commandPending[x]) { fd_device_sendcommand(FD_DEVICE(self->device), self->commands[x]); self->commandPending[x] = FALSE; } } for (x = 0; x < CONTROLINDEX_COUNT; x++) { if (self->controlPending[x]) { fd_device_sendcontrol(FD_DEVICE(self->device), self->controls[x]); self->controlPending[x] = FALSE; } } pthread_mutex_unlock(&FD_DEVICE(self->device)->deviceMutex); sched_yield(); nanosleep(&interval, &remainder); if(!self->sampling) { samplingStarted = FALSE; sched_yield(); continue; //skip the rest of the loop. } sched_yield(); pthread_mutex_lock(&FD_DEVICE(self->device)->deviceMutex); //lastCaptureState = captureState; if (!firstRun) captureState = fd_runtime_getcapturestate(self); //if(captureState != lastCaptureState) //g_message("Capture state changed to %i", captureState); switch(captureState) { case CAPTURE_READY: case CAPTURE_READY5200: // Get data and process it, if we're still sampling errorCode = getSamples(self, samplingStarted); if(errorCode < 0) g_message("Getting sample data failed: %i", errorCode); // Check if we're in single trigger mode if(self->triggerMode == TRIGGERMODE_SINGLE && samplingStarted) fd_runtime_stopsampling(self); // Sampling completed, restart it when necessary samplingStarted = FALSE; // Start next capture if necessary by leaving out the break statement if(!self->sampling) break; case CAPTURE_WAITING: if(samplingStarted && lastTriggerMode == self->triggerMode) break; if (firstRun) firstRun = FALSE; // Start capturing errorCode = fd_device_sendcommand(FD_DEVICE(self->device), self->commands[COMMAND_STARTSAMPLING]); if(errorCode < 0) { if(errorCode == LIBUSB_ERROR_NO_DEVICE) captureState = LIBUSB_ERROR_NO_DEVICE; break; } //g_message("Starting to capture"); // Enable trigger errorCode = fd_device_sendcommand(FD_DEVICE(self->device), self->commands[COMMAND_ENABLETRIGGER]); if(errorCode < 0) { if(errorCode == LIBUSB_ERROR_NO_DEVICE) captureState = LIBUSB_ERROR_NO_DEVICE; break; } //g_message("Enabling trigger"); if(self->triggerMode == TRIGGERMODE_AUTO) { // Force triggering errorCode = fd_device_sendcommand(FD_DEVICE(self->device), self->commands[COMMAND_FORCETRIGGER]); if(errorCode == LIBUSB_ERROR_NO_DEVICE) captureState = LIBUSB_ERROR_NO_DEVICE; //g_message("Forcing trigger"); } samplingStarted = TRUE; lastTriggerMode = self->triggerMode; break; case CAPTURE_SAMPLING: break; default: if(captureState < 0) g_message("Getting capture state failed: %i", captureState); break; } pthread_mutex_unlock(&FD_DEVICE(self->device)->deviceMutex); } }
static void nsleep(uint64_t n) { struct timespec timeout; timeout.tv_sec = n/1000000000; timeout.tv_nsec = n%1000000000; while (nanosleep(&timeout, &timeout) && errno == EINTR); }
void iC_quit(int sig) { #ifdef RASPBERRYPI sig = (*iC_term)(sig); /* clear and unexport RASPBERRYPI stuff */ #endif /* RASPBERRYPI */ /******************************************************************** * The following termination function is an empty function * in the libict.a support library. * int iCend(void) { return -1; } * It may be implemented in a literal block of an iC source, in * which case that function will be linked in preference. * User implementations of iCend() should return 0, to activate * the debug message "== iCend complete ======". * * It can be used to free allocated memory, etc. * * If the iCbegin() function contains a fork() call, iCend() may have * a matching wait() call. *******************************************************************/ if ((sig >= QUIT_TERMINAL || sig == SIGINT) && iCend() != -1 /* iC termination function */ ) { #if YYDEBUG if (iC_debug & 0100) { fprintf(iC_outFP, "\n== iCend complete ======\n"); } #endif /* YYDEBUG */ } #ifdef TCP if (iC_sockFN > 0) { if (sig < SIGUSR1 || sig == QUIT_TERMINAL || sig == QUIT_DEBUGGER) { /* but not QUIT_SERVER */ #ifdef LOAD if (C_channel) { /* disconnect iClive - follow with '0' for iCserver */ snprintf(regBuf, REQUEST, "%hu:5,%hu:0", C_channel, C_channel); iC_send_msg_to_server(iC_sockFN, regBuf); #ifdef WIN32 Sleep(200); /* 200 ms in ms */ #else /* WIN32 */ nanosleep(&ms200, NULL); #endif /* WIN32 */ if (iC_micro) iC_microPrint("Disconnected", 0); } #endif /* LOAD */ if (iC_Xflag) { /* stop iCserver if this process started it */ snprintf(regBuf, REQUEST, "X%s", iC_iccNM); iC_send_msg_to_server(iC_sockFN, regBuf); } iC_send_msg_to_server(iC_sockFN, ""); /* 0 length message to disconnect from iCserver */ } close(iC_sockFN); /* close connection to iCserver */ } #endif /* TCP */ /******************************************************************** * Normal quit *******************************************************************/ fflush(iC_outFP); /* in case dangling debug messages without CR */ if (iC_outFP != stdout) { fclose(iC_outFP); } if ((iC_debug & DQ) == 0) { if (sig == QUIT_TERMINAL) { fprintf(iC_errFP, "\n'%s' stopped from terminal\n", iC_iccNM); } else if (sig == QUIT_DEBUGGER) { fprintf(iC_errFP, "\n'%s' stopped by debugger\n", iC_iccNM); } else if (sig == QUIT_SERVER) { fprintf(iC_errFP, "\n'%s' disconnected by server\n", iC_iccNM); } } if (sig == SIGINT) { fprintf(iC_errFP, "\n'%s' stopped by interrupt from terminal\n", iC_iccNM); } else if (sig == SIGSEGV) { fprintf(iC_errFP, "\n'%s' stopped by 'Invalid memory reference'\n", iC_iccNM); } else if (sig == SIGUSR1) { fprintf(iC_errFP, "\n'%s' stopped by 'non-recoverable run-time error'\n", iC_iccNM); } #if defined(TCP) && defined(LOAD) if (iC_savFP) { fflush(iC_savFP); fclose(iC_savFP); } if (iC_vcdFP) { fflush(iC_vcdFP); fclose(iC_vcdFP); } #endif /* defined(TCP) && defined(LOAD) */ #ifdef _MSDOS_ if (oldhandler && iC_debug & 03000) { /* reset the old interrupt handler */ #ifdef MSC _dos_setvect(INTR, oldhandler); #else /* MSC */ setvect(INTR, oldhandler); #endif /* MSC */ } #else /* ! _MSDOS_ Linux */ if (ttyparmFlag) { if (tcsetattr(0, TCSAFLUSH, &ttyparms) == -1) exit(-1); } #endif /* ! _MSDOS_ Linux */ if (iC_errFP != stderr) { fflush(iC_errFP); fclose(iC_errFP); } #if defined(TCP) && defined(EFENCE) free(rpyBuf); free(regBuf); #ifdef LOAD free(msgBuf); free(iC_outBuf); #endif /* LOAD */ #endif /* defined(TCP) && defined(EFENCE) */ exit(sig < QUIT_TERMINAL ? sig : 0); /* really quit */ } /* iC_quit */