title: Trying to decode a FM like signal encoded on audio
body: <p>I have an audio signal that has a kind of FM encoded signal on it. The encoded signal is using <a href="https://en.wikipedia.org/wiki/Differential_Manchester_encoding" rel="nofollow">this Biphase mark coding technique</a> &lt;-- see at the end of this page.</p>
  
  <p>This signal is a digital representation of a timecode, in hours, minutes, seconds and frames. It basically works like this: </p>
  
  <ol>
  <li>lets consider that we are working in 25 frames per second; </li>
  <li>we know that the code is transmitting 80 bits of information every frame (that is 80 bits per frame x 25 frames per second = 2000 bits per second);</li>
  <li>The wave is being sampled at 44100 samples per second. So, if we divide 44100/2000 we see that every bit uses 22,05 samples;</li>
  <li>A bit happens when the signal changes sign. </li>
  <li>If the wave changes sign and keeps its sign during the whole bit period it is a ZERO. If the wave changes sign two times over one bit period it is a ONE;</li>
  </ol>
  
  <p>What my code does is this:</p>
  
  <ol>
  <li>detects the first zero crossing, that is the clock start (to)</li>
  <li>measures the level for to = to + 0.75*bitPeriod... 0.75 to give a tolerance.</li>
  <li>if that second level is different, we have a 1, if not we have a 0;</li>
  </ol>
  
  <p>This is the code:</p>
  
  <pre><code>// data is a C array of floats representing the audio levels
  
  float bitPeriod = ceil(44100 / 2000);
  int firstZeroCrossIndex = findNextZeroCross(data);
  // firstZeroCrossIndex is the value where the signal changed
  // for example: data[0] = -0.23 and data[1] = 0.5
  // firstZeroCrossIndex will be equal to 1
  
  // if firstZeroCrossIndex is invalid, go away
  if (firstZeroCrossIndex &lt; 0) return 
  
  float firstValue = data[firstZeroCrossIndex];
  int lastSignal = sign(firstValue);
  
  if (lastSignal == 0) return; // invalid, go away
  
  while (YES) {
  
      float newValue = data[firstZeroCrossIndex + 0.75* bitPeriod];
      int newSignal = sign(newValue);
  
      if (lastSignal == newSignal)
        printf("0");
      else 
        printf("1");
  
      firstZeroCrossIndex += bitPeriod;
  
      // I think I must invert the signal here for the next loop interaction
      lastSignal = -newSignal;
  
      if (firstZeroCrossIndex &gt; maximuPossibleIndex)
        break;
  
  }
  </code></pre>
  
  <p>This code appears logical to me but the result coming from it is a total nonsense. What am I missing?</p>
  
  <p>NOTE: this code is executing over a live signal and reads values from a circular ring buffer. <code>sign</code> returns -1 if the value is negative, 1 if the value is positive or 0 if the value is zero.</p>