summaryrefslogtreecommitdiff
path: root/util.c
blob: c998930c3c1386ff436f7a61140d89b7e0acb269 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

UNUSED
long
read_entire_file (const char *file_name, char **str)
{
  long file_size = 0;
    
  FILE *file = fopen(file_name, "r");
    
  if (!file) {
    fprintf(stderr, "Cannot open file \"%s\": ", file_name);
    perror(NULL);
    return 0;
  }

  fseek(file, 0, SEEK_END);
  file_size = ftell(file);
  fseek(file, 0, SEEK_SET);

  *str = (char*)realloc(*str, file_size+1);
  *((*str)+file_size) = 0;

  fread(*str, sizeof(char), file_size, file);
    
  fclose(file);  
  return file_size;
}

UC_ATTR
LENT
max(const LENT a, const LENT b)
{
  return (a < b) ? b : a;
}

U_ATTR
LENT
min(LENT a, LENT b)
{
  return (a < b) ? a : b;
}

U_ATTR
WaveFrag
mix_waves(WaveFrag *frags, LENT len)
{
  WaveFrag wf = (WaveFrag) { NULL, 0 };

  LENT max_len = 0;
  
  Pulse p = 0.0;

  for (LENT i = 0; i < len; i++)
    max_len = max(max_len, (frags+i)->n);

  wf.n = max_len;
  wf.w = MYALLOC(Pulse, max_len);
  
  for (LENT i = 0; i < max_len; i++) {
    p = 0.0;

    for (LENT j = 0; j < len; j++)
      if (i < (frags+j)->n) p += *((frags+j)->w+i);
    
    *(wf.w+i) = p / (float) len;
  }
  
  return wf;
}

HC_ATTR
Hertz
stoh(const Semitones st)
{
  return STDP * pow(STD_BASE, st);
}