fix coverity CID 349306 - resource leak
[RRG-proxmark3.git] / common / lfdemod.c
blob3c32834f65047a55f5e21a39268924e006b8e943
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2014
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // Low frequency demod/decode commands - by marshmellow, holiman, iceman and
9 // many others who came before
11 // NOTES:
12 // LF Demod functions are placed here to allow the flexability to use client or
13 // device side. Most BUT NOT ALL of these functions are currenlty safe for
14 // device side use currently. (DetectST for example...)
16 // There are likely many improvements to the code that could be made, please
17 // make suggestions...
19 // we tried to include author comments so any questions could be directed to
20 // the source.
22 // There are 4 main sections of code below:
24 // Utilities Section:
25 // for general utilities used by multiple other functions
27 // Clock / Bitrate Detection Section:
28 // for clock detection functions for each modulation
30 // Modulation Demods &/or Decoding Section:
31 // for main general modulation demodulating and encoding decoding code.
33 // Tag format detection section:
34 // for detection of specific tag formats within demodulated data
36 // marshmellow
37 //-----------------------------------------------------------------------------
39 #include "lfdemod.h"
40 #include <string.h> // for memset, memcmp and size_t
41 #include <stdlib.h> // qsort
42 #include "parity.h" // for parity test
43 #include "pm3_cmd.h" // error codes
44 #include "commonutil.h" // Arraylen
46 // **********************************************************************************************
47 // ---------------------------------Utilities Section--------------------------------------------
48 // **********************************************************************************************
49 #define LOWEST_DEFAULT_CLOCK 32
50 #define FSK_PSK_THRESHOLD 123
52 //to allow debug print calls when used not on dev
54 #ifndef ON_DEVICE
55 #include "ui.h"
56 #include "util.h"
57 # include "cmddata.h"
58 # define prnt(args...) PrintAndLogEx(DEBUG, ## args );
59 #else
60 # include "dbprint.h"
61 uint8_t g_debugMode = 0;
62 # define prnt Dbprintf
63 #endif
65 signal_t signalprop = { 255, -255, 0, 0, true };
66 signal_t *getSignalProperties(void) {
67 return &signalprop;
70 static void resetSignal(void) {
71 signalprop.low = 255;
72 signalprop.high = -255;
73 signalprop.mean = 0;
74 signalprop.amplitude = 0;
75 signalprop.isnoise = true;
78 static void printSignal(void) {
79 prnt("LF signal properties:");
80 prnt(" high..........%d", signalprop.high);
81 prnt(" low...........%d", signalprop.low);
82 prnt(" mean..........%d", signalprop.mean);
83 prnt(" amplitude.....%d", signalprop.amplitude);
84 prnt(" is Noise......%s", (signalprop.isnoise) ? _RED_("Yes") : _GREEN_("No"));
85 prnt(" THRESHOLD noise amplitude......%d", NOISE_AMPLITUDE_THRESHOLD);
88 #ifndef ON_DEVICE
89 static int cmp_uint8(const void *a, const void *b) {
90 if (*(const uint8_t *)a < * (const uint8_t *)b)
91 return -1;
92 else
93 return *(const uint8_t *)a > *(const uint8_t *)b;
95 #endif
97 void computeSignalProperties(uint8_t *samples, uint32_t size) {
98 resetSignal();
100 if (samples == NULL || size < SIGNAL_MIN_SAMPLES) return;
102 uint32_t sum = 0;
103 uint32_t offset_size = size - SIGNAL_IGNORE_FIRST_SAMPLES;
105 #ifndef ON_DEVICE
106 uint8_t tmp[offset_size];
107 memcpy(tmp, samples + SIGNAL_IGNORE_FIRST_SAMPLES, sizeof(tmp));
108 qsort(tmp, sizeof(tmp), sizeof(uint8_t), cmp_uint8);
110 uint8_t low10 = 0.5 * (tmp[(int)(offset_size * 0.1)] + tmp[(int)((offset_size - 1) * 0.1)]);
111 uint8_t hi90 = 0.5 * (tmp[(int)(offset_size * 0.9)] + tmp[(int)((offset_size - 1) * 0.9)]);
112 uint32_t cnt = 0;
113 for (uint32_t i = SIGNAL_IGNORE_FIRST_SAMPLES; i < size; i++) {
115 if (samples[i] < signalprop.low) signalprop.low = samples[i];
116 if (samples[i] > signalprop.high) signalprop.high = samples[i];
118 if (samples[i] < low10 || samples[i] > hi90)
119 continue;
121 sum += samples[i];
122 cnt++;
124 if (cnt > 0)
125 signalprop.mean = sum / cnt;
126 else
127 signalprop.mean = 0;
128 #else
129 for (uint32_t i = SIGNAL_IGNORE_FIRST_SAMPLES; i < size; i++) {
130 if (samples[i] < signalprop.low) signalprop.low = samples[i];
131 if (samples[i] > signalprop.high) signalprop.high = samples[i];
132 sum += samples[i];
134 signalprop.mean = sum / offset_size;
135 #endif
137 // measure amplitude of signal
138 signalprop.amplitude = signalprop.high - signalprop.mean;
139 // By measuring mean and look at amplitude of signal from HIGH / LOW,
140 // we can detect noise
141 signalprop.isnoise = signalprop.amplitude < NOISE_AMPLITUDE_THRESHOLD;
143 if (g_debugMode)
144 printSignal();
147 void removeSignalOffset(uint8_t *samples, uint32_t size) {
148 if (samples == NULL || size < SIGNAL_MIN_SAMPLES) return;
150 int acc_off = 0;
151 uint32_t offset_size = size - SIGNAL_IGNORE_FIRST_SAMPLES;
153 #ifndef ON_DEVICE
155 uint8_t tmp[offset_size];
156 memcpy(tmp, samples + SIGNAL_IGNORE_FIRST_SAMPLES, sizeof(tmp));
157 qsort(tmp, sizeof(tmp), sizeof(uint8_t), cmp_uint8);
159 uint8_t low10 = 0.5 * (tmp[(int)(offset_size * 0.05)] + tmp[(int)((offset_size - 1) * 0.05)]);
160 uint8_t hi90 = 0.5 * (tmp[(int)(offset_size * 0.95)] + tmp[(int)((offset_size - 1) * 0.95)]);
161 int32_t cnt = 0;
162 for (uint32_t i = SIGNAL_IGNORE_FIRST_SAMPLES; i < size; i++) {
164 if (samples[i] < low10 || samples[i] > hi90)
165 continue;
167 acc_off += samples[i] - 128;
168 cnt++;
170 if (cnt > 0)
171 acc_off /= cnt;
172 else
173 acc_off = 0;
174 #else
175 for (uint32_t i = SIGNAL_IGNORE_FIRST_SAMPLES; i < size; i++)
176 acc_off += samples[i] - 128;
178 acc_off /= (int)offset_size;
179 #endif
181 // shift and saturate samples to center the mean
182 for (uint32_t i = 0; i < size; i++) {
183 if (acc_off > 0) {
184 samples[i] = (samples[i] >= acc_off) ? samples[i] - acc_off : 0;
186 if (acc_off < 0) {
187 samples[i] = (255 - samples[i] >= -acc_off) ? samples[i] - acc_off : 255;
192 //by marshmellow
193 //get high and low values of a wave with passed in fuzz factor. also return noise test = 1 for passed or 0 for only noise
194 //void getHiLo(uint8_t *bits, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo) {
195 void getHiLo(int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo) {
196 // add fuzz.
197 *high = (signalprop.high * fuzzHi) / 100;
198 if (signalprop.low < 0) {
199 *low = (signalprop.low * fuzzLo) / 100;
200 } else {
201 uint8_t range = signalprop.high - signalprop.low;
203 *low = signalprop.low + ((range * (100 - fuzzLo)) / 100);
206 // if fuzzing to great and overlap
207 if (*high <= *low) {
208 *high = signalprop.high;
209 *low = signalprop.low;
212 // prnt("getHiLo fuzzed: High %d | Low %d", *high, *low);
215 // by marshmellow
216 // pass bits to be tested in bits, length bits passed in bitLen, and parity type (even=0 | odd=1) in pType
217 // returns 1 if passed
218 bool parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType) {
219 return oddparity32(bits) ^ pType;
222 //by marshmellow
223 // takes a array of binary values, start position, length of bits per parity (includes parity bit - MAX 32),
224 // Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run)
225 size_t removeParity(uint8_t *bits, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen) {
226 uint32_t parityWd = 0;
227 size_t bitCnt = 0;
228 for (int word = 0; word < (bLen); word += pLen) {
229 for (int bit = 0; bit < pLen; bit++) {
230 if (word + bit >= bLen) break;
231 parityWd = (parityWd << 1) | bits[startIdx + word + bit];
232 bits[bitCnt++] = (bits[startIdx + word + bit]);
234 if (word + pLen > bLen) break;
236 bitCnt--; // overwrite parity with next data
237 // if parity fails then return 0
238 switch (pType) {
239 case 3:
240 if (bits[bitCnt] == 1) {return 0;}
241 break; //should be 0 spacer bit
242 case 2:
243 if (bits[bitCnt] == 0) {return 0;}
244 break; //should be 1 spacer bit
245 default:
246 if (parityTest(parityWd, pLen, pType) == 0) { return 0; }
247 break; //test parity
249 parityWd = 0;
251 // if we got here then all the parities passed
252 //return size
253 return bitCnt;
256 // by marshmellow
257 // takes a array of binary values, length of bits per parity (includes parity bit),
258 // Parity Type (1 for odd; 0 for even; 2 Always 1's; 3 Always 0's), and binary Length (length to run)
259 // Make sure *dest is long enough to store original sourceLen + #_of_parities_to_be_added
260 size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType) {
261 uint32_t parityWd = 0;
262 size_t j = 0, bitCnt = 0;
263 for (int word = 0; word < sourceLen; word += pLen - 1) {
264 for (int bit = 0; bit < pLen - 1; bit++) {
265 parityWd = (parityWd << 1) | src[word + bit];
266 dest[j++] = (src[word + bit]);
268 // if parity fails then return 0
269 switch (pType) {
270 case 3:
271 dest[j++] = 0;
272 break; // marker bit which should be a 0
273 case 2:
274 dest[j++] = 1;
275 break; // marker bit which should be a 1
276 default:
277 dest[j++] = parityTest(parityWd, pLen - 1, pType) ^ 1;
278 break;
280 bitCnt += pLen;
281 parityWd = 0;
283 // if we got here then all the parities passed
284 //return ID start index and size
285 return bitCnt;
288 // array must be size dividable with 8
289 int bits_to_array(const uint8_t *bits, size_t size, uint8_t *dest) {
290 if ((size == 0) || (size % 8) != 0) return PM3_EINVARG;
292 for (uint32_t i = 0; i < (size / 8); i++)
293 dest[i] = bytebits_to_byte((uint8_t *) bits + (i * 8), 8);
295 return PM3_SUCCESS;
298 uint32_t bytebits_to_byte(uint8_t *src, size_t numbits) {
299 uint32_t num = 0;
300 for (int i = 0 ; i < numbits ; i++) {
301 num = (num << 1) | (*src);
302 src++;
304 return num;
307 //least significant bit first
308 uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits) {
309 uint32_t num = 0;
310 for (int i = 0 ; i < numbits ; i++) {
311 num = (num << 1) | *(src + (numbits - (i + 1)));
313 return num;
316 //by marshmellow
317 //search for given preamble in given BitStream and return success = TRUE or fail = FALSE and startIndex and length
318 bool preambleSearch(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx) {
319 return preambleSearchEx(bits, preamble, pLen, size, startIdx, false);
321 //by marshmellow
322 // search for given preamble in given BitStream and return success=1 or fail=0 and startIndex (where it was found) and length if not fineone
323 // fineone does not look for a repeating preamble for em4x05/4x69 sends preamble once, so look for it once in the first pLen bits
324 //(iceman) FINDONE, only finds start index. NOT SIZE!. I see Em410xDecode (lfdemod.c) uses SIZE to determine success
325 bool preambleSearchEx(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx, bool findone) {
326 // Sanity check. If preamble length is bigger than bits length.
327 if (*size <= pLen)
328 return false;
330 uint8_t foundCnt = 0;
331 for (size_t idx = 0; idx < *size - pLen; idx++) {
332 if (memcmp(bits + idx, preamble, pLen) == 0) {
333 //first index found
334 foundCnt++;
335 if (foundCnt == 1) {
336 if (g_debugMode >= 1) prnt("DEBUG: (preambleSearchEx) preamble found at %zu", idx);
337 *startIdx = idx;
338 if (findone)
339 return true;
341 if (foundCnt == 2) {
342 if (g_debugMode >= 1) prnt("DEBUG: (preambleSearchEx) preamble 2 found at %zu", idx);
343 *size = idx - *startIdx;
344 return true;
348 return (foundCnt > 0);
351 // find start of modulating data (for fsk and psk) in case of beginning noise or slow chip startup.
352 static size_t findModStart(uint8_t *src, size_t size, uint8_t expWaveSize) {
353 size_t i = 0;
354 size_t waveSizeCnt = 0;
355 uint8_t thresholdCnt = 0;
356 bool isAboveThreshold = src[i++] >= signalprop.mean; //FSK_PSK_THRESHOLD;
357 for (; i < size - 20; i++) {
358 if (src[i] < signalprop.mean && isAboveThreshold) {
359 thresholdCnt++;
360 if (thresholdCnt > 2 && waveSizeCnt < expWaveSize + 1) break;
361 isAboveThreshold = false;
362 waveSizeCnt = 0;
363 } else if (src[i] >= signalprop.mean && !isAboveThreshold) {
364 thresholdCnt++;
365 if (thresholdCnt > 2 && waveSizeCnt < expWaveSize + 1) break;
366 isAboveThreshold = true;
367 waveSizeCnt = 0;
368 } else {
369 waveSizeCnt++;
371 if (thresholdCnt > 10) break;
373 if (g_debugMode == 2) prnt("DEBUG: threshold Count reached at index %zu, count: %u", i, thresholdCnt);
374 return i;
377 static int getClosestClock(int testclk) {
378 uint16_t clocks[] = {8, 16, 32, 40, 50, 64, 100, 128, 256, 384};
379 uint8_t limit[] = {1, 2, 4, 4, 5, 8, 8, 8, 8, 8};
381 for (uint8_t i = 0; i < 10; i++) {
382 if (testclk >= clocks[i] - limit[i] && testclk <= clocks[i] + limit[i])
383 return clocks[i];
385 return 0;
388 void getNextLow(uint8_t *samples, size_t size, int low, size_t *i) {
389 while ((samples[*i] > low) && (*i < size))
390 *i += 1;
393 void getNextHigh(uint8_t *samples, size_t size, int high, size_t *i) {
394 while ((samples[*i] < high) && (*i < size))
395 *i += 1;
398 // load wave counters
399 bool loadWaveCounters(uint8_t *samples, size_t size, int lowToLowWaveLen[], int highToLowWaveLen[], int *waveCnt, int *skip, int *minClk, int *high, int *low) {
400 size_t i = 0;
401 //size_t testsize = (size < 512) ? size : 512;
403 // just noise - no super good detection. good enough
404 if (signalprop.isnoise) {
405 if (g_debugMode == 2) prnt("DEBUG STT: just noise detected - quitting");
406 return false;
409 getHiLo(high, low, 80, 80);
411 // get to first full low to prime loop and skip incomplete first pulse
412 getNextHigh(samples, size, *high, &i);
413 getNextLow(samples, size, *low, &i);
414 *skip = i;
416 // populate tmpbuff buffer with pulse lengths
417 while (i < size) {
418 // measure from low to low
419 size_t firstLow = i;
420 //find first high point for this wave
421 getNextHigh(samples, size, *high, &i);
422 size_t firstHigh = i;
424 getNextLow(samples, size, *low, &i);
426 if (*waveCnt >= (size / LOWEST_DEFAULT_CLOCK))
427 break;
429 highToLowWaveLen[*waveCnt] = i - firstHigh; //first high to first low
430 lowToLowWaveLen[*waveCnt] = i - firstLow;
431 *waveCnt += 1;
432 if (i - firstLow < *minClk && i < size) {
433 *minClk = i - firstLow;
436 return true;
439 size_t pskFindFirstPhaseShift(uint8_t *samples, size_t size, uint8_t *curPhase, size_t waveStart, uint16_t fc, uint16_t *fullWaveLen) {
440 uint16_t loopCnt = (size + 3 < 4096) ? size : 4096; //don't need to loop through entire array...
442 uint16_t avgWaveVal = 0, lastAvgWaveVal;
443 size_t i = waveStart, waveEnd, waveLenCnt, firstFullWave;
444 for (; i < loopCnt; i++) {
445 // find peak // was "samples[i] + fc" but why? must have been used to weed out some wave error... removed..
446 if (samples[i] < samples[i + 1] && samples[i + 1] >= samples[i + 2]) {
447 waveEnd = i + 1;
448 if (g_debugMode == 2) prnt("DEBUG PSK: waveEnd: %zu, waveStart: %zu", waveEnd, waveStart);
449 waveLenCnt = waveEnd - waveStart;
450 if (waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack
451 lastAvgWaveVal = avgWaveVal / (waveLenCnt);
452 firstFullWave = waveStart;
453 *fullWaveLen = waveLenCnt;
454 //if average wave value is > graph 0 then it is an up wave or a 1 (could cause inverting)
455 if (lastAvgWaveVal > FSK_PSK_THRESHOLD) *curPhase ^= 1;
456 return firstFullWave;
458 waveStart = i + 1;
459 avgWaveVal = 0;
461 avgWaveVal += samples[i + 2];
463 return 0;
466 //by marshmellow
467 //amplify based on ask edge detection - not accurate enough to use all the time
468 void askAmp(uint8_t *bits, size_t size) {
469 uint8_t last = 128;
470 for (size_t i = 1; i < size; ++i) {
471 if (bits[i] - bits[i - 1] >= 30) //large jump up
472 last = 255;
473 else if (bits[i - 1] - bits[i] >= 20) //large jump down
474 last = 0;
476 bits[i] = last;
480 // iceman, simplify this
481 uint32_t manchesterEncode2Bytes(uint16_t datain) {
482 uint32_t output = 0;
483 for (uint8_t i = 0; i < 16; i++) {
484 uint8_t b = (datain >> (15 - i) & 1);
485 output |= (1 << (((15 - i) * 2) + b));
487 return output;
490 void manchesterEncodeUint32(uint32_t data_in, uint8_t bitlen_in, uint8_t *bits_out, uint16_t *index) {
491 for (int i = bitlen_in - 1; i >= 0; i--) {
492 if ((data_in >> i) & 1) {
493 bits_out[(*index)++] = 1;
494 bits_out[(*index)++] = 0;
495 } else {
496 bits_out[(*index)++] = 0;
497 bits_out[(*index)++] = 1;
502 //by marshmellow
503 //encode binary data into binary manchester
504 //NOTE: bitstream must have triple the size of "size" available in memory to do the swap
505 int ManchesterEncode(uint8_t *bits, size_t size) {
506 //allow up to 4096b out (means bits must be at least 2048+4096 to handle the swap)
507 size = (size > 2048) ? 2048 : size;
508 size_t modIdx = size;
509 size_t i;
510 for (size_t idx = 0; idx < size; idx++) {
511 bits[idx + modIdx++] = bits[idx];
512 bits[idx + modIdx++] = bits[idx] ^ 1;
514 for (i = 0; i < (size * 2); i++) {
515 bits[i] = bits[i + size];
517 return i;
520 // by marshmellow
521 // to detect a wave that has heavily clipped (clean) samples
522 // loop 1024 samples, if 250 of them is deemed maxed out, we assume the wave is clipped.
523 bool DetectCleanAskWave(uint8_t *dest, size_t size, uint8_t high, uint8_t low) {
524 bool allArePeaks = true;
525 uint16_t cntPeaks = 0;
526 size_t loopEnd = 1024 + 160;
528 // sanity check
529 if (loopEnd > size) loopEnd = size;
531 for (size_t i = 160; i < loopEnd; i++) {
533 if (dest[i] > low && dest[i] < high)
534 allArePeaks = false;
535 else {
536 cntPeaks++;
537 //if (g_debugMode == 2) prnt("DEBUG DetectCleanAskWave: peaks (200) %u", cntPeaks);
538 if (cntPeaks > 200) return true;
542 if (allArePeaks == false) {
543 if (g_debugMode == 2) prnt("DEBUG DetectCleanAskWave: peaks (200) %u", cntPeaks);
544 if (cntPeaks > 200) return true;
546 return allArePeaks;
550 // **********************************************************************************************
551 // -------------------Clock / Bitrate Detection Section------------------------------------------
552 // **********************************************************************************************
555 // by marshmellow
556 // to help detect clocks on heavily clipped samples
557 // based on count of low to low
558 int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clock) {
559 size_t i = 100;
560 size_t minClk = 512;
561 uint16_t shortestWaveIdx = 0;
563 // get to first full low to prime loop and skip incomplete first pulse
564 getNextHigh(dest, size, high, &i);
565 getNextLow(dest, size, low, &i);
567 if (i == size)
568 return -1;
569 if (size < 512)
570 return -2;
572 // clock, numoftimes, first idx
573 uint16_t tmpclk[10][3] = {
574 {8, 0, 0},
575 {16, 0, 0},
576 {32, 0, 0},
577 {40, 0, 0},
578 {50, 0, 0},
579 {64, 0, 0},
580 {100, 0, 0},
581 {128, 0, 0},
582 {256, 0, 0},
583 {384, 0, 0},
586 // loop through all samples (well, we don't want to go out-of-bounds)
587 while (i < (size - 512)) {
588 // measure from low to low
589 size_t startwave = i;
591 getNextHigh(dest, size, high, &i);
592 getNextLow(dest, size, low, &i);
594 //get minimum measured distance
595 if (i - startwave < minClk && i < size) {
596 minClk = i - startwave;
597 shortestWaveIdx = startwave;
600 int foo = getClosestClock(minClk);
601 if (foo > 0) {
602 for (uint8_t j = 0; j < 10; j++) {
603 if (tmpclk[j][0] == foo) {
604 tmpclk[j][1]++;
606 if (tmpclk[j][2] == 0) {
607 tmpclk[j][2] = shortestWaveIdx;
609 break;
615 // find the clock with most hits and it the first index it was encountered.
616 int max = 0;
617 for (uint8_t j = 0; j < 10; j++) {
618 if (g_debugMode == 2) {
619 prnt("DEBUG, ASK, clocks %u | hits %u | idx %u"
620 , tmpclk[j][0]
621 , tmpclk[j][1]
622 , tmpclk[j][2]
625 if (max < tmpclk[j][1]) {
626 *clock = tmpclk[j][0];
627 shortestWaveIdx = tmpclk[j][2];
628 max = tmpclk[j][1];
632 if (*clock == 0)
633 return -1;
635 return shortestWaveIdx;
638 // by marshmellow
639 // not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
640 // maybe somehow adjust peak trimming value based on samples to fix?
641 // return start index of best starting position for that clock and return clock (by reference)
642 int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) {
644 //don't need to loop through entire array. (cotag has clock of 384)
645 uint16_t loopCnt = 2000;
647 // not enough samples
648 if (size <= loopCnt + 60) {
649 if (g_debugMode == 2) prnt("DEBUG DetectASKClock: not enough samples - aborting");
650 return -1;
653 // just noise - no super good detection. good enough
654 if (signalprop.isnoise) {
655 if (g_debugMode == 2) prnt("DEBUG DetectASKClock: just noise detected - aborting");
656 return -2;
659 size_t i = 1;
660 uint16_t num_clks = 9;
661 // first 255 value pos0 is placeholder for user inputed clock.
662 uint16_t clk[] = {255, 8, 16, 32, 40, 50, 64, 100, 128, 255};
664 // sometimes there is a strange end wave - filter out this
665 size -= 60;
667 // What is purpose?
668 // already have a valid clock?
669 uint8_t found_clk = 0;
670 for (; i < num_clks; ++i) {
671 if (clk[i] == *clock) {
672 found_clk = i;
676 // threshold 75% of high, low peak
677 int peak_hi, peak_low;
678 getHiLo(&peak_hi, &peak_low, 75, 75);
680 // test for large clean, STRONG, CLIPPED peaks
682 if (!found_clk) {
684 if (DetectCleanAskWave(dest, size, peak_hi, peak_low)) {
686 int idx = DetectStrongAskClock(dest, size, peak_hi, peak_low, clock);
687 if (g_debugMode == 2)
688 prnt("DEBUG ASK: DetectASKClock Clean ASK Wave detected: clk %i, Best Starting Position: %i", *clock, idx);
690 // return shortest wave start position
691 if (idx > -1)
692 return idx;
695 // test for weak peaks
697 // test clock if given as cmd parameter
698 if (*clock > 0)
699 clk[0] = *clock;
701 uint8_t clkCnt, tol;
702 size_t j = 0;
703 uint16_t bestErr[] = {1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
704 uint8_t bestStart[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
705 size_t errCnt, arrLoc, loopEnd;
707 if (found_clk) {
708 clkCnt = found_clk;
709 num_clks = found_clk + 1;
710 } else {
711 clkCnt = 1;
714 //test each valid clock from smallest to greatest to see which lines up
715 for (; clkCnt < num_clks; clkCnt++) {
716 if (clk[clkCnt] <= 32) {
717 tol = 1;
718 } else {
719 tol = 0;
721 //if no errors allowed - keep start within the first clock
722 if (!maxErr && size > clk[clkCnt] * 2 + tol && clk[clkCnt] < 128)
723 loopCnt = clk[clkCnt] * 2;
725 bestErr[clkCnt] = 1000;
727 //try lining up the peaks by moving starting point (try first few clocks)
729 // get to first full low to prime loop and skip incomplete first pulse
730 getNextHigh(dest, size, peak_hi, &j);
731 getNextLow(dest, size, peak_low, &j);
733 for (; j < loopCnt; j++) {
734 errCnt = 0;
735 // now that we have the first one lined up test rest of wave array
736 loopEnd = ((size - j - tol) / clk[clkCnt]) - 1;
737 for (i = 0; i < loopEnd; ++i) {
738 arrLoc = j + (i * clk[clkCnt]);
739 if (dest[arrLoc] >= peak_hi || dest[arrLoc] <= peak_low) {
740 } else if (dest[arrLoc - tol] >= peak_hi || dest[arrLoc - tol] <= peak_low) {
741 } else if (dest[arrLoc + tol] >= peak_hi || dest[arrLoc + tol] <= peak_low) {
742 } else { //error no peak detected
743 errCnt++;
746 // if we found no errors then we can stop here and a low clock (common clocks)
747 // this is correct one - return this clock
748 // if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, err %d, startpos %d, endpos %d", clk[clkCnt], errCnt, j, i);
749 if (errCnt == 0 && clkCnt < 7) {
750 if (!found_clk)
751 *clock = clk[clkCnt];
752 return j;
754 // if we found errors see if it is lowest so far and save it as best run
755 if (errCnt < bestErr[clkCnt]) {
756 bestErr[clkCnt] = errCnt;
757 bestStart[clkCnt] = j;
762 uint8_t k, best = 0;
764 for (k = 1; k < num_clks; ++k) {
765 if (bestErr[k] < bestErr[best]) {
766 if (bestErr[k] == 0) bestErr[k] = 1;
767 // current best bit to error ratio vs new bit to error ratio
768 if ((size / clk[best]) / bestErr[best] < (size / clk[k]) / bestErr[k]) {
769 best = k;
772 //if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, # Errors %d, Current Best Clk %d, bestStart %d", clk[k], bestErr[k], clk[best], bestStart[best]);
775 bool chg = false;
776 for (i = 0; i < ARRAYLEN(bestErr); i++) {
777 chg = (bestErr[i] != 1000);
778 if (chg)
779 break;
780 chg = (bestStart[i] != 0);
781 if (chg)
782 break;
785 // just noise - no super good detection. good enough
786 if (chg == false) {
787 if (g_debugMode == 2) prnt("DEBUG DetectASKClock: no good values detected - aborting");
788 return -2;
791 if (!found_clk)
792 *clock = clk[best];
794 return bestStart[best];
797 int DetectStrongNRZClk(uint8_t *dest, size_t size, int peak, int low, bool *strong) {
798 //find shortest transition from high to low
799 *strong = false;
800 size_t i = 0;
801 size_t transition1 = 0;
802 int lowestTransition = 255;
803 bool lastWasHigh = false;
804 size_t transitionSampleCount = 0;
805 //find first valid beginning of a high or low wave
806 while ((dest[i] >= peak || dest[i] <= low) && (i < size))
807 ++i;
808 while ((dest[i] < peak && dest[i] > low) && (i < size))
809 ++i;
811 lastWasHigh = (dest[i] >= peak);
813 if (i == size)
814 return 0;
816 transition1 = i;
818 for (; i < size; i++) {
819 if ((dest[i] >= peak && !lastWasHigh) || (dest[i] <= low && lastWasHigh)) {
820 lastWasHigh = (dest[i] >= peak);
821 if (i - transition1 < lowestTransition)
822 lowestTransition = i - transition1;
823 transition1 = i;
824 } else if (dest[i] < peak && dest[i] > low) {
825 transitionSampleCount++;
828 if (lowestTransition == 255)
829 lowestTransition = 0;
831 if (g_debugMode == 2) prnt("DEBUG NRZ: detectstrongNRZclk smallest wave: %d", lowestTransition);
832 // if less than 10% of the samples were not peaks (or 90% were peaks) then we have a strong wave
833 if (transitionSampleCount / size < 10) {
834 *strong = true;
835 lowestTransition = getClosestClock(lowestTransition);
837 return lowestTransition;
840 //by marshmellow
841 //detect nrz clock by reading #peaks vs no peaks(or errors)
842 int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx) {
843 size_t i = 0;
844 uint8_t clk[] = {8, 16, 32, 40, 50, 64, 100, 128, 255};
845 size_t loopCnt = 4096; //don't need to loop through entire array...
847 //if we already have a valid clock quit
848 for (; i < 8; ++i)
849 if (clk[i] == clock) return clock;
851 if (size < 20) return 0;
852 // size must be larger than 20 here
853 if (size < loopCnt) loopCnt = size - 20;
856 // just noise - no super good detection. good enough
857 if (signalprop.isnoise) {
858 if (g_debugMode == 2) prnt("DEBUG DetectNZRClock: just noise detected - quitting");
859 return 0;
862 //get high and low peak
863 int peak, low;
864 //getHiLo(dest, loopCnt, &peak, &low, 90, 90);
865 getHiLo(&peak, &low, 90, 90);
867 bool strong = false;
868 int lowestTransition = DetectStrongNRZClk(dest, size - 20, peak, low, &strong);
869 if (strong) return lowestTransition;
870 size_t ii;
871 uint8_t clkCnt;
872 uint8_t tol = 0;
873 uint16_t smplCnt = 0;
874 int16_t peakcnt = 0;
875 int16_t peaksdet[] = {0, 0, 0, 0, 0, 0, 0, 0};
876 uint16_t minPeak = 255;
877 bool firstpeak = true;
878 //test for large clipped waves - ignore first peak
879 for (i = 0; i < loopCnt; i++) {
880 if (dest[i] >= peak || dest[i] <= low) {
881 if (firstpeak) continue;
882 smplCnt++;
883 } else {
884 firstpeak = false;
885 if (smplCnt > 0) {
886 if (minPeak > smplCnt && smplCnt > 7) minPeak = smplCnt;
887 peakcnt++;
888 if (g_debugMode == 2) prnt("DEBUG NRZ: minPeak: %d, smplCnt: %d, peakcnt: %d", minPeak, smplCnt, peakcnt);
889 smplCnt = 0;
893 if (minPeak < 8) return 0;
895 bool errBitHigh = 0, bitHigh = 0, lastPeakHigh = 0;
896 uint8_t ignoreCnt = 0, ignoreWindow = 4;
897 int lastBit = 0;
898 size_t bestStart[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
899 peakcnt = 0;
900 //test each valid clock from smallest to greatest to see which lines up
901 for (clkCnt = 0; clkCnt < 8; ++clkCnt) {
902 //ignore clocks smaller than smallest peak
903 if (clk[clkCnt] < minPeak - (clk[clkCnt] / 4)) continue;
904 //try lining up the peaks by moving starting point (try first 256)
905 for (ii = 20; ii < loopCnt; ++ii) {
906 if ((dest[ii] >= peak) || (dest[ii] <= low)) {
907 peakcnt = 0;
908 bitHigh = false;
909 ignoreCnt = 0;
910 lastBit = ii - clk[clkCnt];
911 //loop through to see if this start location works
912 for (i = ii; i < size - 20; ++i) {
913 //if we are at a clock bit
914 if ((i >= lastBit + clk[clkCnt] - tol) && (i <= lastBit + clk[clkCnt] + tol)) {
915 //test high/low
916 if (dest[i] >= peak || dest[i] <= low) {
917 //if same peak don't count it
918 if ((dest[i] >= peak && !lastPeakHigh) || (dest[i] <= low && lastPeakHigh)) {
919 peakcnt++;
921 lastPeakHigh = (dest[i] >= peak);
922 bitHigh = true;
923 errBitHigh = false;
924 ignoreCnt = ignoreWindow;
925 lastBit += clk[clkCnt];
926 } else if (i == lastBit + clk[clkCnt] + tol) {
927 lastBit += clk[clkCnt];
929 //else if not a clock bit and no peaks
930 } else if (dest[i] < peak && dest[i] > low) {
931 if (ignoreCnt == 0) {
932 bitHigh = false;
933 if (errBitHigh == true)
934 peakcnt--;
935 errBitHigh = false;
936 } else {
937 ignoreCnt--;
939 // else if not a clock bit but we have a peak
940 } else if ((dest[i] >= peak || dest[i] <= low) && (!bitHigh)) {
941 //error bar found no clock...
942 errBitHigh = true;
945 if (peakcnt > peaksdet[clkCnt]) {
946 bestStart[clkCnt] = ii;
947 peaksdet[clkCnt] = peakcnt;
953 uint8_t best = 0;
954 for (int m = 7; m > 0; m--) {
955 if ((peaksdet[m] >= (peaksdet[best] - 1)) && (peaksdet[m] <= peaksdet[best] + 1) && lowestTransition) {
956 if (clk[m] > (lowestTransition - (clk[m] / 8)) && clk[m] < (lowestTransition + (clk[m] / 8))) {
957 best = m;
959 } else if (peaksdet[m] > peaksdet[best]) {
960 best = m;
962 if (g_debugMode == 2) prnt("DEBUG NRZ: Clk: %d, peaks: %d, minPeak: %d, bestClk: %d, lowestTrs: %d", clk[m], peaksdet[m], minPeak, clk[best], lowestTransition);
964 *clockStartIdx = bestStart[best];
965 return clk[best];
968 //by marshmellow
969 //countFC is to detect the field clock lengths.
970 //counts and returns the 2 most common wave lengths
971 //mainly used for FSK field clock detection
972 uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj) {
973 uint8_t fcLens[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
974 uint16_t fcCnts[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
975 uint8_t fcLensFnd = 0;
976 uint8_t lastFCcnt = 0;
977 uint8_t fcCounter = 0;
978 size_t i;
979 if (size < 180) return 0;
981 // prime i to first up transition
982 for (i = 160; i < size - 20; i++)
983 if (bits[i] > bits[i - 1] && bits[i] >= bits[i + 1])
984 break;
986 for (; i < size - 20; i++) {
987 if (bits[i] > bits[i - 1] && bits[i] >= bits[i + 1]) {
988 // new up transition
989 fcCounter++;
990 if (fskAdj) {
991 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
992 if (lastFCcnt == 5 && fcCounter == 9) fcCounter--;
994 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
995 if ((fcCounter == 9) || fcCounter == 4) fcCounter++;
996 // save last field clock count (fc/xx)
997 lastFCcnt = fcCounter;
999 // find which fcLens to save it to:
1000 for (int m = 0; m < 15; m++) {
1001 if (fcLens[m] == fcCounter) {
1002 fcCnts[m]++;
1003 fcCounter = 0;
1004 break;
1007 if (fcCounter > 0 && fcLensFnd < 15) {
1008 //add new fc length
1009 fcCnts[fcLensFnd]++;
1010 fcLens[fcLensFnd++] = fcCounter;
1012 fcCounter = 0;
1013 } else {
1014 // count sample
1015 fcCounter++;
1019 uint8_t best1 = 14, best2 = 14, best3 = 14;
1020 uint16_t maxCnt1 = 0;
1021 // go through fclens and find which ones are bigest 2
1022 for (i = 0; i < 15; i++) {
1023 // get the 3 best FC values
1024 if (fcCnts[i] > maxCnt1) {
1025 best3 = best2;
1026 best2 = best1;
1027 maxCnt1 = fcCnts[i];
1028 best1 = i;
1029 } else if (fcCnts[i] > fcCnts[best2]) {
1030 best3 = best2;
1031 best2 = i;
1032 } else if (fcCnts[i] > fcCnts[best3]) {
1033 best3 = i;
1035 if (g_debugMode == 2) prnt("DEBUG countfc: FC %u, Cnt %u, best fc: %u, best2 fc: %u", fcLens[i], fcCnts[i], fcLens[best1], fcLens[best2]);
1036 if (fcLens[i] == 0) break;
1039 if (fcLens[best1] == 0) return 0;
1040 uint8_t fcH = 0, fcL = 0;
1041 if (fcLens[best1] > fcLens[best2]) {
1042 fcH = fcLens[best1];
1043 fcL = fcLens[best2];
1044 } else {
1045 fcH = fcLens[best2];
1046 fcL = fcLens[best1];
1048 if ((size - 180) / fcH / 3 > fcCnts[best1] + fcCnts[best2]) {
1049 if (g_debugMode == 2) prnt("DEBUG countfc: fc is too large: %zu > %u. Not psk or fsk", (size - 180) / fcH / 3, fcCnts[best1] + fcCnts[best2]);
1050 return 0; //lots of waves not psk or fsk
1052 // TODO: take top 3 answers and compare to known Field clocks to get top 2
1054 uint16_t fcs = (((uint16_t)fcH) << 8) | fcL;
1055 if (fskAdj) return fcs;
1056 return (uint16_t)fcLens[best2] << 8 | fcLens[best1];
1059 //by marshmellow
1060 //detect psk clock by reading each phase shift
1061 // a phase shift is determined by measuring the sample length of each wave
1062 int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShift, uint8_t *curPhase, uint8_t *fc) {
1063 uint8_t clk[] = {255, 16, 32, 40, 50, 64, 100, 128, 255}; //255 is not a valid clock
1064 uint16_t loopCnt = 4096; //don't need to loop through entire array...
1066 if (size < 160 + 20) return 0;
1067 // size must be larger than 20 here, and 160 later on.
1068 if (size < loopCnt) loopCnt = size - 20;
1070 uint16_t fcs = countFC(dest, size, 0);
1072 *fc = fcs & 0xFF;
1074 if (g_debugMode == 2) prnt("DEBUG PSK: FC: %d, FC2: %d", *fc, fcs >> 8);
1076 if ((fcs >> 8) == 10 && *fc == 8) return 0;
1078 if (*fc != 2 && *fc != 4 && *fc != 8) return 0;
1081 size_t waveEnd, firstFullWave = 0;
1083 uint8_t clkCnt;
1084 uint16_t waveLenCnt, fullWaveLen = 0;
1085 uint16_t bestErr[] = {1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
1086 uint16_t peaksdet[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
1088 //find start of modulating data in trace
1089 size_t i = findModStart(dest, size, *fc);
1091 firstFullWave = pskFindFirstPhaseShift(dest, size, curPhase, i, *fc, &fullWaveLen);
1092 if (firstFullWave == 0) {
1093 // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
1094 // so skip a little to ensure we are past any Start Signal
1095 firstFullWave = 160;
1096 fullWaveLen = 0;
1099 *firstPhaseShift = firstFullWave;
1100 if (g_debugMode == 2) prnt("DEBUG PSK: firstFullWave: %zu, waveLen: %d", firstFullWave, fullWaveLen);
1102 // Avoid autodetect if user selected a clock
1103 for (uint8_t validClk = 1; validClk < 8; validClk++) {
1104 if (clock == clk[validClk]) return (clock);
1107 //test each valid clock from greatest to smallest to see which lines up
1108 for (clkCnt = 7; clkCnt >= 1 ; clkCnt--) {
1109 uint8_t tol = *fc / 2;
1110 size_t lastClkBit = firstFullWave; //set end of wave as clock align
1111 size_t waveStart = 0;
1112 uint16_t errCnt = 0;
1113 uint16_t peakcnt = 0;
1114 if (g_debugMode == 2) prnt("DEBUG PSK: clk: %d, lastClkBit: %zu", clk[clkCnt], lastClkBit);
1116 for (i = firstFullWave + fullWaveLen - 1; i < loopCnt - 2; i++) {
1117 //top edge of wave = start of new wave
1118 if (dest[i] < dest[i + 1] && dest[i + 1] >= dest[i + 2]) {
1119 if (waveStart == 0) {
1120 waveStart = i + 1;
1121 } else { //waveEnd
1122 waveEnd = i + 1;
1123 waveLenCnt = waveEnd - waveStart;
1124 if (waveLenCnt > *fc) {
1125 //if this wave is a phase shift
1126 if (g_debugMode == 2) prnt("DEBUG PSK: phase shift at: %zu, len: %d, nextClk: %zu, i: %zu, fc: %d", waveStart, waveLenCnt, lastClkBit + clk[clkCnt] - tol, i + 1, *fc);
1127 if (i + 1 >= lastClkBit + clk[clkCnt] - tol) { //should be a clock bit
1128 peakcnt++;
1129 lastClkBit += clk[clkCnt];
1130 } else if (i < lastClkBit + 8) {
1131 //noise after a phase shift - ignore
1132 } else { //phase shift before supposed to based on clock
1133 errCnt++;
1135 } else if (i + 1 > lastClkBit + clk[clkCnt] + tol + *fc) {
1136 lastClkBit += clk[clkCnt]; //no phase shift but clock bit
1138 waveStart = i + 1;
1142 if (errCnt == 0) return clk[clkCnt];
1143 if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt] = errCnt;
1144 if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt] = peakcnt;
1146 //all tested with errors
1147 //return the highest clk with the most peaks found
1148 uint8_t best = 7;
1149 for (i = 7; i >= 1; i--) {
1150 if (peaksdet[i] > peaksdet[best])
1151 best = i;
1153 if (g_debugMode == 2) prnt("DEBUG PSK: Clk: %d, peaks: %d, errs: %d, bestClk: %d", clk[i], peaksdet[i], bestErr[i], clk[best]);
1155 return clk[best];
1158 //by marshmellow
1159 //detects the bit clock for FSK given the high and low Field Clocks
1160 uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, int *firstClockEdge) {
1162 if (size == 0)
1163 return 0;
1165 uint8_t clk[] = {8, 16, 32, 40, 50, 64, 100, 128, 0};
1166 uint16_t rfLens[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1167 uint8_t rfCnts[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1168 uint8_t rfLensFnd = 0;
1169 uint8_t lastFCcnt = 0;
1170 uint16_t fcCounter = 0;
1171 uint16_t rfCounter = 0;
1172 uint8_t firstBitFnd = 0;
1173 size_t i;
1174 uint8_t fcTol = ((fcHigh * 100 - fcLow * 100) / 2 + 50) / 100; //(uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
1176 // prime i to first peak / up transition
1177 for (i = 160; i < size - 20; i++)
1178 if (bits[i] > bits[i - 1] && bits[i] >= bits[i + 1])
1179 break;
1181 for (; i < size - 20; i++) {
1182 fcCounter++;
1183 rfCounter++;
1185 if (bits[i] <= bits[i - 1] || bits[i] < bits[i + 1])
1186 continue;
1187 // else new peak
1188 // if we got less than the small fc + tolerance then set it to the small fc
1189 // if it is inbetween set it to the last counter
1190 if (fcCounter < fcHigh && fcCounter > fcLow)
1191 fcCounter = lastFCcnt;
1192 else if (fcCounter < fcLow + fcTol)
1193 fcCounter = fcLow;
1194 else //set it to the large fc
1195 fcCounter = fcHigh;
1197 //look for bit clock (rf/xx)
1198 if ((fcCounter < lastFCcnt || fcCounter > lastFCcnt)) {
1199 //not the same size as the last wave - start of new bit sequence
1200 if (firstBitFnd > 1) { //skip first wave change - probably not a complete bit
1201 for (int ii = 0; ii < 15; ii++) {
1202 if (rfLens[ii] >= (rfCounter - 4) && rfLens[ii] <= (rfCounter + 4)) {
1203 rfCnts[ii]++;
1204 rfCounter = 0;
1205 break;
1208 if (rfCounter > 0 && rfLensFnd < 15) {
1209 //prnt("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
1210 rfCnts[rfLensFnd]++;
1211 rfLens[rfLensFnd++] = rfCounter;
1213 } else {
1214 *firstClockEdge = i;
1215 firstBitFnd++;
1217 rfCounter = 0;
1218 lastFCcnt = fcCounter;
1220 fcCounter = 0;
1222 uint8_t rfHighest = 15, rfHighest2 = 15, rfHighest3 = 15;
1224 for (i = 0; i < 15; i++) {
1225 //get highest 2 RF values (might need to get more values to compare or compare all?)
1226 if (rfCnts[i] > rfCnts[rfHighest]) {
1227 rfHighest3 = rfHighest2;
1228 rfHighest2 = rfHighest;
1229 rfHighest = i;
1230 } else if (rfCnts[i] > rfCnts[rfHighest2]) {
1231 rfHighest3 = rfHighest2;
1232 rfHighest2 = i;
1233 } else if (rfCnts[i] > rfCnts[rfHighest3]) {
1234 rfHighest3 = i;
1236 if (g_debugMode == 2)
1237 prnt("DEBUG FSK: RF %d, cnts %d", rfLens[i], rfCnts[i]);
1239 // set allowed clock remainder tolerance to be 1 large field clock length+1
1240 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
1241 uint8_t tol1 = fcHigh + 1;
1243 if (g_debugMode == 2)
1244 prnt("DEBUG FSK: most counted rf values: 1 %d, 2 %d, 3 %d", rfLens[rfHighest], rfLens[rfHighest2], rfLens[rfHighest3]);
1246 // loop to find the highest clock that has a remainder less than the tolerance
1247 // compare samples counted divided by
1248 // test 128 down to 32 (shouldn't be possible to have fc/10 & fc/8 and rf/16 or less)
1249 int m = 7;
1250 for (; m >= 2; m--) {
1251 if (rfLens[rfHighest] % clk[m] < tol1 || rfLens[rfHighest] % clk[m] > clk[m] - tol1) {
1252 if (rfLens[rfHighest2] % clk[m] < tol1 || rfLens[rfHighest2] % clk[m] > clk[m] - tol1) {
1253 if (rfLens[rfHighest3] % clk[m] < tol1 || rfLens[rfHighest3] % clk[m] > clk[m] - tol1) {
1254 if (g_debugMode == 2)
1255 prnt("DEBUG FSK: clk %d divides into the 3 most rf values within tolerance", clk[m]);
1256 break;
1262 if (m < 2) return 0; // oops we went too far
1264 return clk[m];
1268 // **********************************************************************************************
1269 // --------------------Modulation Demods &/or Decoding Section-----------------------------------
1270 // **********************************************************************************************
1273 // look for Sequence Terminator - should be pulses of clk*(1 or 2), clk*2, clk*(1.5 or 2), by idx we mean graph position index...
1274 static bool findST(int *stStopLoc, int *stStartIdx, int lowToLowWaveLen[], int highToLowWaveLen[], int clk, int tol, int buffSize, size_t *i) {
1275 if (buffSize < *i + 4) return false;
1277 for (; *i < buffSize - 4; *i += 1) {
1278 *stStartIdx += lowToLowWaveLen[*i]; //caution part of this wave may be data and part may be ST.... to be accounted for in main function for now...
1279 if (lowToLowWaveLen[*i] >= clk * 1 - tol && lowToLowWaveLen[*i] <= (clk * 2) + tol && highToLowWaveLen[*i] < clk + tol) { //1 to 2 clocks depending on 2 bits prior
1280 if (lowToLowWaveLen[*i + 1] >= clk * 2 - tol && lowToLowWaveLen[*i + 1] <= clk * 2 + tol && highToLowWaveLen[*i + 1] > clk * 3 / 2 - tol) { //2 clocks and wave size is 1 1/2
1281 if (lowToLowWaveLen[*i + 2] >= (clk * 3) / 2 - tol && lowToLowWaveLen[*i + 2] <= clk * 2 + tol && highToLowWaveLen[*i + 2] > clk - tol) { //1 1/2 to 2 clocks and at least one full clock wave
1282 if (lowToLowWaveLen[*i + 3] >= clk * 1 - tol && lowToLowWaveLen[*i + 3] <= clk * 2 + tol) { //1 to 2 clocks for end of ST + first bit
1283 *stStopLoc = *i + 3;
1284 return true;
1290 return false;
1292 //by marshmellow
1293 //attempt to identify a Sequence Terminator in ASK modulated raw wave
1294 bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, size_t *stend) {
1295 size_t bufsize = *size;
1296 //need to loop through all samples and identify our clock, look for the ST pattern
1297 int clk = 0;
1298 int tol = 0;
1299 int j = 0, high, low, skip = 0, start = 0, end = 0, minClk = 255;
1300 size_t i = 0;
1301 //probably should malloc... || test if memory is available ... handle device side? memory danger!!! [marshmellow]
1302 int tmpbuff[bufsize / LOWEST_DEFAULT_CLOCK]; // low to low wave count //guess rf/32 clock, if click is smaller we will only have room for a fraction of the samples captured
1303 int waveLen[bufsize / LOWEST_DEFAULT_CLOCK]; // high to low wave count //if clock is larger then we waste memory in array size that is not needed...
1304 //size_t testsize = (bufsize < 512) ? bufsize : 512;
1305 int phaseoff = 0;
1306 high = low = 128;
1307 memset(tmpbuff, 0, sizeof(tmpbuff));
1308 memset(waveLen, 0, sizeof(waveLen));
1310 if (!loadWaveCounters(buffer, bufsize, tmpbuff, waveLen, &j, &skip, &minClk, &high, &low)) return false;
1311 // set clock - might be able to get this externally and remove this work...
1312 clk = getClosestClock(minClk);
1313 // clock not found - ERROR
1314 if (!clk) {
1315 if (g_debugMode == 2) prnt("DEBUG STT: clock not found - quitting");
1316 return false;
1318 *foundclock = clk;
1320 tol = clk / 8;
1321 if (!findST(&start, &skip, tmpbuff, waveLen, clk, tol, j, &i)) {
1322 // first ST not found - ERROR
1323 if (g_debugMode == 2) prnt("DEBUG STT: first STT not found - quitting");
1324 return false;
1325 } else {
1326 if (g_debugMode == 2) prnt("DEBUG STT: first STT found at wave: %i, skip: %i, j=%i", start, skip, j);
1328 if (waveLen[i + 2] > clk * 1 + tol)
1329 phaseoff = 0;
1330 else
1331 phaseoff = clk / 2;
1333 // skip over the remainder of ST
1334 skip += clk * 7 / 2; //3.5 clocks from tmpbuff[i] = end of st - also aligns for ending point
1336 // now do it again to find the end
1337 int dummy1 = 0;
1338 end = skip;
1339 i += 3;
1340 if (!findST(&dummy1, &end, tmpbuff, waveLen, clk, tol, j, &i)) {
1341 //didn't find second ST - ERROR
1342 if (g_debugMode == 2) prnt("DEBUG STT: second STT not found - quitting");
1343 return false;
1345 end -= phaseoff;
1346 if (g_debugMode == 2) prnt("DEBUG STT: start of data: %d end of data: %d, datalen: %d, clk: %d, bits: %d, phaseoff: %d", skip, end, end - skip, clk, (end - skip) / clk, phaseoff);
1347 //now begin to trim out ST so we can use normal demod cmds
1348 start = skip;
1349 size_t datalen = end - start;
1350 // check validity of datalen (should be even clock increments) - use a tolerance of up to 1/8th a clock
1351 if (clk - (datalen % clk) <= clk / 8) {
1352 // padd the amount off - could be problematic... but shouldn't happen often
1353 datalen += clk - (datalen % clk);
1354 } else if ((datalen % clk) <= clk / 8) {
1355 // padd the amount off - could be problematic... but shouldn't happen often
1356 datalen -= datalen % clk;
1357 } else {
1358 if (g_debugMode == 2) prnt("DEBUG STT: datalen not divisible by clk: %zu %% %d = %zu - quitting", datalen, clk, datalen % clk);
1359 return false;
1361 // if datalen is less than one t55xx block - ERROR
1362 if (datalen / clk < 8 * 4) {
1363 if (g_debugMode == 2) prnt("DEBUG STT: datalen is less than 1 full t55xx block - quitting");
1364 return false;
1366 size_t dataloc = start;
1367 if (buffer[dataloc - (clk * 4) - (clk / 4)] <= low && buffer[dataloc] <= low && buffer[dataloc - (clk * 4)] >= high) {
1368 //we have low drift (and a low just before the ST and a low just after the ST) - compensate by backing up the start
1369 for (i = 0; i <= (clk / 4); ++i) {
1370 if (buffer[dataloc - (clk * 4) - i] <= low) {
1371 dataloc -= i;
1372 break;
1377 size_t newloc = 0;
1378 i = 0;
1379 if (g_debugMode == 2) prnt("DEBUG STT: Starting STT trim - start: %zu, datalen: %zu ", dataloc, datalen);
1380 bool firstrun = true;
1381 // warning - overwriting buffer given with raw wave data with ST removed...
1382 while (dataloc < bufsize - (clk / 2)) {
1383 //compensate for long high at end of ST not being high due to signal loss... (and we cut out the start of wave high part)
1384 if (buffer[dataloc] < high && buffer[dataloc] > low && buffer[dataloc + clk / 4] < high && buffer[dataloc + clk / 4] > low) {
1385 for (i = 0; i < clk / 2 - tol; ++i) {
1386 buffer[dataloc + i] = high + 5;
1388 } //test for small spike outlier (high between two lows) in the case of very strong waves
1389 if (buffer[dataloc] > low && buffer[dataloc + clk / 4] <= low) {
1390 for (i = 0; i < clk / 4; ++i) {
1391 buffer[dataloc + i] = buffer[dataloc + clk / 4];
1394 if (firstrun) {
1395 *stend = dataloc;
1396 *ststart = dataloc - (clk * 4);
1397 firstrun = false;
1399 for (i = 0; i < datalen; ++i) {
1400 if (i + newloc < bufsize) {
1401 if (i + newloc < dataloc)
1402 buffer[i + newloc] = buffer[dataloc];
1404 dataloc++;
1407 newloc += i;
1408 //skip next ST - we just assume it will be there from now on...
1409 if (g_debugMode == 2) prnt("DEBUG STT: skipping STT at %zu to %zu", dataloc, dataloc + (clk * 4));
1410 dataloc += clk * 4;
1412 *size = newloc;
1413 return true;
1416 //by marshmellow
1417 //take 11 10 01 11 00 and make 01100 ... miller decoding
1418 //check for phase errors - should never have half a 1 or 0 by itself and should never exceed 1111 or 0000 in a row
1419 //decodes miller encoded binary
1420 //NOTE askrawdemod will NOT demod miller encoded ask unless the clock is manually set to 1/2 what it is detected as!
1422 static int millerRawDecode(uint8_t *bits, size_t *size, int invert) {
1423 if (*size < 16) return -1;
1425 uint16_t MaxBits = 512, errCnt = 0;
1426 size_t i, bitCnt = 0;
1427 uint8_t alignCnt = 0, curBit = bits[0], alignedIdx = 0, halfClkErr = 0;
1429 //find alignment, needs 4 1s or 0s to properly align
1430 for (i = 1; i < *size - 1; i++) {
1431 alignCnt = (bits[i] == curBit) ? alignCnt + 1 : 0;
1432 curBit = bits[i];
1433 if (alignCnt == 4) break;
1435 // for now error if alignment not found. later add option to run it with multiple offsets...
1436 if (alignCnt != 4) {
1437 if (g_debugMode) prnt("ERROR MillerDecode: alignment not found so either your bits is not miller or your data does not have a 101 in it");
1438 return -1;
1440 alignedIdx = (i - 1) % 2;
1441 for (i = alignedIdx; i < *size - 3; i += 2) {
1442 halfClkErr = (uint8_t)((halfClkErr << 1 | bits[i]) & 0xFF);
1443 if ((halfClkErr & 0x7) == 5 || (halfClkErr & 0x7) == 2 || (i > 2 && (halfClkErr & 0x7) == 0) || (halfClkErr & 0x1F) == 0x1F) {
1444 errCnt++;
1445 bits[bitCnt++] = 7;
1446 continue;
1448 bits[bitCnt++] = bits[i] ^ bits[i + 1] ^ invert;
1450 if (bitCnt > MaxBits) break;
1452 *size = bitCnt;
1453 return errCnt;
1457 //by marshmellow
1458 //take 01 or 10 = 1 and 11 or 00 = 0
1459 //check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010
1460 //decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding
1461 int BiphaseRawDecode(uint8_t *bits, size_t *size, int *offset, int invert) {
1462 //sanity check
1463 if (*size < 51) return -1;
1465 if (*offset < 0) *offset = 0;
1467 uint16_t bitnum = 0;
1468 uint16_t errCnt = 0;
1469 size_t i = *offset;
1470 uint16_t maxbits = 512;
1472 //check for phase change faults - skip one sample if faulty
1473 bool offsetA = true, offsetB = true;
1474 for (; i < *offset + 48; i += 2) {
1475 if (bits[i + 1] == bits[i + 2]) offsetA = false;
1476 if (bits[i + 2] == bits[i + 3]) offsetB = false;
1478 if (!offsetA && offsetB) ++*offset;
1480 // main loop
1481 for (i = *offset; i < *size - 1; i += 2) {
1482 //check for phase error
1483 if (bits[i + 1] == bits[i + 2]) {
1484 bits[bitnum++] = 7;
1485 errCnt++;
1487 if ((bits[i] == 1 && bits[i + 1] == 0) || (bits[i] == 0 && bits[i + 1] == 1)) {
1488 bits[bitnum++] = 1 ^ invert;
1489 } else if ((bits[i] == 0 && bits[i + 1] == 0) || (bits[i] == 1 && bits[i + 1] == 1)) {
1490 bits[bitnum++] = invert;
1491 } else {
1492 bits[bitnum++] = 7;
1493 errCnt++;
1495 if (bitnum > maxbits) break;
1497 *size = bitnum;
1498 return errCnt;
1501 //by marshmellow
1502 //take 10 and 01 and manchester decode
1503 //run through 2 times and take least errCnt
1504 // "," indicates 00 or 11 wrong bit
1505 uint16_t manrawdecode(uint8_t *bits, size_t *size, uint8_t invert, uint8_t *alignPos) {
1507 // sanity check
1508 if (*size < 16) return 0xFFFF;
1510 int errCnt = 0, bestErr = 1000;
1511 uint16_t bitnum = 0, maxBits = 512, bestRun = 0;
1512 size_t i;
1514 //find correct start position [alignment]
1515 for (uint8_t k = 0; k < 2; k++) {
1517 for (i = k; i < *size - 1; i += 2) {
1519 if (bits[i] == bits[i + 1])
1520 errCnt++;
1522 if (errCnt > 50)
1523 break;
1526 if (bestErr > errCnt) {
1527 bestErr = errCnt;
1528 bestRun = k;
1529 if (g_debugMode == 2) prnt("DEBUG manrawdecode: bestErr %d | bestRun %u", bestErr, bestRun);
1531 errCnt = 0;
1534 *alignPos = bestRun;
1535 //decode
1536 for (i = bestRun; i < *size; i += 2) {
1537 if (bits[i] == 1 && (bits[i + 1] == 0)) {
1538 bits[bitnum++] = invert;
1539 } else if ((bits[i] == 0) && bits[i + 1] == 1) {
1540 bits[bitnum++] = invert ^ 1;
1541 } else {
1542 bits[bitnum++] = 7;
1544 if (bitnum > maxBits) break;
1546 *size = bitnum;
1547 return bestErr;
1550 //by marshmellow
1551 //demodulates strong heavily clipped samples
1552 //RETURN: num of errors. if 0, is ok.
1553 static uint16_t cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int invert, int high, int low, int *startIdx) {
1554 *startIdx = 0;
1555 size_t bitCnt = 0, smplCnt = 1, errCnt = 0, pos = 0;
1556 uint8_t cl_4 = clk / 4;
1557 uint8_t cl_2 = clk / 2;
1558 bool waveHigh = true;
1560 getNextHigh(bits, *size, high, &pos);
1561 // getNextLow(bits, *size, low, &pos);
1563 // do not skip first transition
1564 if ((pos > cl_2 - cl_4 - 1) && (pos <= clk + cl_4 + 1)) {
1565 bits[bitCnt++] = invert ^ 1;
1568 // sample counts, like clock = 32.. it tries to find 32/4 = 8, 32/2 = 16
1569 for (size_t i = pos; i < *size; i++) {
1570 if (bits[i] >= high && waveHigh) {
1571 smplCnt++;
1572 } else if (bits[i] <= low && !waveHigh) {
1573 smplCnt++;
1574 } else {
1575 //transition
1576 if ((bits[i] >= high && !waveHigh) || (bits[i] <= low && waveHigh)) {
1578 // 8 :: 8-2-1 = 5 8+2+1 = 11
1579 // 16 :: 16-4-1 = 11 16+4+1 = 21
1580 // 32 :: 32-8-1 = 23 32+8+1 = 41
1581 // 64 :: 64-16-1 = 47 64+16+1 = 81
1582 if (smplCnt > clk - cl_4 - 1) { //full clock
1584 if (smplCnt > clk + cl_4 + 1) {
1585 //too many samples
1586 errCnt++;
1587 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod ASK Modulation Error FULL at: %zu [%zu > %u]", i, smplCnt, clk + cl_4 + 1);
1588 bits[bitCnt++] = 7;
1589 } else if (waveHigh) {
1590 bits[bitCnt++] = invert;
1591 bits[bitCnt++] = invert;
1592 } else {
1593 bits[bitCnt++] = invert ^ 1;
1594 bits[bitCnt++] = invert ^ 1;
1596 if (*startIdx == 0) {
1597 *startIdx = i - clk;
1598 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod minus clock [%d]", *startIdx);
1600 waveHigh = !waveHigh;
1601 smplCnt = 0;
1603 // 16-8-1 = 7
1604 } else if (smplCnt > cl_2 - cl_4 - 1) { //half clock
1606 if (smplCnt > cl_2 + cl_4 + 1) { //too many samples
1607 errCnt++;
1608 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod ASK Modulation Error HALF at: %zu [%zu]", i, smplCnt);
1609 bits[bitCnt++] = 7;
1612 if (waveHigh) {
1613 bits[bitCnt++] = invert;
1614 } else {
1615 bits[bitCnt++] = invert ^ 1;
1618 if (*startIdx == 0) {
1619 *startIdx = i - cl_2;
1620 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod minus half clock [%d]", *startIdx);
1622 waveHigh = !waveHigh;
1623 smplCnt = 0;
1624 } else {
1625 smplCnt++;
1626 //transition bit oops
1628 } else { //haven't hit new high or new low yet
1629 smplCnt++;
1634 *size = bitCnt;
1636 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod Startidx %d", *startIdx);
1638 return errCnt;
1641 //by marshmellow
1642 //attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester
1643 int askdemod_ext(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType, int *startIdx) {
1645 if (*size == 0) return -1;
1647 if (signalprop.isnoise) {
1648 if (g_debugMode == 2) prnt("DEBUG (askdemod_ext) just noise detected - aborting");
1649 return -2;
1652 int start = DetectASKClock(bits, *size, clk, maxErr);
1653 if (*clk == 0 || start < 0) return -3;
1655 if (*invert != 1) *invert = 0;
1657 // amplify signal data.
1658 // ICEMAN todo,
1659 if (amp == 1) askAmp(bits, *size);
1661 if (g_debugMode == 2) prnt("DEBUG (askdemod_ext) clk %d, beststart %d, amp %d", *clk, start, amp);
1663 // Detect high and lows
1664 //25% clip in case highs and lows aren't clipped [marshmellow]
1665 int high, low;
1666 getHiLo(&high, &low, 75, 75);
1668 size_t errCnt = 0;
1669 // if clean clipped waves detected run alternate demod
1670 if (DetectCleanAskWave(bits, *size, high, low)) {
1672 //start pos from detect ask clock is 1/2 clock offset
1673 // NOTE: can be negative (demod assumes rest of wave was there)
1674 *startIdx = start - (*clk / 2);
1675 if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Clean wave detected --- startindex %d", *startIdx);
1677 errCnt = cleanAskRawDemod(bits, size, *clk, *invert, high, low, startIdx);
1679 if (askType) { //ask/manchester
1680 uint8_t alignPos = 0;
1681 errCnt = manrawdecode(bits, size, 0, &alignPos);
1682 *startIdx += ((*clk / 2) * alignPos);
1684 if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) CLEAN: startIdx %i, alignPos %u , bestError %zu", *startIdx, alignPos, errCnt);
1686 return errCnt;
1689 *startIdx = start - (*clk / 2);
1690 if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Weak wave detected: startIdx %i", *startIdx);
1692 int lastBit; // set first clock check - can go negative
1693 size_t i, bitnum = 0; // output counter
1694 uint8_t midBit = 0;
1695 uint8_t tol = 0; // clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
1696 if (*clk <= 32) tol = 1; // clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely
1697 size_t MaxBits = 3072; // max bits to collect
1698 lastBit = start - *clk;
1700 for (i = start; i < *size; ++i) {
1701 if (i - lastBit >= *clk - tol) {
1702 if (bits[i] >= high) {
1703 bits[bitnum++] = *invert;
1704 } else if (bits[i] <= low) {
1705 bits[bitnum++] = *invert ^ 1;
1706 } else if (i - lastBit >= *clk + tol) {
1707 if (bitnum > 0) {
1708 // if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Modulation Error at: %u", i);
1709 bits[bitnum++] = 7;
1710 errCnt++;
1712 } else { //in tolerance - looking for peak
1713 continue;
1715 midBit = 0;
1716 lastBit += *clk;
1717 } else if (i - lastBit >= (*clk / 2 - tol) && !midBit && !askType) {
1718 if (bits[i] >= high) {
1719 bits[bitnum++] = *invert;
1720 } else if (bits[i] <= low) {
1721 bits[bitnum++] = *invert ^ 1;
1722 } else if (i - lastBit >= *clk / 2 + tol) {
1723 if (bitnum > 0) {
1724 bits[bitnum] = bits[bitnum - 1];
1725 bitnum++;
1726 } else {
1727 bits[bitnum] = 0;
1728 bitnum++;
1730 } else { //in tolerance - looking for peak
1731 continue;
1733 midBit = 1;
1735 if (bitnum >= MaxBits) break;
1737 *size = bitnum;
1738 return errCnt;
1741 int askdemod(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType) {
1742 int start = 0;
1743 return askdemod_ext(bits, size, clk, invert, maxErr, amp, askType, &start);
1746 // by marshmellow - demodulate NRZ wave - requires a read with strong signal
1747 // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
1748 int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startIdx) {
1750 if (signalprop.isnoise) {
1751 if (g_debugMode == 2) prnt("DEBUG nrzRawDemod: just noise detected - quitting");
1752 return -1;
1755 size_t clkStartIdx = 0;
1756 *clk = DetectNRZClock(dest, *size, *clk, &clkStartIdx);
1757 if (*clk == 0) return -2;
1759 size_t i;
1760 int high, low;
1762 getHiLo(&high, &low, 75, 75);
1764 uint8_t bit = 0;
1765 //convert wave samples to 1's and 0's
1766 for (i = 20; i < *size - 20; i++) {
1767 if (dest[i] >= high) bit = 1;
1768 if (dest[i] <= low) bit = 0;
1769 dest[i] = bit;
1771 //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit)
1772 size_t lastBit = 0;
1773 size_t numBits = 0;
1774 for (i = 21; i < *size - 20; i++) {
1775 //if transition detected or large number of same bits - store the passed bits
1776 if (dest[i] != dest[i - 1] || (i - lastBit) == (10 * *clk)) {
1777 memset(dest + numBits, dest[i - 1] ^ *invert, (i - lastBit + (*clk / 4)) / *clk);
1778 numBits += (i - lastBit + (*clk / 4)) / *clk;
1779 if (lastBit == 0) {
1780 *startIdx = i - (numBits * *clk);
1781 if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx);
1783 lastBit = i - 1;
1786 *size = numBits;
1787 return 0;
1790 //translate wave to 11111100000 (1 for each short wave [higher freq] 0 for each long wave [lower freq])
1791 static size_t fsk_wave_demod(uint8_t *dest, size_t size, uint8_t fchigh, uint8_t fclow, int *startIdx) {
1793 if (size < 1024) return 0; // not enough samples
1795 if (fchigh == 0) fchigh = 10;
1796 if (fclow == 0) fclow = 8;
1798 //set the threshold close to 0 (graph) or 128 std to avoid static
1799 size_t preLastSample, LastSample = 0;
1800 size_t currSample = 0, last_transition = 0;
1801 size_t idx, numBits = 0;
1803 //find start of modulating data in trace
1804 idx = findModStart(dest, size, fchigh);
1805 // Need to threshold first sample
1806 dest[idx] = (dest[idx] < signalprop.mean) ? 0 : 1;
1808 last_transition = idx;
1809 idx++;
1811 // Definition: cycles between consecutive lo-hi transitions
1812 // Lets define some expected lengths. FSK1 is easier since it has bigger differences between.
1813 // FSK1 8/5
1814 // 50/8 = 6 | 40/8 = 5 | 64/8 = 8
1815 // 50/5 = 10 | 40/5 = 8 | 64/5 = 12
1817 // FSK2 10/8
1818 // 50/10 = 5 | 40/10 = 4 | 64/10 = 6
1819 // 50/8 = 6 | 40/8 = 5 | 64/8 = 8
1821 // count cycles between consecutive lo-hi transitions,
1822 // in practice due to noise etc we may end up with anywhere
1823 // To allow fuzz would mean +-1 on expected cycle width.
1824 // FSK1 8/5
1825 // 50/8 = 6 (5-7) | 40/8 = 5 (4-6) | 64/8 = 8 (7-9)
1826 // 50/5 = 10 (9-11) | 40/5 = 8 (7-9) | 64/5 = 12 (11-13)
1828 // FSK2 10/8
1829 // 50/10 = 5 (4-6) | 40/10 = 4 (3-5) | 64/10 = 6 (5-7)
1830 // 50/8 = 6 (5-7) | 40/8 = 5 (4-6) | 64/8 = 8 (7-9)
1832 // It easy to see to the overgaping, but luckily we the group value also, like 1111000001111
1833 // to separate between which bit to demodulate to.
1835 // process:
1836 // count width from 0-1 transition to 1-0.
1837 // determine the width is withing FUZZ_min and FUZZ_max tolerances
1838 // width should be divided with exp_one. i:e 6+7+6+2=21, 21/5 = 4,
1839 // the 1-0 to 0-1 width should be divided with exp_zero. Ie: 3+5+6+7 = 21/6 = 3
1841 for (; idx < size - 20; idx++) {
1843 // threshold current value
1844 dest[idx] = (dest[idx] < signalprop.mean) ? 0 : 1;
1846 // Check for 0->1 transition
1847 if (dest[idx - 1] < dest[idx]) {
1848 preLastSample = LastSample;
1849 LastSample = currSample;
1850 currSample = idx - last_transition;
1851 if (currSample < (fclow - 2)) { //0-5 = garbage noise (or 0-3)
1852 //do nothing with extra garbage
1853 } else if (currSample < (fchigh - 1)) { //6-8 = 8 sample waves (or 3-6 = 5)
1854 //correct previous 9 wave surrounded by 8 waves (or 6 surrounded by 5)
1855 if (numBits > 1 && LastSample > (fchigh - 2) && (preLastSample < (fchigh - 1))) {
1856 dest[numBits - 1] = 1;
1858 dest[numBits++] = 1;
1861 if (numBits > 0 && *startIdx == 0)
1862 *startIdx = idx - fclow;
1864 } else if (currSample > (fchigh + 1) && numBits < 3) { //12 + and first two bit = unusable garbage
1865 //do nothing with beginning garbage and reset.. should be rare..
1866 numBits = 0;
1867 } else if (currSample == (fclow + 1) && LastSample == (fclow - 1)) { // had a 7 then a 9 should be two 8's (or 4 then a 6 should be two 5's)
1868 dest[numBits++] = 1;
1869 if (numBits > 0 && *startIdx == 0) {
1870 *startIdx = idx - fclow;
1872 } else { //9+ = 10 sample waves (or 6+ = 7)
1873 dest[numBits++] = 0;
1874 if (numBits > 0 && *startIdx == 0) {
1875 *startIdx = idx - fchigh;
1878 last_transition = idx;
1881 return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
1884 //translate 11111100000 to 10
1885 //rfLen = clock, fchigh = larger field clock, fclow = smaller field clock
1886 static size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t clk, uint8_t invert, uint8_t fchigh, uint8_t fclow, int *startIdx) {
1888 uint8_t lastval = dest[0];
1889 size_t i = 0;
1890 size_t numBits = 0;
1891 uint32_t n = 1;
1892 uint8_t hclk = clk / 2;
1894 for (i = 1; i < size; i++) {
1895 n++;
1896 if (dest[i] == lastval) continue; //skip until we hit a transition
1898 //find out how many bits (n) we collected (use 1/2 clk tolerance)
1900 if (dest[i - 1] == 1)
1901 //if lastval was 1, we have a 1->0 crossing
1902 n = (n * fclow + hclk) / clk;
1903 else
1904 // 0->1 crossing
1905 n = (n * fchigh + hclk) / clk;
1907 if (n == 0)
1908 n = 1;
1910 //first transition - save startidx
1911 if (numBits == 0) {
1912 if (lastval == 1) { //high to low
1913 *startIdx += (fclow * i) - (n * clk);
1914 if (g_debugMode == 2) prnt("DEBUG (aggregate_bits) FSK startIdx %i, fclow*idx %zu, n*clk %u", *startIdx, fclow * i, n * clk);
1915 } else {
1916 *startIdx += (fchigh * i) - (n * clk);
1917 if (g_debugMode == 2) prnt("DEBUG (aggregate_bits) FSK startIdx %i, fchigh*idx %zu, n*clk %u", *startIdx, fchigh * i, n * clk);
1921 //add to our destination the bits we collected
1922 memset(dest + numBits, dest[i - 1] ^ invert, n);
1924 numBits += n;
1925 n = 0;
1926 lastval = dest[i];
1928 }//end for
1930 // if valid extra bits at the end were all the same frequency - add them in
1931 if (n > clk / fchigh) {
1932 if (dest[i - 2] == 1) {
1933 n = (n * fclow + clk / 2) / clk;
1934 } else {
1935 n = (n * fchigh + clk / 2) / clk;
1937 memset(dest + numBits, dest[i - 1] ^ invert, n);
1938 numBits += n;
1939 if (g_debugMode == 2) prnt("DEBUG (aggregate_bits) extra bits in the end");
1941 return numBits;
1944 //by marshmellow (from holiman's base)
1945 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
1946 size_t fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow, int *start_idx) {
1947 if (signalprop.isnoise) return 0;
1948 // FSK demodulator
1949 size = fsk_wave_demod(dest, size, fchigh, fclow, start_idx);
1950 if (g_debugMode == 2) prnt("DEBUG (fskdemod) got %zu bits", size);
1951 size = aggregate_bits(dest, size, rfLen, invert, fchigh, fclow, start_idx);
1952 if (g_debugMode == 2) prnt("DEBUG (fskdemod) got %zu bits", size);
1953 return size;
1956 // by marshmellow
1957 // convert psk1 demod to psk2 demod
1958 // only transition waves are 1s
1959 //TODO: Iceman - hard coded value 7, should be #define
1960 void psk1TOpsk2(uint8_t *bits, size_t size) {
1961 uint8_t lastbit = bits[0];
1962 for (size_t i = 1; i < size; i++) {
1963 //ignore errors
1964 if (bits[i] == 7) continue;
1966 if (lastbit != bits[i]) {
1967 lastbit = bits[i];
1968 bits[i] = 1;
1969 } else {
1970 bits[i] = 0;
1975 // by marshmellow
1976 // convert psk2 demod to psk1 demod
1977 // from only transition waves are 1s to phase shifts change bit
1978 void psk2TOpsk1(uint8_t *bits, size_t size) {
1979 uint8_t phase = 0;
1980 for (size_t i = 0; i < size; i++) {
1981 if (bits[i] == 1) {
1982 phase ^= 1;
1984 bits[i] = phase;
1988 //by marshmellow - demodulate PSK1 wave
1989 //uses wave lengths (# Samples)
1990 //TODO: Iceman - hard coded value 7, should be #define
1991 int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *startIdx) {
1993 // sanity check
1994 if (*size < 170) return -1;
1996 uint8_t curPhase = *invert;
1997 uint8_t fc = 0;
1998 size_t i = 0, numBits = 0, waveStart = 1, waveEnd, firstFullWave = 0, lastClkBit = 0;
1999 uint16_t fullWaveLen = 0, waveLenCnt, avgWaveVal = 0;
2000 uint16_t errCnt = 0, errCnt2 = 0;
2002 *clock = DetectPSKClock(dest, *size, *clock, &firstFullWave, &curPhase, &fc);
2003 if (*clock <= 0) return -1;
2004 //if clock detect found firstfullwave...
2005 uint16_t tol = fc / 2;
2006 if (firstFullWave == 0) {
2007 //find start of modulating data in trace
2008 i = findModStart(dest, *size, fc);
2009 //find first phase shift
2010 firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, i, fc, &fullWaveLen);
2011 if (firstFullWave == 0) {
2012 // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
2013 // so skip a little to ensure we are past any Start Signal
2014 firstFullWave = 160;
2015 memset(dest, curPhase, firstFullWave / *clock);
2016 } else {
2017 memset(dest, curPhase ^ 1, firstFullWave / *clock);
2019 } else {
2020 memset(dest, curPhase ^ 1, firstFullWave / *clock);
2022 //advance bits
2023 numBits += (firstFullWave / *clock);
2024 *startIdx = firstFullWave - (*clock * numBits) + 2;
2025 //set start of wave as clock align
2026 lastClkBit = firstFullWave;
2027 if (g_debugMode == 2) {
2028 prnt("DEBUG PSK: firstFullWave: %zu, waveLen: %u, startIdx %i", firstFullWave, fullWaveLen, *startIdx);
2029 prnt("DEBUG PSK: clk: %d, lastClkBit: %zu, fc: %u", *clock, lastClkBit, fc);
2032 waveStart = 0;
2033 dest[numBits++] = curPhase; //set first read bit
2034 for (i = firstFullWave + fullWaveLen - 1; i < *size - 3; i++) {
2035 //top edge of wave = start of new wave
2036 if (dest[i] + fc < dest[i + 1] && dest[i + 1] >= dest[i + 2]) {
2037 if (waveStart == 0) {
2038 waveStart = i + 1;
2039 avgWaveVal = dest[i + 1];
2040 } else { //waveEnd
2041 waveEnd = i + 1;
2042 waveLenCnt = waveEnd - waveStart;
2043 if (waveLenCnt > fc) {
2044 //this wave is a phase shift
2046 prnt("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d"
2047 , waveStart
2048 , waveLenCnt
2049 , lastClkBit + *clock - tol
2050 , i + 1
2051 , fc);
2053 if (i + 1 >= lastClkBit + *clock - tol) { //should be a clock bit
2054 curPhase ^= 1;
2055 dest[numBits++] = curPhase;
2056 lastClkBit += *clock;
2057 } else if (i < lastClkBit + 10 + fc) {
2058 //noise after a phase shift - ignore
2059 } else { //phase shift before supposed to based on clock
2060 errCnt++;
2061 dest[numBits++] = 7;
2063 } else if (i + 1 > lastClkBit + *clock + tol + fc) {
2064 lastClkBit += *clock; //no phase shift but clock bit
2065 dest[numBits++] = curPhase;
2066 } else if (waveLenCnt < fc - 1) { //wave is smaller than field clock (shouldn't happen often)
2067 errCnt2++;
2068 if (errCnt2 > 101) return errCnt2;
2069 avgWaveVal += dest[i + 1];
2070 continue;
2072 avgWaveVal = 0;
2073 waveStart = i + 1;
2076 avgWaveVal += dest[i + 1];
2078 *size = numBits;
2079 return errCnt;
2082 int pskRawDemod(uint8_t *dest, size_t *size, int *clock, int *invert) {
2083 int start_idx = 0;
2084 return pskRawDemod_ext(dest, size, clock, invert, &start_idx);
2088 // **********************************************************************************************
2089 // -----------------Tag format detection section-------------------------------------------------
2090 // **********************************************************************************************
2093 // by marshmellow
2094 // FSK Demod then try to locate an AWID ID
2095 int detectAWID(uint8_t *dest, size_t *size, int *waveStartIdx) {
2096 //make sure buffer has enough data (96bits * 50clock samples)
2097 if (*size < 96 * 50) return -1;
2099 if (signalprop.isnoise) return -2;
2101 // FSK2a demodulator clock 50, invert 1, fcHigh 10, fcLow 8
2102 *size = fskdemod(dest, *size, 50, 1, 10, 8, waveStartIdx); //awid fsk2a
2104 //did we get a good demod?
2105 if (*size < 96) return -3;
2107 size_t start_idx = 0;
2108 uint8_t preamble[] = {0, 0, 0, 0, 0, 0, 0, 1};
2109 if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx))
2110 return -4; //preamble not found
2112 // wrong size? (between to preambles)
2113 if (*size != 96) return -5;
2115 return (int)start_idx;
2118 //by marshmellow
2119 //takes 1s and 0s and searches for EM410x format - output EM ID
2120 int Em410xDecode(uint8_t *bits, size_t *size, size_t *start_idx, uint32_t *hi, uint64_t *lo) {
2121 // sanity check
2122 if (bits[1] > 1) return -1;
2123 if (*size < 64) return -2;
2125 uint8_t fmtlen;
2126 *start_idx = 0;
2128 // preamble 0111111111
2129 // include 0 in front to help get start pos
2130 uint8_t preamble[] = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
2131 if (!preambleSearch(bits, preamble, sizeof(preamble), size, start_idx))
2132 return -4;
2134 // (iceman) if the preamble doesn't find two occuriences, this identification fails.
2135 fmtlen = (*size == 128) ? 22 : 10;
2137 //skip last 4bit parity row for simplicity
2138 *size = removeParity(bits, *start_idx + sizeof(preamble), 5, 0, fmtlen * 5);
2140 switch (*size) {
2141 case 40: {
2142 // std em410x format
2143 *hi = 0;
2144 *lo = ((uint64_t)(bytebits_to_byte(bits, 8)) << 32) | (bytebits_to_byte(bits + 8, 32));
2145 break;
2147 case 88: {
2148 // long em format
2149 *hi = (bytebits_to_byte(bits, 24));
2150 *lo = ((uint64_t)(bytebits_to_byte(bits + 24, 32)) << 32) | (bytebits_to_byte(bits + 24 + 32, 32));
2151 break;
2153 default:
2154 return -6;
2156 return 1;
2160 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
2161 int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx) {
2162 //make sure buffer has data
2163 if (*size < 96 * 50) return -1;
2165 if (signalprop.isnoise) return -2;
2167 // FSK demodulator fsk2a so invert and fc/10/8
2168 *size = fskdemod(dest, *size, 50, 1, 10, 8, waveStartIdx); //hid fsk2a
2170 //did we get a good demod?
2171 if (*size < 96 * 2) return -3;
2173 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
2174 size_t start_idx = 0;
2175 uint8_t preamble[] = {0, 0, 0, 1, 1, 1, 0, 1};
2176 if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx))
2177 return -4; //preamble not found
2179 // wrong size? (between to preambles)
2180 //if (*size != 96) return -5;
2182 size_t num_start = start_idx + sizeof(preamble);
2183 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
2184 for (size_t idx = num_start; (idx - num_start) < *size - sizeof(preamble); idx += 2) {
2185 if (dest[idx] == dest[idx + 1]) {
2186 return -5; //not manchester data
2188 *hi2 = (*hi2 << 1) | (*hi >> 31);
2189 *hi = (*hi << 1) | (*lo >> 31);
2190 //Then, shift in a 0 or one into low
2191 *lo <<= 1;
2192 if (dest[idx] && !dest[idx + 1]) // 1 0
2193 *lo |= 1;
2194 else // 0 1
2195 *lo |= 0;
2197 return (int)start_idx;
2200 int detectIOProx(uint8_t *dest, size_t *size, int *waveStartIdx) {
2201 //make sure buffer has data
2202 if (*size < 66 * 64) return -1;
2204 if (signalprop.isnoise) return -2;
2206 // FSK demodulator RF/64, fsk2a so invert, and fc/10/8
2207 *size = fskdemod(dest, *size, 64, 1, 10, 8, waveStartIdx); //io fsk2a
2209 //did we get enough demod data?
2210 if (*size < 64) return -3;
2212 //Index map
2213 //0 10 20 30 40 50 60
2214 //| | | | | | |
2215 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
2216 //-----------------------------------------------------------------------------
2217 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
2219 //XSF(version)facility:codeone+codetwo
2221 size_t start_idx = 0;
2222 uint8_t preamble[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
2223 if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx))
2224 return -4; //preamble not found
2226 // wrong size? (between to preambles)
2227 if (*size != 64) return -5;
2229 if (!dest[start_idx + 8]
2230 && dest[start_idx + 17] == 1
2231 && dest[start_idx + 26] == 1
2232 && dest[start_idx + 35] == 1
2233 && dest[start_idx + 44] == 1
2234 && dest[start_idx + 53] == 1) {
2235 //confirmed proper separator bits found
2236 //return start position
2237 return (int) start_idx;
2239 return -6;