Advertisement
Guest User

PiFM

a guest
May 25th, 2015
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 20.78 KB | None | 0 0
  1. // To run:
  2. //  g++ -O3 -o pifm pifm.c
  3. //  ./pifm left_right.wav 103.3 22050 stereo
  4. //  ./pifm sound.wav
  5.  
  6. // Created by Oliver Mattos and Oskar Weigl.
  7. // Code quality = Totally hacked together.
  8.  
  9.  
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include <dirent.h>
  14. #include <math.h>
  15. #include <fcntl.h>
  16. #include <assert.h>
  17. #include <malloc.h>
  18. #include <sys/mman.h>
  19. #include <sys/types.h>
  20. #include <sys/stat.h>
  21. #include <sys/time.h>
  22. #include <signal.h>
  23. #include <unistd.h>
  24.  
  25. #define PAGE_SIZE (4*1024)
  26. #define BLOCK_SIZE (4*1024)
  27.  
  28. #define PI 3.14159265
  29.  
  30. int  mem_fd;
  31. char *gpio_mem, *gpio_map;
  32. char *spi0_mem, *spi0_map;
  33.  
  34.  
  35. // I/O access
  36. volatile unsigned *gpio;
  37. volatile unsigned *allof7e;
  38.  
  39. // GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y)
  40. #define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
  41. #define OUT_GPIO(g) *(gpio+((g)/10)) |=  (1<<(((g)%10)*3))
  42. #define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))
  43.  
  44. #define GPIO_SET *(gpio+7)  // sets   bits which are 1 ignores bits which are 0
  45. #define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
  46. #define GPIO_GET *(gpio+13)  // sets   bits which are 1 ignores bits which are 0
  47.  
  48. #define ACCESS(base) *(volatile int*)((int)allof7e+base-0x7e000000)
  49. #define SETBIT(base, bit) ACCESS(base) |= 1<<bit
  50. #define CLRBIT(base, bit) ACCESS(base) &= ~(1<<bit)
  51.  
  52. #define CM_GP0CTL (0x7e101070)
  53. #define GPFSEL0 (0x7E200000)
  54. #define CM_GP0DIV (0x7e101074)
  55. #define CLKBASE (0x7E101000)
  56. #define DMABASE (0x7E007000)
  57. #define PWMBASE  (0x7e20C000) /* PWM controller */
  58.  
  59.  
  60. struct GPCTL {
  61.     char SRC         : 4;
  62.     char ENAB        : 1;
  63.     char KILL        : 1;
  64.     char             : 1;
  65.     char BUSY        : 1;
  66.     char FLIP        : 1;
  67.     char MASH        : 2;
  68.     unsigned int     : 13;
  69.     char PASSWD      : 8;
  70. };
  71.  
  72.  
  73.  
  74. void getRealMemPage(void** vAddr, void** pAddr) {
  75.     void* a = valloc(4096);
  76.  
  77.     ((int*)a)[0] = 1;  // use page to force allocation.
  78.  
  79.     mlock(a, 4096);  // lock into ram.
  80.  
  81.     *vAddr = a;  // yay - we know the virtual address
  82.  
  83.     unsigned long long frameinfo;
  84.  
  85.     int fp = open("/proc/self/pagemap", 'r');
  86.     lseek(fp, ((int)a)/4096*8, SEEK_SET);
  87.     read(fp, &frameinfo, sizeof(frameinfo));
  88.  
  89.     *pAddr = (void*)((int)(frameinfo*4096));
  90. }
  91.  
  92. void freeRealMemPage(void* vAddr) {
  93.  
  94.     munlock(vAddr, 4096);  // unlock ram.
  95.  
  96.     free(vAddr);
  97. }
  98.  
  99. void setup_fm()
  100. {
  101.  
  102.     /* open /dev/mem */
  103.     if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
  104.         printf("can't open /dev/mem \n");
  105.         exit (-1);
  106.     }
  107.  
  108.     allof7e = (unsigned *)mmap(
  109.                   NULL,
  110.                   0x01000000,  //len
  111.                   PROT_READ|PROT_WRITE,
  112.                   MAP_SHARED,
  113.                   mem_fd,
  114.                   0x20000000  //base
  115.               );
  116.  
  117.     if ((int)allof7e==-1) exit(-1);
  118.  
  119.     SETBIT(GPFSEL0 , 14);
  120.     CLRBIT(GPFSEL0 , 13);
  121.     CLRBIT(GPFSEL0 , 12);
  122.  
  123.  
  124.     struct GPCTL setupword = {6/*SRC*/, 1, 0, 0, 0, 1,0x5a};
  125.  
  126.     ACCESS(CM_GP0CTL) = *((int*)&setupword);
  127. }
  128.  
  129.  
  130. void modulate(int m)
  131. {
  132.     ACCESS(CM_GP0DIV) = (0x5a << 24) + 0x4d72 + m;
  133. }
  134.  
  135. struct CB {
  136.     volatile unsigned int TI;
  137.     volatile unsigned int SOURCE_AD;
  138.     volatile unsigned int DEST_AD;
  139.     volatile unsigned int TXFR_LEN;
  140.     volatile unsigned int STRIDE;
  141.     volatile unsigned int NEXTCONBK;
  142.     volatile unsigned int RES1;
  143.     volatile unsigned int RES2;
  144.  
  145. };
  146.  
  147. struct DMAregs {
  148.     volatile unsigned int CS;
  149.     volatile unsigned int CONBLK_AD;
  150.     volatile unsigned int TI;
  151.     volatile unsigned int SOURCE_AD;
  152.     volatile unsigned int DEST_AD;
  153.     volatile unsigned int TXFR_LEN;
  154.     volatile unsigned int STRIDE;
  155.     volatile unsigned int NEXTCONBK;
  156.     volatile unsigned int DEBUG;
  157. };
  158.  
  159. struct PageInfo {
  160.     void* p;  // physical address
  161.     void* v;   // virtual address
  162. };
  163.  
  164. struct PageInfo constPage;
  165. struct PageInfo instrPage;
  166. #define BUFFERINSTRUCTIONS 65536
  167. struct PageInfo instrs[BUFFERINSTRUCTIONS];
  168.  
  169.  
  170.  
  171. class SampleSink{
  172. public:
  173.     virtual void consume(float* data, int dataLen){};  // floating point samples
  174.     virtual void consume(void* data, int dataLen){};  // raw data, len in bytes.
  175. };
  176.  
  177. class Outputter : public SampleSink {
  178. public:
  179.     int bufPtr;
  180.     float clocksPerSample;
  181.     const int sleeptime;
  182.     float fracerror;
  183.     float timeErr;
  184.  
  185.     Outputter(float rate):
  186.         sleeptime((float)1e6 * BUFFERINSTRUCTIONS/4/rate/2),   // sleep time is half of the time to empty the buffer
  187.         fracerror(0),
  188.         timeErr(0) {
  189.         clocksPerSample = 22500.0 / rate * 1373.5;  // for timing, determined by experiment
  190.         bufPtr=0;
  191.     };
  192.     void consume(float* data, int num) {
  193.         for (int i=0; i<num; i++) {
  194.             float value = data[i]*8;  // modulation index (AKA volume!)
  195.  
  196.             // dump raw baseband data to stdout for audacity analysis.
  197.             //write(1, &value, 4);
  198.  
  199.             // debug code.  Replaces data with a set of tones.
  200.             //static int debugCount;
  201.             //debugCount++;
  202.             //value = (debugCount & 0x1000)?0.5:0;  // two different tests
  203.             //value += 0.2 * ((debugCount & 0x8)?1.0:-1.0);   // tone
  204.             //if (debugCount & 0x2000) value = 0;   // silence
  205.             // end debug code
  206.  
  207.             value += fracerror;  // error that couldn't be encoded from last time.
  208.  
  209.             int intval = (int)(round(value));  // integer component
  210.             float frac = (value - (float)intval + 1)/2;
  211.             unsigned int fracval = round(frac*clocksPerSample); // the fractional component
  212.  
  213.             // we also record time error so that if one sample is output
  214.             // for slightly too long, the next sample will be shorter.
  215.             timeErr = timeErr - int(timeErr) + clocksPerSample;
  216.  
  217.             fracerror = (frac - (float)fracval*(1.0-2.3/clocksPerSample)/clocksPerSample)*2;  // error to feed back for delta sigma
  218.  
  219.             // Note, the 2.3 constant is because our PWM isn't perfect.
  220.             // There is a finite time for the DMA controller to load a new value from memory,
  221.             // Therefore the width of each pulse we try to insert has a constant added to it.
  222.             // That constant is about 2.3 bytes written to the serializer, or about 18 cycles.  We use delta sigma
  223.             // to correct for this error and the pwm timing quantization error.
  224.  
  225.             // To reduce noise, rather than just rounding to the nearest clock we can use, we PWM between
  226.             // the two nearest values.
  227.  
  228.             // delay if necessary.  We can also print debug stuff here while not breaking timing.
  229.             static int time;
  230.             time++;
  231.  
  232.             while( (ACCESS(DMABASE + 0x04 /* CurBlock*/) & ~ 0x7F) ==  (int)(instrs[bufPtr].p)) {
  233.                 usleep(sleeptime);  // are we anywhere in the next 4 instructions?
  234.             }
  235.  
  236.             // Create DMA command to set clock controller to output FM signal for PWM "LOW" time.
  237.             ((struct CB*)(instrs[bufPtr].v))->SOURCE_AD = (int)constPage.p + 2048 + intval*4 - 4 ;
  238.             bufPtr++;
  239.  
  240.             // Create DMA command to delay using serializer module for suitable time.
  241.             ((struct CB*)(instrs[bufPtr].v))->TXFR_LEN = (int)timeErr-fracval;
  242.             bufPtr++;
  243.  
  244.             // Create DMA command to set clock controller to output FM signal for PWM "HIGH" time.
  245.             ((struct CB*)(instrs[bufPtr].v))->SOURCE_AD = (int)constPage.p + 2048 + intval*4 + 4;
  246.             bufPtr++;
  247.  
  248.             // Create DMA command for more delay.
  249.             ((struct CB*)(instrs[bufPtr].v))->TXFR_LEN = fracval;
  250.             bufPtr=(bufPtr+1) % (BUFFERINSTRUCTIONS);
  251.         }
  252.     }
  253. };
  254.  
  255. class PreEmp : public SampleSink {
  256. public:
  257.     float fmconstant;
  258.     float dataold;
  259.     SampleSink* next;
  260.  
  261.     // this isn't the right filter...  But it's close...
  262.     // Something todo with a bilinear transform not being right...
  263.     PreEmp(float rate, SampleSink* next):
  264.         fmconstant(rate * 75.0e-6), // for pre-emphisis filter.  75us time constant
  265.         dataold(0),
  266.         next(next) { };
  267.  
  268.  
  269.     void consume(float* data, int num) {
  270.         for (int i=0; i<num; i++) {
  271.             float value = data[i];
  272.  
  273.             float sample = value + (dataold-value) / (1-fmconstant);  // fir of 1 + s tau
  274.  
  275.             next->consume(&sample, 1);
  276.  
  277.             dataold = value;
  278.         }
  279.     }
  280. };
  281.  
  282.  
  283. class Resamp : public SampleSink {
  284. public:
  285.     static const int QUALITY = 5;    // comp. complexity goes up linearly with this.
  286.     static const int SQUALITY = 10;  // start time quality (defines max phase error of filter vs ram used & cache thrashing)
  287.     static const int BUFSIZE = 1000;
  288.     float dataOld[QUALITY];
  289.     float sincLUT[SQUALITY][QUALITY]; // [startime][samplenum]
  290.     float ratio;
  291.     float outTimeLeft;
  292.     float outBuffer[BUFSIZE];
  293.     int outBufPtr;
  294.     SampleSink* next;
  295.  
  296.     Resamp(float rateIn, float rateOut, SampleSink* next):
  297.         outTimeLeft(1.0),
  298.         outBufPtr(0),
  299.         ratio((float)rateIn/(float)rateOut),
  300.         next(next) {
  301.  
  302.         for(int i=0; i<QUALITY; i++) {  // sample
  303.           for(int j=0; j<SQUALITY; j++) {  // starttime
  304.             float x = PI * ((float)j/SQUALITY + (QUALITY-1-i) - (QUALITY-1)/2.0);
  305.             if (x==0)
  306.               sincLUT[j][i] = 1.0;  // sin(0)/(0) == 1, says my limits therory
  307.             else
  308.               sincLUT[j][i] = sin(x)/x;
  309.           }
  310.         }
  311.  
  312.     };
  313.  
  314.  
  315.     void consume(float* data, int num) {
  316.         for (int i=0; i<num; i++) {
  317.             // shift old data along
  318.             for (int j=0; j<QUALITY-1; j++) {
  319.               dataOld[j] = dataOld[j+1];
  320.             }
  321.  
  322.             // put in new sample
  323.             dataOld[QUALITY-1] = data[i];
  324.             outTimeLeft -= 1.0;
  325.  
  326.             // go output this stuff!
  327.             while (outTimeLeft<1.0) {
  328.                 float outSample = 0;
  329.                 int lutNum = (int)(outTimeLeft*SQUALITY);
  330.                 for (int j=0; j<QUALITY; j++) {
  331.                     outSample += dataOld[j] * sincLUT[lutNum][j];
  332.                 }
  333.                 outBuffer[outBufPtr++] = outSample;
  334.                 outTimeLeft += ratio;
  335.  
  336.                 // if we have lots of data, shunt it to the next stage.
  337.                 if (outBufPtr >= BUFSIZE) {
  338.                   next->consume(outBuffer, outBufPtr);
  339.                   outBufPtr = 0;
  340.                 }
  341.             }
  342.         }
  343.     }
  344. };
  345.  
  346. class NullSink: public SampleSink {
  347. public:
  348.  
  349.     NullSink() { }
  350.  
  351.     void consume(float* data, int num) {}   // throws away data
  352. };
  353.  
  354. // decodes a mono wav file
  355. class Mono: public SampleSink {
  356. public:
  357.     SampleSink* next;
  358.  
  359.     Mono(SampleSink* next): next(next) { }
  360.  
  361.     void consume(void* data, int num) {    // expects num%2 == 0
  362.         for (int i=0; i<num/2; i++) {
  363.             float l = (float)(((short*)data)[i]) / 32768.0;
  364.             next->consume( &l, 1);
  365.         }
  366.     }
  367. };
  368.  
  369. class StereoSplitter: public SampleSink {
  370. public:
  371.     SampleSink* nextLeft;
  372.     SampleSink* nextRight;
  373.  
  374.     StereoSplitter(SampleSink* nextLeft, SampleSink* nextRight):
  375.         nextLeft(nextLeft), nextRight(nextRight) { }
  376.  
  377.  
  378.     void consume(void* data, int num) {    // expects num%4 == 0
  379.         for (int i=0; i<num/2; i+=2) {
  380.             float l = (float)(((short*)data)[i]) / 32768.0;
  381.             nextLeft->consume( &l, 1);
  382.  
  383.             float r = (float)(((short*)data)[i+1]) / 32768.0;
  384.             nextRight->consume( &r, 1);
  385.         }
  386.     }
  387. };
  388.  
  389.  
  390. const unsigned char RDSDATA[] = {
  391. // RDS data.  Send MSB first.  Google search gr_rds_data_encoder.cc to make your own data.
  392.     0x50, 0xFF, 0xA9, 0x01, 0x02, 0x1E, 0xB0, 0x00, 0x05, 0xA1, 0x41, 0xA4, 0x12,
  393.     0x50, 0xFF, 0xA9, 0x01, 0x02, 0x45, 0x20, 0x00, 0x05, 0xA1, 0x19, 0xB6, 0x8C,
  394.     0x50, 0xFF, 0xA9, 0x01, 0x02, 0xA9, 0x90, 0x00, 0x05, 0xA0, 0x80, 0x80, 0xDC,
  395.     0x50, 0xFF, 0xA9, 0x01, 0x03, 0xC7, 0xD0, 0x00, 0x05, 0xA0, 0x80, 0x80, 0xDC,
  396.     0x50, 0xFF, 0xA9, 0x09, 0x00, 0x14, 0x75, 0x47, 0x51, 0x7D, 0xB9, 0x95, 0x79,
  397.     0x50, 0xFF, 0xA9, 0x09, 0x00, 0x4F, 0xE7, 0x32, 0x02, 0x21, 0x99, 0xC8, 0x09,
  398.     0x50, 0xFF, 0xA9, 0x09, 0x00, 0xA3, 0x56, 0xF6, 0xD9, 0xE8, 0x81, 0xE5, 0xEE,
  399.     0x50, 0xFF, 0xA9, 0x09, 0x00, 0xF8, 0xC6, 0xF7, 0x5B, 0x19, 0xC8, 0x80, 0x88,
  400.     0x50, 0xFF, 0xA9, 0x09, 0x01, 0x21, 0xA5, 0x26, 0x19, 0xD5, 0xCD, 0xC3, 0xDC,
  401.     0x50, 0xFF, 0xA9, 0x09, 0x01, 0x7A, 0x36, 0x26, 0x56, 0x31, 0xC9, 0xC8, 0x72,
  402.     0x50, 0xFF, 0xA9, 0x09, 0x01, 0x96, 0x87, 0x92, 0x09, 0xA5, 0x41, 0xA4, 0x12,
  403.     0x50, 0xFF, 0xA9, 0x09, 0x01, 0xCD, 0x12, 0x02, 0x8C, 0x0D, 0xBD, 0xB6, 0xA6,
  404.     0x50, 0xFF, 0xA9, 0x09, 0x02, 0x24, 0x46, 0x17, 0x4B, 0xB9, 0xD1, 0xBC, 0xE2,
  405.     0x50, 0xFF, 0xA9, 0x09, 0x02, 0x7F, 0xD7, 0x34, 0x09, 0xE1, 0x9D, 0xB5, 0xFF,
  406.     0x50, 0xFF, 0xA9, 0x09, 0x02, 0x93, 0x66, 0x16, 0x92, 0xD9, 0xB0, 0xB9, 0x3E,
  407.     0x50, 0xFF, 0xA9, 0x09, 0x02, 0xC8, 0xF6, 0x36, 0xF4, 0x85, 0xB4, 0xA4, 0x74,
  408.     0x50, 0xFF, 0xA9, 0x09, 0x03, 0x11, 0x92, 0x02, 0x00, 0x00, 0x80, 0x80, 0xDC,
  409.     0x50, 0xFF, 0xA9, 0x09, 0x03, 0x4A, 0x02, 0x02, 0x00, 0x00, 0x80, 0x80, 0xDC,
  410.     0x50, 0xFF, 0xA9, 0x09, 0x03, 0xA6, 0xB2, 0x02, 0x00, 0x00, 0x80, 0x80, 0xDC,
  411.     0x50, 0xFF, 0xA9, 0x09, 0x03, 0xFD, 0x22, 0x02, 0x00, 0x00, 0x80, 0x80, 0xDC
  412. };
  413.  
  414. class RDSEncoder: public SampleSink {
  415. public:
  416.     float sinLut[8];
  417.     SampleSink* next;
  418.     int bitNum;
  419.     int lastBit;
  420.     int time;
  421.     float lastValue;
  422.  
  423.     RDSEncoder(SampleSink* next):
  424.         next(next), bitNum(0), lastBit(0), time(0), lastValue(0) {
  425.         for (int i=0; i<8; i++) {
  426.             sinLut[i] = sin((float)i*2.0*PI*3/8);
  427.         }
  428.     }
  429.  
  430.     void consume(float* data, int num) {
  431.         for (int i=0; i<num; i++) {
  432.             if (!time) {
  433.               // time for a new bit
  434.               int newBit = (RDSDATA[bitNum/8]>>(7-(bitNum%8)))&1;
  435.               lastBit = lastBit^newBit;  // differential encoding
  436.  
  437.               bitNum = (bitNum+1)%(20*13*8);
  438.             }
  439.  
  440.             int outputBit = (time<192)?lastBit:1-lastBit; // manchester encoding
  441.  
  442.             lastValue = lastValue*0.99 + (((float)outputBit)*2-1)*0.01;  // very simple IIR filter to hopefully reduce sidebands.
  443.             data[i] += lastValue*sinLut[time%8]*0.05;
  444.  
  445.             time = (time+1)%384;
  446.         }
  447.         next->consume(data, num);
  448.     }
  449. };
  450.  
  451. // Takes 2 input signals at 152kHz and stereo modulates it.
  452. class StereoModulator: public SampleSink {
  453. public:
  454.  
  455.     // Helper to make two input interfaces for the stereomodulator.   Feels like I'm reimplementing a closure here... :-(
  456.     class ModulatorInput: public SampleSink {
  457.     public:
  458.         StereoModulator* mod;
  459.         int channel;
  460.  
  461.         ModulatorInput(StereoModulator* mod, int channel):
  462.             mod(mod),
  463.             channel(channel) { }
  464.  
  465.         void consume(float* data, int num) {
  466.             mod->consume(data, num, channel);
  467.         }
  468.     };
  469.  
  470.     float buffer[1024];
  471.     int bufferOwner;
  472.     int bufferLen;
  473.     int state; // 8 state state machine.
  474.     float sinLut[16];
  475.  
  476.     SampleSink* next;
  477.  
  478.     StereoModulator(SampleSink* next):
  479.         next(next), bufferOwner(0), bufferLen(0), state(0) {
  480.         for (int i=0; i<16; i++) {
  481.             sinLut[i] = sin((float)i*2.0*PI/8);
  482.         }
  483.     }
  484.  
  485.     SampleSink* getChannel(int channel) {
  486.         return new ModulatorInput(this, channel);  // never freed, cos I'm a rebel...
  487.     }
  488.  
  489.     void consume(float* data, int num, int channel) {
  490.         if (channel==bufferOwner || bufferLen==0) {
  491.             bufferOwner=channel;
  492.             // append to buffer
  493.             while(num && bufferLen<1024) {
  494.                 buffer[bufferLen++] = data[0];
  495.                 data++;
  496.                 num--;
  497.             }
  498.         } else {
  499.             int consumable = (bufferLen<num)?bufferLen:num;
  500.             float* left = (bufferOwner==0)?buffer:data;
  501.             float* right = (bufferOwner==1)?buffer:data;
  502.             for (int i=0; i<consumable; i++) {
  503.                 state = (state+1) %8;
  504.                 // equation straight from wikipedia...
  505.                 buffer[i] = ((left[i]+right[i])/2 + (left[i]-right[i])/2*sinLut[state*2])*0.9 + 0.1*sinLut[state];
  506.             }
  507.             next->consume(buffer, consumable);
  508.  
  509.             // move stuff along buffer
  510.             for (int i=consumable; i<bufferLen; i++) {
  511.               buffer[i-consumable] = buffer[i];
  512.             }
  513.             bufferLen-=consumable;
  514.  
  515.             //reconsume any remaining data
  516.             data += consumable;
  517.             num -= consumable;
  518.             consume(data, num, channel);
  519.         }
  520.     }
  521. };
  522.  
  523.  
  524. void playWav(char* filename, float samplerate, bool stereo)
  525. {
  526.     int fp= STDIN_FILENO;
  527.     if(filename[0]!='-') fp = open(filename, 'r');
  528.  
  529.     char data[1024];
  530.  
  531.     SampleSink* ss;
  532.  
  533.     if (stereo) {
  534.       StereoModulator* sm = new StereoModulator(new RDSEncoder(new Outputter(152000)));
  535.       ss = new StereoSplitter(
  536.         // left
  537.         new PreEmp(samplerate, new Resamp(samplerate, 152000, sm->getChannel(0))),
  538.  
  539.         // Right
  540.         new PreEmp(samplerate, new Resamp(samplerate, 152000, sm->getChannel(1)))
  541.       );
  542.     } else {
  543.       ss = new Mono(new PreEmp(samplerate, new Outputter(samplerate)));
  544.     }
  545.  
  546.     for (int i=0; i<22; i++)
  547.        read(fp, &data, 2);  // read past header
  548.  
  549.     int readBytes;
  550.     while (readBytes = read(fp, &data, 1024)) {
  551.  
  552.         ss->consume(data, readBytes);
  553.     }
  554.     close(fp);
  555. }
  556.  
  557. void unSetupDMA(){
  558.     printf("exiting\n");
  559.     struct DMAregs* DMA0 = (struct DMAregs*)&(ACCESS(DMABASE));
  560.     DMA0->CS =1<<31;  // reset dma controller
  561.  
  562. }
  563.  
  564. void handSig(int dunno) {
  565.     exit(0);
  566. }
  567. void setupDMA( float centerFreq ){
  568.  
  569.   atexit(unSetupDMA);
  570.   signal (SIGINT, handSig);
  571.   signal (SIGTERM, handSig);
  572.   signal (SIGHUP, handSig);
  573.   signal (SIGQUIT, handSig);
  574.  
  575.    // allocate a few pages of ram
  576.    getRealMemPage(&constPage.v, &constPage.p);
  577.  
  578.    int centerFreqDivider = (int)((500.0 / centerFreq) * (float)(1<<12) + 0.5);
  579.  
  580.    // make data page contents - it's essientially 1024 different commands for the
  581.    // DMA controller to send to the clock module at the correct time.
  582.    for (int i=0; i<1024; i++)
  583.      ((int*)(constPage.v))[i] = (0x5a << 24) + centerFreqDivider - 512 + i;
  584.  
  585.  
  586.    int instrCnt = 0;
  587.  
  588.    while (instrCnt<BUFFERINSTRUCTIONS) {
  589.      getRealMemPage(&instrPage.v, &instrPage.p);
  590.  
  591.      // make copy instructions
  592.      struct CB* instr0= (struct CB*)instrPage.v;
  593.  
  594.      for (int i=0; i<4096/sizeof(struct CB); i++) {
  595.        instrs[instrCnt].v = (void*)((int)instrPage.v + sizeof(struct CB)*i);
  596.        instrs[instrCnt].p = (void*)((int)instrPage.p + sizeof(struct CB)*i);
  597.        instr0->SOURCE_AD = (unsigned int)constPage.p+2048;
  598.        instr0->DEST_AD = PWMBASE+0x18 /* FIF1 */;
  599.        instr0->TXFR_LEN = 4;
  600.        instr0->STRIDE = 0;
  601.        //instr0->NEXTCONBK = (int)instrPage.p + sizeof(struct CB)*(i+1);
  602.        instr0->TI = (1/* DREQ  */<<6) | (5 /* PWM */<<16) |  (1<<26/* no wide*/) ;
  603.        instr0->RES1 = 0;
  604.        instr0->RES2 = 0;
  605.  
  606.        if (!(i%2)) {
  607.          instr0->DEST_AD = CM_GP0DIV;
  608.          instr0->STRIDE = 4;
  609.          instr0->TI = (1<<26/* no wide*/) ;
  610.        }
  611.  
  612.        if (instrCnt!=0) ((struct CB*)(instrs[instrCnt-1].v))->NEXTCONBK = (int)instrs[instrCnt].p;
  613.        instr0++;
  614.        instrCnt++;
  615.      }
  616.    }
  617.    ((struct CB*)(instrs[BUFFERINSTRUCTIONS-1].v))->NEXTCONBK = (int)instrs[0].p;
  618.  
  619.    // set up a clock for the PWM
  620.    ACCESS(CLKBASE + 40*4 /*PWMCLK_CNTL*/) = 0x5A000026;
  621.    usleep(1000);
  622.    ACCESS(CLKBASE + 41*4 /*PWMCLK_DIV*/)  = 0x5A002800;
  623.    ACCESS(CLKBASE + 40*4 /*PWMCLK_CNTL*/) = 0x5A000016;
  624.    usleep(1000);
  625.  
  626.    // set up pwm
  627.    ACCESS(PWMBASE + 0x0 /* CTRL*/) = 0;
  628.    usleep(1000);
  629.    ACCESS(PWMBASE + 0x4 /* status*/) = -1;  // clear errors
  630.    usleep(1000);
  631.    ACCESS(PWMBASE + 0x0 /* CTRL*/) = -1; //(1<<13 /* Use fifo */) | (1<<10 /* repeat */) | (1<<9 /* serializer */) | (1<<8 /* enable ch */) ;
  632.    usleep(1000);
  633.    ACCESS(PWMBASE + 0x8 /* DMAC*/) = (1<<31 /* DMA enable */) | 0x0707;
  634.  
  635.    //activate dma
  636.    struct DMAregs* DMA0 = (struct DMAregs*)&(ACCESS(DMABASE));
  637.    DMA0->CS =1<<31;  // reset
  638.    DMA0->CONBLK_AD=0;
  639.    DMA0->TI=0;
  640.    DMA0->CONBLK_AD = (unsigned int)(instrPage.p);
  641.    DMA0->CS =(1<<0)|(255 <<16);  // enable bit = 0, clear end flag = 1, prio=19-16
  642. }
  643.  
  644.  
  645.  
  646. int main(int argc, char **argv)
  647. {
  648.  
  649.     if (argc>1) {
  650.       setup_fm();
  651.       setupDMA(argc>2?atof(argv[2]):103.3);
  652.       playWav(argv[1], argc>3?atof(argv[3]):22050, argc>4);
  653.     } else
  654.       fprintf(stderr, "Usage:   program wavfile.wav [freq] [sample rate] [stereo]\n\nWhere wavfile is 16 bit 22.5kHz Stereo.  Set wavfile to '-' to use stdin.\nfreq is in Mhz (default 103.3)\nsample rate of wav file in Hz\n\nPlay an empty file to transmit silence\n");
  655.  
  656.     return 0;
  657.  
  658. } // main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement