text
[RRG-proxmark3.git] / common / lfdemod.c
blobb07dc22351954862805ea20af3e9eaf2d1bbc1ca
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 static 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 static size_t removeEm410xParity(uint8_t *bits, size_t startIdx, bool isLong, bool *validShort, bool *validShortExtended, bool *validLong) {
257 uint32_t parityWd = 0;
258 size_t bitCnt = 0;
259 bool validColParity = false;
260 bool validRowParity = true;
261 bool validRowParitySkipColP = true;
262 *validShort = false;
263 *validShortExtended = false;
264 *validLong = false;
265 uint8_t bLen = isLong ? 110 : 55;
266 uint16_t parityCol[4] = { 0, 0, 0, 0 };
267 for (int word = 0; word < bLen; word += 5) {
268 for (int bit = 0; bit < 5; bit++) {
269 if (word + bit >= bLen) break;
270 parityWd = (parityWd << 1) | bits[startIdx + word + bit];
271 if ((word <= 50) && (bit < 4))
272 parityCol[bit] = (parityCol[bit] << 1) | bits[startIdx + word + bit];
273 bits[bitCnt++] = (bits[startIdx + word + bit]);
275 if (word + 5 > bLen) break;
277 bitCnt--; // overwrite parity with next data
278 validRowParity &= parityTest(parityWd, 5, 0) != 0;
279 if (word == 50) { // column parity nibble on short EM and on Electra
280 validColParity = parityTest(parityCol[0], 11, 0) != 0;
281 validColParity &= parityTest(parityCol[1], 11, 0) != 0;
282 validColParity &= parityTest(parityCol[2], 11, 0) != 0;
283 validColParity &= parityTest(parityCol[3], 11, 0) != 0;
284 } else {
285 validRowParitySkipColP &= parityTest(parityWd, 5, 0) != 0;
287 parityWd = 0;
289 if (!isLong && validRowParitySkipColP && validColParity) {
290 *validShort = true;
292 if (isLong && validRowParity) {
293 *validLong = true;
295 if (isLong && validRowParitySkipColP && validColParity) {
296 *validShortExtended = true;
298 if (*validShort || *validShortExtended || *validLong) {
299 return bitCnt;
300 } else {
301 return 0;
305 // by marshmellow
306 // takes a array of binary values, length of bits per parity (includes parity bit),
307 // Parity Type (1 for odd; 0 for even; 2 Always 1's; 3 Always 0's), and binary Length (length to run)
308 // Make sure *dest is long enough to store original sourceLen + #_of_parities_to_be_added
309 size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType) {
310 uint32_t parityWd = 0;
311 size_t j = 0, bitCnt = 0;
312 for (int word = 0; word < sourceLen; word += pLen - 1) {
313 for (int bit = 0; bit < pLen - 1; bit++) {
314 parityWd = (parityWd << 1) | src[word + bit];
315 dest[j++] = (src[word + bit]);
317 // if parity fails then return 0
318 switch (pType) {
319 case 3:
320 dest[j++] = 0;
321 break; // marker bit which should be a 0
322 case 2:
323 dest[j++] = 1;
324 break; // marker bit which should be a 1
325 default:
326 dest[j++] = parityTest(parityWd, pLen - 1, pType) ^ 1;
327 break;
329 bitCnt += pLen;
330 parityWd = 0;
332 // if we got here then all the parities passed
333 //return ID start index and size
334 return bitCnt;
337 // array must be size dividable with 8
338 int bits_to_array(const uint8_t *bits, size_t size, uint8_t *dest) {
339 if ((size == 0) || (size % 8) != 0) return PM3_EINVARG;
341 for (uint32_t i = 0; i < (size / 8); i++)
342 dest[i] = bytebits_to_byte((uint8_t *) bits + (i * 8), 8);
344 return PM3_SUCCESS;
347 uint32_t bytebits_to_byte(uint8_t *src, size_t numbits) {
348 uint32_t num = 0;
349 for (int i = 0 ; i < numbits ; i++) {
350 num = (num << 1) | (*src);
351 src++;
353 return num;
356 //least significant bit first
357 uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits) {
358 uint32_t num = 0;
359 for (int i = 0 ; i < numbits ; i++) {
360 num = (num << 1) | *(src + (numbits - (i + 1)));
362 return num;
365 //by marshmellow
366 //search for given preamble in given BitStream and return success = TRUE or fail = FALSE and startIndex and length
367 bool preambleSearch(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx) {
368 return preambleSearchEx(bits, preamble, pLen, size, startIdx, false);
370 //by marshmellow
371 // 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
372 // fineone does not look for a repeating preamble for em4x05/4x69 sends preamble once, so look for it once in the first pLen bits
373 //(iceman) FINDONE, only finds start index. NOT SIZE!. I see Em410xDecode (lfdemod.c) uses SIZE to determine success
374 bool preambleSearchEx(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx, bool findone) {
375 // Sanity check. If preamble length is bigger than bits length.
376 if (*size <= pLen)
377 return false;
379 uint8_t foundCnt = 0;
380 for (size_t idx = 0; idx < *size - pLen; idx++) {
381 if (memcmp(bits + idx, preamble, pLen) == 0) {
382 //first index found
383 foundCnt++;
384 if (foundCnt == 1) {
385 if (g_debugMode >= 1) prnt("DEBUG: (preambleSearchEx) preamble found at %zu", idx);
386 *startIdx = idx;
387 if (findone)
388 return true;
390 if (foundCnt == 2) {
391 if (g_debugMode >= 1) prnt("DEBUG: (preambleSearchEx) preamble 2 found at %zu", idx);
392 *size = idx - *startIdx;
393 return true;
397 return (foundCnt > 0);
400 // find start of modulating data (for fsk and psk) in case of beginning noise or slow chip startup.
401 static size_t findModStart(uint8_t *src, size_t size, uint8_t expWaveSize) {
402 size_t i = 0;
403 size_t waveSizeCnt = 0;
404 uint8_t thresholdCnt = 0;
405 bool isAboveThreshold = src[i++] >= signalprop.mean; //FSK_PSK_THRESHOLD;
406 for (; i < size - 20; i++) {
407 if (src[i] < signalprop.mean && isAboveThreshold) {
408 thresholdCnt++;
409 if (thresholdCnt > 2 && waveSizeCnt < expWaveSize + 1) break;
410 isAboveThreshold = false;
411 waveSizeCnt = 0;
412 } else if (src[i] >= signalprop.mean && !isAboveThreshold) {
413 thresholdCnt++;
414 if (thresholdCnt > 2 && waveSizeCnt < expWaveSize + 1) break;
415 isAboveThreshold = true;
416 waveSizeCnt = 0;
417 } else {
418 waveSizeCnt++;
420 if (thresholdCnt > 10) break;
422 if (g_debugMode == 2) prnt("DEBUG: threshold Count reached at index %zu, count: %u", i, thresholdCnt);
423 return i;
426 static int getClosestClock(int testclk) {
427 uint16_t clocks[] = {8, 16, 32, 40, 50, 64, 100, 128, 256, 384};
428 uint8_t limit[] = {1, 2, 4, 4, 5, 8, 8, 8, 8, 8};
430 for (uint8_t i = 0; i < 10; i++) {
431 if (testclk >= clocks[i] - limit[i] && testclk <= clocks[i] + limit[i])
432 return clocks[i];
434 return 0;
437 void getNextLow(uint8_t *samples, size_t size, int low, size_t *i) {
438 while ((samples[*i] > low) && (*i < size))
439 *i += 1;
442 void getNextHigh(uint8_t *samples, size_t size, int high, size_t *i) {
443 while ((samples[*i] < high) && (*i < size))
444 *i += 1;
447 // load wave counters
448 bool loadWaveCounters(uint8_t *samples, size_t size, int lowToLowWaveLen[], int highToLowWaveLen[], int *waveCnt, int *skip, int *minClk, int *high, int *low) {
449 size_t i = 0;
450 //size_t testsize = (size < 512) ? size : 512;
452 // just noise - no super good detection. good enough
453 if (signalprop.isnoise) {
454 if (g_debugMode == 2) prnt("DEBUG STT: just noise detected - quitting");
455 return false;
458 getHiLo(high, low, 80, 80);
460 // get to first full low to prime loop and skip incomplete first pulse
461 getNextHigh(samples, size, *high, &i);
462 getNextLow(samples, size, *low, &i);
463 *skip = i;
465 // populate tmpbuff buffer with pulse lengths
466 while (i < size) {
467 // measure from low to low
468 size_t firstLow = i;
469 //find first high point for this wave
470 getNextHigh(samples, size, *high, &i);
471 size_t firstHigh = i;
473 getNextLow(samples, size, *low, &i);
475 if (*waveCnt >= (size / LOWEST_DEFAULT_CLOCK))
476 break;
478 highToLowWaveLen[*waveCnt] = i - firstHigh; //first high to first low
479 lowToLowWaveLen[*waveCnt] = i - firstLow;
480 *waveCnt += 1;
481 if (i - firstLow < *minClk && i < size) {
482 *minClk = i - firstLow;
485 return true;
488 size_t pskFindFirstPhaseShift(uint8_t *samples, size_t size, uint8_t *curPhase, size_t waveStart, uint16_t fc, uint16_t *fullWaveLen) {
489 uint16_t loopCnt = (size + 3 < 4096) ? size : 4096; //don't need to loop through entire array...
491 uint16_t avgWaveVal = 0, lastAvgWaveVal;
492 size_t i = waveStart, waveEnd, waveLenCnt, firstFullWave;
493 for (; i < loopCnt; i++) {
494 // find peak // was "samples[i] + fc" but why? must have been used to weed out some wave error... removed..
495 if (samples[i] < samples[i + 1] && samples[i + 1] >= samples[i + 2]) {
496 waveEnd = i + 1;
497 if (g_debugMode == 2) prnt("DEBUG PSK: waveEnd: %zu, waveStart: %zu", waveEnd, waveStart);
498 waveLenCnt = waveEnd - waveStart;
499 if (waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack
500 lastAvgWaveVal = avgWaveVal / (waveLenCnt);
501 firstFullWave = waveStart;
502 *fullWaveLen = waveLenCnt;
503 //if average wave value is > graph 0 then it is an up wave or a 1 (could cause inverting)
504 if (lastAvgWaveVal > FSK_PSK_THRESHOLD) *curPhase ^= 1;
505 return firstFullWave;
507 waveStart = i + 1;
508 avgWaveVal = 0;
510 avgWaveVal += samples[i + 2];
512 return 0;
515 //by marshmellow
516 //amplify based on ask edge detection - not accurate enough to use all the time
517 void askAmp(uint8_t *bits, size_t size) {
518 uint8_t last = 128;
519 for (size_t i = 1; i < size; ++i) {
520 if (bits[i] - bits[i - 1] >= 30) //large jump up
521 last = 255;
522 else if (bits[i - 1] - bits[i] >= 20) //large jump down
523 last = 0;
525 bits[i] = last;
529 // iceman, simplify this
530 uint32_t manchesterEncode2Bytes(uint16_t datain) {
531 uint32_t output = 0;
532 for (uint8_t i = 0; i < 16; i++) {
533 uint8_t b = (datain >> (15 - i) & 1);
534 output |= (1 << (((15 - i) * 2) + b));
536 return output;
539 void manchesterEncodeUint32(uint32_t data_in, uint8_t bitlen_in, uint8_t *bits_out, uint16_t *index) {
540 for (int i = bitlen_in - 1; i >= 0; i--) {
541 if ((data_in >> i) & 1) {
542 bits_out[(*index)++] = 1;
543 bits_out[(*index)++] = 0;
544 } else {
545 bits_out[(*index)++] = 0;
546 bits_out[(*index)++] = 1;
551 //by marshmellow
552 //encode binary data into binary manchester
553 //NOTE: bitstream must have triple the size of "size" available in memory to do the swap
554 int ManchesterEncode(uint8_t *bits, size_t size) {
555 //allow up to 4096b out (means bits must be at least 2048+4096 to handle the swap)
556 size = (size > 2048) ? 2048 : size;
557 size_t modIdx = size;
558 size_t i;
559 for (size_t idx = 0; idx < size; idx++) {
560 bits[idx + modIdx++] = bits[idx];
561 bits[idx + modIdx++] = bits[idx] ^ 1;
563 for (i = 0; i < (size * 2); i++) {
564 bits[i] = bits[i + size];
566 return i;
569 // by marshmellow
570 // to detect a wave that has heavily clipped (clean) samples
571 // loop 1024 samples, if 250 of them is deemed maxed out, we assume the wave is clipped.
572 bool DetectCleanAskWave(uint8_t *dest, size_t size, uint8_t high, uint8_t low) {
573 bool allArePeaks = true;
574 uint16_t cntPeaks = 0;
575 size_t loopEnd = 1024 + 160;
577 // sanity check
578 if (loopEnd > size) loopEnd = size;
580 for (size_t i = 160; i < loopEnd; i++) {
582 if (dest[i] > low && dest[i] < high)
583 allArePeaks = false;
584 else {
585 cntPeaks++;
586 //if (g_debugMode == 2) prnt("DEBUG DetectCleanAskWave: peaks (200) %u", cntPeaks);
587 if (cntPeaks > 200) return true;
591 if (allArePeaks == false) {
592 if (g_debugMode == 2) prnt("DEBUG DetectCleanAskWave: peaks (200) %u", cntPeaks);
593 if (cntPeaks > 200) return true;
595 return allArePeaks;
599 // **********************************************************************************************
600 // -------------------Clock / Bitrate Detection Section------------------------------------------
601 // **********************************************************************************************
604 // by marshmellow
605 // to help detect clocks on heavily clipped samples
606 // based on count of low to low
607 int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clock) {
608 size_t i = 100;
609 size_t minClk = 512;
610 uint16_t shortestWaveIdx = 0;
612 // get to first full low to prime loop and skip incomplete first pulse
613 getNextHigh(dest, size, high, &i);
614 getNextLow(dest, size, low, &i);
616 if (i == size)
617 return -1;
618 if (size < 512)
619 return -2;
621 // clock, numoftimes, first idx
622 uint16_t tmpclk[10][3] = {
623 {8, 0, 0},
624 {16, 0, 0},
625 {32, 0, 0},
626 {40, 0, 0},
627 {50, 0, 0},
628 {64, 0, 0},
629 {100, 0, 0},
630 {128, 0, 0},
631 {256, 0, 0},
632 {384, 0, 0},
635 // loop through all samples (well, we don't want to go out-of-bounds)
636 while (i < (size - 512)) {
637 // measure from low to low
638 size_t startwave = i;
640 getNextHigh(dest, size, high, &i);
641 getNextLow(dest, size, low, &i);
643 //get minimum measured distance
644 if (i - startwave < minClk && i < size) {
645 minClk = i - startwave;
646 shortestWaveIdx = startwave;
649 int foo = getClosestClock(minClk);
650 if (foo > 0) {
651 for (uint8_t j = 0; j < 10; j++) {
652 if (tmpclk[j][0] == foo) {
653 tmpclk[j][1]++;
655 if (tmpclk[j][2] == 0) {
656 tmpclk[j][2] = shortestWaveIdx;
658 break;
664 // find the clock with most hits and it the first index it was encountered.
665 int max = 0;
666 for (uint8_t j = 0; j < 10; j++) {
667 if (g_debugMode == 2) {
668 prnt("DEBUG, ASK, clocks %u | hits %u | idx %u"
669 , tmpclk[j][0]
670 , tmpclk[j][1]
671 , tmpclk[j][2]
674 if (max < tmpclk[j][1]) {
675 *clock = tmpclk[j][0];
676 shortestWaveIdx = tmpclk[j][2];
677 max = tmpclk[j][1];
681 if (*clock == 0)
682 return -1;
684 return shortestWaveIdx;
687 // by marshmellow
688 // not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
689 // maybe somehow adjust peak trimming value based on samples to fix?
690 // return start index of best starting position for that clock and return clock (by reference)
691 int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) {
693 //don't need to loop through entire array. (cotag has clock of 384)
694 uint16_t loopCnt = 2000;
696 // not enough samples
697 if (size <= loopCnt + 60) {
698 if (g_debugMode == 2) prnt("DEBUG DetectASKClock: not enough samples - aborting");
699 return -1;
702 // just noise - no super good detection. good enough
703 if (signalprop.isnoise) {
704 if (g_debugMode == 2) prnt("DEBUG DetectASKClock: just noise detected - aborting");
705 return -2;
708 size_t i = 1;
709 uint16_t num_clks = 9;
710 // first 255 value pos0 is placeholder for user inputed clock.
711 uint16_t clk[] = {255, 8, 16, 32, 40, 50, 64, 100, 128, 255};
713 // sometimes there is a strange end wave - filter out this
714 size -= 60;
716 // What is purpose?
717 // already have a valid clock?
718 uint8_t found_clk = 0;
719 for (; i < num_clks; ++i) {
720 if (clk[i] == *clock) {
721 found_clk = i;
725 // threshold 75% of high, low peak
726 int peak_hi, peak_low;
727 getHiLo(&peak_hi, &peak_low, 75, 75);
729 // test for large clean, STRONG, CLIPPED peaks
731 if (!found_clk) {
733 if (DetectCleanAskWave(dest, size, peak_hi, peak_low)) {
735 int idx = DetectStrongAskClock(dest, size, peak_hi, peak_low, clock);
736 if (g_debugMode == 2)
737 prnt("DEBUG ASK: DetectASKClock Clean ASK Wave detected: clk %i, Best Starting Position: %i", *clock, idx);
739 // return shortest wave start position
740 if (idx > -1)
741 return idx;
744 // test for weak peaks
746 // test clock if given as cmd parameter
747 if (*clock > 0)
748 clk[0] = *clock;
750 uint8_t clkCnt, tol;
751 size_t j = 0;
752 uint16_t bestErr[] = {1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
753 uint8_t bestStart[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
754 size_t errCnt, arrLoc, loopEnd;
756 if (found_clk) {
757 clkCnt = found_clk;
758 num_clks = found_clk + 1;
759 } else {
760 clkCnt = 1;
763 //test each valid clock from smallest to greatest to see which lines up
764 for (; clkCnt < num_clks; clkCnt++) {
765 if (clk[clkCnt] <= 32) {
766 tol = 1;
767 } else {
768 tol = 0;
770 //if no errors allowed - keep start within the first clock
771 if (!maxErr && size > clk[clkCnt] * 2 + tol && clk[clkCnt] < 128)
772 loopCnt = clk[clkCnt] * 2;
774 bestErr[clkCnt] = 1000;
776 //try lining up the peaks by moving starting point (try first few clocks)
778 // get to first full low to prime loop and skip incomplete first pulse
779 getNextHigh(dest, size, peak_hi, &j);
780 getNextLow(dest, size, peak_low, &j);
782 for (; j < loopCnt; j++) {
783 errCnt = 0;
784 // now that we have the first one lined up test rest of wave array
785 loopEnd = ((size - j - tol) / clk[clkCnt]) - 1;
786 for (i = 0; i < loopEnd; ++i) {
787 arrLoc = j + (i * clk[clkCnt]);
788 if (dest[arrLoc] >= peak_hi || dest[arrLoc] <= peak_low) {
789 } else if (dest[arrLoc - tol] >= peak_hi || dest[arrLoc - tol] <= peak_low) {
790 } else if (dest[arrLoc + tol] >= peak_hi || dest[arrLoc + tol] <= peak_low) {
791 } else { //error no peak detected
792 errCnt++;
795 // if we found no errors then we can stop here and a low clock (common clocks)
796 // this is correct one - return this clock
797 // if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, err %d, startpos %d, endpos %d", clk[clkCnt], errCnt, j, i);
798 if (errCnt == 0 && clkCnt < 7) {
799 if (!found_clk)
800 *clock = clk[clkCnt];
801 return j;
803 // if we found errors see if it is lowest so far and save it as best run
804 if (errCnt < bestErr[clkCnt]) {
805 bestErr[clkCnt] = errCnt;
806 bestStart[clkCnt] = j;
811 uint8_t k, best = 0;
813 for (k = 1; k < num_clks; ++k) {
814 if (bestErr[k] < bestErr[best]) {
815 if (bestErr[k] == 0) bestErr[k] = 1;
816 // current best bit to error ratio vs new bit to error ratio
817 if ((size / clk[best]) / bestErr[best] < (size / clk[k]) / bestErr[k]) {
818 best = k;
821 //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]);
824 bool chg = false;
825 for (i = 0; i < ARRAYLEN(bestErr); i++) {
826 chg = (bestErr[i] != 1000);
827 if (chg)
828 break;
829 chg = (bestStart[i] != 0);
830 if (chg)
831 break;
834 // just noise - no super good detection. good enough
835 if (chg == false) {
836 if (g_debugMode == 2) prnt("DEBUG DetectASKClock: no good values detected - aborting");
837 return -2;
840 if (!found_clk)
841 *clock = clk[best];
843 return bestStart[best];
846 int DetectStrongNRZClk(uint8_t *dest, size_t size, int peak, int low, bool *strong) {
847 //find shortest transition from high to low
848 *strong = false;
849 size_t i = 0;
850 size_t transition1 = 0;
851 int lowestTransition = 255;
852 bool lastWasHigh = false;
853 size_t transitionSampleCount = 0;
854 //find first valid beginning of a high or low wave
855 while ((dest[i] >= peak || dest[i] <= low) && (i < size))
856 ++i;
857 while ((dest[i] < peak && dest[i] > low) && (i < size))
858 ++i;
860 lastWasHigh = (dest[i] >= peak);
862 if (i == size)
863 return 0;
865 transition1 = i;
867 for (; i < size; i++) {
868 if ((dest[i] >= peak && !lastWasHigh) || (dest[i] <= low && lastWasHigh)) {
869 lastWasHigh = (dest[i] >= peak);
870 if (i - transition1 < lowestTransition)
871 lowestTransition = i - transition1;
872 transition1 = i;
873 } else if (dest[i] < peak && dest[i] > low) {
874 transitionSampleCount++;
877 if (lowestTransition == 255)
878 lowestTransition = 0;
880 if (g_debugMode == 2) prnt("DEBUG NRZ: detectstrongNRZclk smallest wave: %d", lowestTransition);
881 // if less than 10% of the samples were not peaks (or 90% were peaks) then we have a strong wave
882 if (transitionSampleCount / size < 10) {
883 *strong = true;
884 lowestTransition = getClosestClock(lowestTransition);
886 return lowestTransition;
889 //by marshmellow
890 //detect nrz clock by reading #peaks vs no peaks(or errors)
891 int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx) {
892 size_t i = 0;
893 uint8_t clk[] = {8, 16, 32, 40, 50, 64, 100, 128, 255};
894 size_t loopCnt = 4096; //don't need to loop through entire array...
896 //if we already have a valid clock quit
897 for (; i < 8; ++i)
898 if (clk[i] == clock) return clock;
900 if (size < 20) return 0;
901 // size must be larger than 20 here
902 if (size < loopCnt) loopCnt = size - 20;
905 // just noise - no super good detection. good enough
906 if (signalprop.isnoise) {
907 if (g_debugMode == 2) prnt("DEBUG DetectNZRClock: just noise detected - quitting");
908 return 0;
911 //get high and low peak
912 int peak, low;
913 //getHiLo(dest, loopCnt, &peak, &low, 90, 90);
914 getHiLo(&peak, &low, 90, 90);
916 bool strong = false;
917 int lowestTransition = DetectStrongNRZClk(dest, size - 20, peak, low, &strong);
918 if (strong) return lowestTransition;
919 size_t ii;
920 uint8_t clkCnt;
921 uint8_t tol = 0;
922 uint16_t smplCnt = 0;
923 int16_t peakcnt = 0;
924 int16_t peaksdet[] = {0, 0, 0, 0, 0, 0, 0, 0};
925 uint16_t minPeak = 255;
926 bool firstpeak = true;
927 //test for large clipped waves - ignore first peak
928 for (i = 0; i < loopCnt; i++) {
929 if (dest[i] >= peak || dest[i] <= low) {
930 if (firstpeak) continue;
931 smplCnt++;
932 } else {
933 firstpeak = false;
934 if (smplCnt > 0) {
935 if (minPeak > smplCnt && smplCnt > 7) minPeak = smplCnt;
936 peakcnt++;
937 if (g_debugMode == 2) prnt("DEBUG NRZ: minPeak: %d, smplCnt: %d, peakcnt: %d", minPeak, smplCnt, peakcnt);
938 smplCnt = 0;
942 if (minPeak < 8) return 0;
944 bool errBitHigh = 0, bitHigh = 0, lastPeakHigh = 0;
945 uint8_t ignoreCnt = 0, ignoreWindow = 4;
946 int lastBit = 0;
947 size_t bestStart[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
948 peakcnt = 0;
949 //test each valid clock from smallest to greatest to see which lines up
950 for (clkCnt = 0; clkCnt < 8; ++clkCnt) {
951 //ignore clocks smaller than smallest peak
952 if (clk[clkCnt] < minPeak - (clk[clkCnt] / 4)) continue;
953 //try lining up the peaks by moving starting point (try first 256)
954 for (ii = 20; ii < loopCnt; ++ii) {
955 if ((dest[ii] >= peak) || (dest[ii] <= low)) {
956 peakcnt = 0;
957 bitHigh = false;
958 ignoreCnt = 0;
959 lastBit = ii - clk[clkCnt];
960 //loop through to see if this start location works
961 for (i = ii; i < size - 20; ++i) {
962 //if we are at a clock bit
963 if ((i >= lastBit + clk[clkCnt] - tol) && (i <= lastBit + clk[clkCnt] + tol)) {
964 //test high/low
965 if (dest[i] >= peak || dest[i] <= low) {
966 //if same peak don't count it
967 if ((dest[i] >= peak && !lastPeakHigh) || (dest[i] <= low && lastPeakHigh)) {
968 peakcnt++;
970 lastPeakHigh = (dest[i] >= peak);
971 bitHigh = true;
972 errBitHigh = false;
973 ignoreCnt = ignoreWindow;
974 lastBit += clk[clkCnt];
975 } else if (i == lastBit + clk[clkCnt] + tol) {
976 lastBit += clk[clkCnt];
978 //else if not a clock bit and no peaks
979 } else if (dest[i] < peak && dest[i] > low) {
980 if (ignoreCnt == 0) {
981 bitHigh = false;
982 if (errBitHigh == true)
983 peakcnt--;
984 errBitHigh = false;
985 } else {
986 ignoreCnt--;
988 // else if not a clock bit but we have a peak
989 } else if ((dest[i] >= peak || dest[i] <= low) && (!bitHigh)) {
990 //error bar found no clock...
991 errBitHigh = true;
994 if (peakcnt > peaksdet[clkCnt]) {
995 bestStart[clkCnt] = ii;
996 peaksdet[clkCnt] = peakcnt;
1002 uint8_t best = 0;
1003 for (int m = 7; m > 0; m--) {
1004 if ((peaksdet[m] >= (peaksdet[best] - 1)) && (peaksdet[m] <= peaksdet[best] + 1) && lowestTransition) {
1005 if (clk[m] > (lowestTransition - (clk[m] / 8)) && clk[m] < (lowestTransition + (clk[m] / 8))) {
1006 best = m;
1008 } else if (peaksdet[m] > peaksdet[best]) {
1009 best = m;
1011 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);
1013 *clockStartIdx = bestStart[best];
1014 return clk[best];
1017 //by marshmellow
1018 //countFC is to detect the field clock lengths.
1019 //counts and returns the 2 most common wave lengths
1020 //mainly used for FSK field clock detection
1021 uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj) {
1022 uint8_t fcLens[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1023 uint16_t fcCnts[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1024 uint8_t fcLensFnd = 0;
1025 uint8_t lastFCcnt = 0;
1026 uint8_t fcCounter = 0;
1027 size_t i;
1028 if (size < 180) return 0;
1030 // prime i to first up transition
1031 for (i = 160; i < size - 20; i++)
1032 if (bits[i] > bits[i - 1] && bits[i] >= bits[i + 1])
1033 break;
1035 for (; i < size - 20; i++) {
1036 if (bits[i] > bits[i - 1] && bits[i] >= bits[i + 1]) {
1037 // new up transition
1038 fcCounter++;
1039 if (fskAdj) {
1040 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
1041 if (lastFCcnt == 5 && fcCounter == 9) fcCounter--;
1043 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
1044 if ((fcCounter == 9) || fcCounter == 4) fcCounter++;
1045 // save last field clock count (fc/xx)
1046 lastFCcnt = fcCounter;
1048 // find which fcLens to save it to:
1049 for (int m = 0; m < 15; m++) {
1050 if (fcLens[m] == fcCounter) {
1051 fcCnts[m]++;
1052 fcCounter = 0;
1053 break;
1056 if (fcCounter > 0 && fcLensFnd < 15) {
1057 //add new fc length
1058 fcCnts[fcLensFnd]++;
1059 fcLens[fcLensFnd++] = fcCounter;
1061 fcCounter = 0;
1062 } else {
1063 // count sample
1064 fcCounter++;
1068 uint8_t best1 = 14, best2 = 14, best3 = 14;
1069 uint16_t maxCnt1 = 0;
1070 // go through fclens and find which ones are bigest 2
1071 for (i = 0; i < 15; i++) {
1072 // get the 3 best FC values
1073 if (fcCnts[i] > maxCnt1) {
1074 best3 = best2;
1075 best2 = best1;
1076 maxCnt1 = fcCnts[i];
1077 best1 = i;
1078 } else if (fcCnts[i] > fcCnts[best2]) {
1079 best3 = best2;
1080 best2 = i;
1081 } else if (fcCnts[i] > fcCnts[best3]) {
1082 best3 = i;
1084 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]);
1085 if (fcLens[i] == 0) break;
1088 if (fcLens[best1] == 0) return 0;
1089 uint8_t fcH = 0, fcL = 0;
1090 if (fcLens[best1] > fcLens[best2]) {
1091 fcH = fcLens[best1];
1092 fcL = fcLens[best2];
1093 } else {
1094 fcH = fcLens[best2];
1095 fcL = fcLens[best1];
1097 if ((size - 180) / fcH / 3 > fcCnts[best1] + fcCnts[best2]) {
1098 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]);
1099 return 0; //lots of waves not psk or fsk
1101 // TODO: take top 3 answers and compare to known Field clocks to get top 2
1103 uint16_t fcs = (((uint16_t)fcH) << 8) | fcL;
1104 if (fskAdj) return fcs;
1105 return (uint16_t)fcLens[best2] << 8 | fcLens[best1];
1108 //by marshmellow
1109 //detect psk clock by reading each phase shift
1110 // a phase shift is determined by measuring the sample length of each wave
1111 int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShift, uint8_t *curPhase, uint8_t *fc) {
1112 uint8_t clk[] = {255, 16, 32, 40, 50, 64, 100, 128, 255}; //255 is not a valid clock
1113 uint16_t loopCnt = 4096; //don't need to loop through entire array...
1115 if (size < 160 + 20) return 0;
1116 // size must be larger than 20 here, and 160 later on.
1117 if (size < loopCnt) loopCnt = size - 20;
1119 uint16_t fcs = countFC(dest, size, 0);
1121 *fc = fcs & 0xFF;
1123 if (g_debugMode == 2) prnt("DEBUG PSK: FC: %d, FC2: %d", *fc, fcs >> 8);
1125 if ((fcs >> 8) == 10 && *fc == 8) return 0;
1127 if (*fc != 2 && *fc != 4 && *fc != 8) return 0;
1130 size_t waveEnd, firstFullWave = 0;
1132 uint8_t clkCnt;
1133 uint16_t waveLenCnt, fullWaveLen = 0;
1134 uint16_t bestErr[] = {1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
1135 uint16_t peaksdet[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
1137 //find start of modulating data in trace
1138 size_t i = findModStart(dest, size, *fc);
1140 firstFullWave = pskFindFirstPhaseShift(dest, size, curPhase, i, *fc, &fullWaveLen);
1141 if (firstFullWave == 0) {
1142 // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
1143 // so skip a little to ensure we are past any Start Signal
1144 firstFullWave = 160;
1145 fullWaveLen = 0;
1148 *firstPhaseShift = firstFullWave;
1149 if (g_debugMode == 2) prnt("DEBUG PSK: firstFullWave: %zu, waveLen: %d", firstFullWave, fullWaveLen);
1151 // Avoid autodetect if user selected a clock
1152 for (uint8_t validClk = 1; validClk < 8; validClk++) {
1153 if (clock == clk[validClk]) return (clock);
1156 //test each valid clock from greatest to smallest to see which lines up
1157 for (clkCnt = 7; clkCnt >= 1 ; clkCnt--) {
1158 uint8_t tol = *fc / 2;
1159 size_t lastClkBit = firstFullWave; //set end of wave as clock align
1160 size_t waveStart = 0;
1161 uint16_t errCnt = 0;
1162 uint16_t peakcnt = 0;
1163 if (g_debugMode == 2) prnt("DEBUG PSK: clk: %d, lastClkBit: %zu", clk[clkCnt], lastClkBit);
1165 for (i = firstFullWave + fullWaveLen - 1; i < loopCnt - 2; i++) {
1166 //top edge of wave = start of new wave
1167 if (dest[i] < dest[i + 1] && dest[i + 1] >= dest[i + 2]) {
1168 if (waveStart == 0) {
1169 waveStart = i + 1;
1170 } else { //waveEnd
1171 waveEnd = i + 1;
1172 waveLenCnt = waveEnd - waveStart;
1173 if (waveLenCnt > *fc) {
1174 //if this wave is a phase shift
1175 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);
1176 if (i + 1 >= lastClkBit + clk[clkCnt] - tol) { //should be a clock bit
1177 peakcnt++;
1178 lastClkBit += clk[clkCnt];
1179 } else if (i < lastClkBit + 8) {
1180 //noise after a phase shift - ignore
1181 } else { //phase shift before supposed to based on clock
1182 errCnt++;
1184 } else if (i + 1 > lastClkBit + clk[clkCnt] + tol + *fc) {
1185 lastClkBit += clk[clkCnt]; //no phase shift but clock bit
1187 waveStart = i + 1;
1191 if (errCnt == 0) return clk[clkCnt];
1192 if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt] = errCnt;
1193 if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt] = peakcnt;
1195 //all tested with errors
1196 //return the highest clk with the most peaks found
1197 uint8_t best = 7;
1198 for (i = 7; i >= 1; i--) {
1199 if (peaksdet[i] > peaksdet[best])
1200 best = i;
1202 if (g_debugMode == 2) prnt("DEBUG PSK: Clk: %d, peaks: %d, errs: %d, bestClk: %d", clk[i], peaksdet[i], bestErr[i], clk[best]);
1204 return clk[best];
1207 //by marshmellow
1208 //detects the bit clock for FSK given the high and low Field Clocks
1209 uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, int *firstClockEdge) {
1211 if (size == 0)
1212 return 0;
1214 uint8_t clk[] = {8, 16, 32, 40, 50, 64, 100, 128, 0};
1215 uint16_t rfLens[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1216 uint8_t rfCnts[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1217 uint8_t rfLensFnd = 0;
1218 uint8_t lastFCcnt = 0;
1219 uint16_t fcCounter = 0;
1220 uint16_t rfCounter = 0;
1221 uint8_t firstBitFnd = 0;
1222 size_t i;
1223 uint8_t fcTol = ((fcHigh * 100 - fcLow * 100) / 2 + 50) / 100; //(uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
1225 // prime i to first peak / up transition
1226 for (i = 160; i < size - 20; i++)
1227 if (bits[i] > bits[i - 1] && bits[i] >= bits[i + 1])
1228 break;
1230 for (; i < size - 20; i++) {
1231 fcCounter++;
1232 rfCounter++;
1234 if (bits[i] <= bits[i - 1] || bits[i] < bits[i + 1])
1235 continue;
1236 // else new peak
1237 // if we got less than the small fc + tolerance then set it to the small fc
1238 // if it is inbetween set it to the last counter
1239 if (fcCounter < fcHigh && fcCounter > fcLow)
1240 fcCounter = lastFCcnt;
1241 else if (fcCounter < fcLow + fcTol)
1242 fcCounter = fcLow;
1243 else //set it to the large fc
1244 fcCounter = fcHigh;
1246 //look for bit clock (rf/xx)
1247 if ((fcCounter < lastFCcnt || fcCounter > lastFCcnt)) {
1248 //not the same size as the last wave - start of new bit sequence
1249 if (firstBitFnd > 1) { //skip first wave change - probably not a complete bit
1250 for (int ii = 0; ii < 15; ii++) {
1251 if (rfLens[ii] >= (rfCounter - 4) && rfLens[ii] <= (rfCounter + 4)) {
1252 rfCnts[ii]++;
1253 rfCounter = 0;
1254 break;
1257 if (rfCounter > 0 && rfLensFnd < 15) {
1258 //prnt("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
1259 rfCnts[rfLensFnd]++;
1260 rfLens[rfLensFnd++] = rfCounter;
1262 } else {
1263 *firstClockEdge = i;
1264 firstBitFnd++;
1266 rfCounter = 0;
1267 lastFCcnt = fcCounter;
1269 fcCounter = 0;
1271 uint8_t rfHighest = 15, rfHighest2 = 15, rfHighest3 = 15;
1273 for (i = 0; i < 15; i++) {
1274 //get highest 2 RF values (might need to get more values to compare or compare all?)
1275 if (rfCnts[i] > rfCnts[rfHighest]) {
1276 rfHighest3 = rfHighest2;
1277 rfHighest2 = rfHighest;
1278 rfHighest = i;
1279 } else if (rfCnts[i] > rfCnts[rfHighest2]) {
1280 rfHighest3 = rfHighest2;
1281 rfHighest2 = i;
1282 } else if (rfCnts[i] > rfCnts[rfHighest3]) {
1283 rfHighest3 = i;
1285 if (g_debugMode == 2)
1286 prnt("DEBUG FSK: RF %d, cnts %d", rfLens[i], rfCnts[i]);
1288 // set allowed clock remainder tolerance to be 1 large field clock length+1
1289 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
1290 uint8_t tol1 = fcHigh + 1;
1292 if (g_debugMode == 2)
1293 prnt("DEBUG FSK: most counted rf values: 1 %d, 2 %d, 3 %d", rfLens[rfHighest], rfLens[rfHighest2], rfLens[rfHighest3]);
1295 // loop to find the highest clock that has a remainder less than the tolerance
1296 // compare samples counted divided by
1297 // test 128 down to 32 (shouldn't be possible to have fc/10 & fc/8 and rf/16 or less)
1298 int m = 7;
1299 for (; m >= 2; m--) {
1300 if (rfLens[rfHighest] % clk[m] < tol1 || rfLens[rfHighest] % clk[m] > clk[m] - tol1) {
1301 if (rfLens[rfHighest2] % clk[m] < tol1 || rfLens[rfHighest2] % clk[m] > clk[m] - tol1) {
1302 if (rfLens[rfHighest3] % clk[m] < tol1 || rfLens[rfHighest3] % clk[m] > clk[m] - tol1) {
1303 if (g_debugMode == 2)
1304 prnt("DEBUG FSK: clk %d divides into the 3 most rf values within tolerance", clk[m]);
1305 break;
1311 if (m < 2) return 0; // oops we went too far
1313 return clk[m];
1317 // **********************************************************************************************
1318 // --------------------Modulation Demods &/or Decoding Section-----------------------------------
1319 // **********************************************************************************************
1322 // 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...
1323 static bool findST(int *stStopLoc, int *stStartIdx, int lowToLowWaveLen[], int highToLowWaveLen[], int clk, int tol, int buffSize, size_t *i) {
1324 if (buffSize < *i + 4) return false;
1326 for (; *i < buffSize - 4; *i += 1) {
1327 *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...
1328 if (lowToLowWaveLen[*i] >= clk * 1 - tol && lowToLowWaveLen[*i] <= (clk * 2) + tol && highToLowWaveLen[*i] < clk + tol) { //1 to 2 clocks depending on 2 bits prior
1329 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
1330 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
1331 if (lowToLowWaveLen[*i + 3] >= clk * 1 - tol && lowToLowWaveLen[*i + 3] <= clk * 2 + tol) { //1 to 2 clocks for end of ST + first bit
1332 *stStopLoc = *i + 3;
1333 return true;
1339 return false;
1341 //by marshmellow
1342 //attempt to identify a Sequence Terminator in ASK modulated raw wave
1343 bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, size_t *stend) {
1344 size_t bufsize = *size;
1345 //need to loop through all samples and identify our clock, look for the ST pattern
1346 int clk = 0;
1347 int tol = 0;
1348 int j = 0, high, low, skip = 0, start = 0, end = 0, minClk = 255;
1349 size_t i = 0;
1350 //probably should malloc... || test if memory is available ... handle device side? memory danger!!! [marshmellow]
1351 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
1352 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...
1353 //size_t testsize = (bufsize < 512) ? bufsize : 512;
1354 int phaseoff = 0;
1355 high = low = 128;
1356 memset(tmpbuff, 0, sizeof(tmpbuff));
1357 memset(waveLen, 0, sizeof(waveLen));
1359 if (!loadWaveCounters(buffer, bufsize, tmpbuff, waveLen, &j, &skip, &minClk, &high, &low)) return false;
1360 // set clock - might be able to get this externally and remove this work...
1361 clk = getClosestClock(minClk);
1362 // clock not found - ERROR
1363 if (!clk) {
1364 if (g_debugMode == 2) prnt("DEBUG STT: clock not found - quitting");
1365 return false;
1367 *foundclock = clk;
1369 tol = clk / 8;
1370 if (!findST(&start, &skip, tmpbuff, waveLen, clk, tol, j, &i)) {
1371 // first ST not found - ERROR
1372 if (g_debugMode == 2) prnt("DEBUG STT: first STT not found - quitting");
1373 return false;
1374 } else {
1375 if (g_debugMode == 2) prnt("DEBUG STT: first STT found at wave: %i, skip: %i, j=%i", start, skip, j);
1377 if (waveLen[i + 2] > clk * 1 + tol)
1378 phaseoff = 0;
1379 else
1380 phaseoff = clk / 2;
1382 // skip over the remainder of ST
1383 skip += clk * 7 / 2; //3.5 clocks from tmpbuff[i] = end of st - also aligns for ending point
1385 // now do it again to find the end
1386 int dummy1 = 0;
1387 end = skip;
1388 i += 3;
1389 if (!findST(&dummy1, &end, tmpbuff, waveLen, clk, tol, j, &i)) {
1390 //didn't find second ST - ERROR
1391 if (g_debugMode == 2) prnt("DEBUG STT: second STT not found - quitting");
1392 return false;
1394 end -= phaseoff;
1395 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);
1396 //now begin to trim out ST so we can use normal demod cmds
1397 start = skip;
1398 size_t datalen = end - start;
1399 // check validity of datalen (should be even clock increments) - use a tolerance of up to 1/8th a clock
1400 if (clk - (datalen % clk) <= clk / 8) {
1401 // padd the amount off - could be problematic... but shouldn't happen often
1402 datalen += clk - (datalen % clk);
1403 } else if ((datalen % clk) <= clk / 8) {
1404 // padd the amount off - could be problematic... but shouldn't happen often
1405 datalen -= datalen % clk;
1406 } else {
1407 if (g_debugMode == 2) prnt("DEBUG STT: datalen not divisible by clk: %zu %% %d = %zu - quitting", datalen, clk, datalen % clk);
1408 return false;
1410 // if datalen is less than one t55xx block - ERROR
1411 if (datalen / clk < 8 * 4) {
1412 if (g_debugMode == 2) prnt("DEBUG STT: datalen is less than 1 full t55xx block - quitting");
1413 return false;
1415 size_t dataloc = start;
1416 if (buffer[dataloc - (clk * 4) - (clk / 4)] <= low && buffer[dataloc] <= low && buffer[dataloc - (clk * 4)] >= high) {
1417 //we have low drift (and a low just before the ST and a low just after the ST) - compensate by backing up the start
1418 for (i = 0; i <= (clk / 4); ++i) {
1419 if (buffer[dataloc - (clk * 4) - i] <= low) {
1420 dataloc -= i;
1421 break;
1426 size_t newloc = 0;
1427 i = 0;
1428 if (g_debugMode == 2) prnt("DEBUG STT: Starting STT trim - start: %zu, datalen: %zu ", dataloc, datalen);
1429 bool firstrun = true;
1430 // warning - overwriting buffer given with raw wave data with ST removed...
1431 while (dataloc < bufsize - (clk / 2)) {
1432 //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)
1433 if (buffer[dataloc] < high && buffer[dataloc] > low && buffer[dataloc + clk / 4] < high && buffer[dataloc + clk / 4] > low) {
1434 for (i = 0; i < clk / 2 - tol; ++i) {
1435 buffer[dataloc + i] = high + 5;
1437 } //test for small spike outlier (high between two lows) in the case of very strong waves
1438 if (buffer[dataloc] > low && buffer[dataloc + clk / 4] <= low) {
1439 for (i = 0; i < clk / 4; ++i) {
1440 buffer[dataloc + i] = buffer[dataloc + clk / 4];
1443 if (firstrun) {
1444 *stend = dataloc;
1445 *ststart = dataloc - (clk * 4);
1446 firstrun = false;
1448 for (i = 0; i < datalen; ++i) {
1449 if (i + newloc < bufsize) {
1450 if (i + newloc < dataloc)
1451 buffer[i + newloc] = buffer[dataloc];
1453 dataloc++;
1456 newloc += i;
1457 //skip next ST - we just assume it will be there from now on...
1458 if (g_debugMode == 2) prnt("DEBUG STT: skipping STT at %zu to %zu", dataloc, dataloc + (clk * 4));
1459 dataloc += clk * 4;
1461 *size = newloc;
1462 return true;
1465 //by marshmellow
1466 //take 11 10 01 11 00 and make 01100 ... miller decoding
1467 //check for phase errors - should never have half a 1 or 0 by itself and should never exceed 1111 or 0000 in a row
1468 //decodes miller encoded binary
1469 //NOTE askrawdemod will NOT demod miller encoded ask unless the clock is manually set to 1/2 what it is detected as!
1471 static int millerRawDecode(uint8_t *bits, size_t *size, int invert) {
1472 if (*size < 16) return -1;
1474 uint16_t MaxBits = 512, errCnt = 0;
1475 size_t i, bitCnt = 0;
1476 uint8_t alignCnt = 0, curBit = bits[0], alignedIdx = 0, halfClkErr = 0;
1478 //find alignment, needs 4 1s or 0s to properly align
1479 for (i = 1; i < *size - 1; i++) {
1480 alignCnt = (bits[i] == curBit) ? alignCnt + 1 : 0;
1481 curBit = bits[i];
1482 if (alignCnt == 4) break;
1484 // for now error if alignment not found. later add option to run it with multiple offsets...
1485 if (alignCnt != 4) {
1486 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");
1487 return -1;
1489 alignedIdx = (i - 1) % 2;
1490 for (i = alignedIdx; i < *size - 3; i += 2) {
1491 halfClkErr = (uint8_t)((halfClkErr << 1 | bits[i]) & 0xFF);
1492 if ((halfClkErr & 0x7) == 5 || (halfClkErr & 0x7) == 2 || (i > 2 && (halfClkErr & 0x7) == 0) || (halfClkErr & 0x1F) == 0x1F) {
1493 errCnt++;
1494 bits[bitCnt++] = 7;
1495 continue;
1497 bits[bitCnt++] = bits[i] ^ bits[i + 1] ^ invert;
1499 if (bitCnt > MaxBits) break;
1501 *size = bitCnt;
1502 return errCnt;
1506 //by marshmellow
1507 //take 01 or 10 = 1 and 11 or 00 = 0
1508 //check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010
1509 //decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding
1510 int BiphaseRawDecode(uint8_t *bits, size_t *size, int *offset, int invert) {
1511 //sanity check
1512 if (*size < 51) return -1;
1514 if (*offset < 0) *offset = 0;
1516 uint16_t bitnum = 0;
1517 uint16_t errCnt = 0;
1518 size_t i = *offset;
1519 uint16_t maxbits = 512;
1521 //check for phase change faults - skip one sample if faulty
1522 bool offsetA = true, offsetB = true;
1523 for (; i < *offset + 48; i += 2) {
1524 if (bits[i + 1] == bits[i + 2]) offsetA = false;
1525 if (bits[i + 2] == bits[i + 3]) offsetB = false;
1527 if (!offsetA && offsetB) ++*offset;
1529 // main loop
1530 for (i = *offset; i < *size - 1; i += 2) {
1531 //check for phase error
1532 if (bits[i + 1] == bits[i + 2]) {
1533 bits[bitnum++] = 7;
1534 errCnt++;
1536 if ((bits[i] == 1 && bits[i + 1] == 0) || (bits[i] == 0 && bits[i + 1] == 1)) {
1537 bits[bitnum++] = 1 ^ invert;
1538 } else if ((bits[i] == 0 && bits[i + 1] == 0) || (bits[i] == 1 && bits[i + 1] == 1)) {
1539 bits[bitnum++] = invert;
1540 } else {
1541 bits[bitnum++] = 7;
1542 errCnt++;
1544 if (bitnum > maxbits) break;
1546 *size = bitnum;
1547 return errCnt;
1550 //by marshmellow
1551 //take 10 and 01 and manchester decode
1552 //run through 2 times and take least errCnt
1553 // "," indicates 00 or 11 wrong bit
1554 uint16_t manrawdecode(uint8_t *bits, size_t *size, uint8_t invert, uint8_t *alignPos) {
1556 // sanity check
1557 if (*size < 16) return 0xFFFF;
1559 int errCnt = 0, bestErr = 1000;
1560 uint16_t bitnum = 0, maxBits = 512, bestRun = 0;
1561 size_t i;
1563 //find correct start position [alignment]
1564 for (uint8_t k = 0; k < 2; k++) {
1566 for (i = k; i < *size - 1; i += 2) {
1568 if (bits[i] == bits[i + 1])
1569 errCnt++;
1571 if (errCnt > 50)
1572 break;
1575 if (bestErr > errCnt) {
1576 bestErr = errCnt;
1577 bestRun = k;
1578 if (g_debugMode == 2) prnt("DEBUG manrawdecode: bestErr %d | bestRun %u", bestErr, bestRun);
1580 errCnt = 0;
1583 *alignPos = bestRun;
1584 //decode
1585 for (i = bestRun; i < *size; i += 2) {
1586 if (bits[i] == 1 && (bits[i + 1] == 0)) {
1587 bits[bitnum++] = invert;
1588 } else if ((bits[i] == 0) && bits[i + 1] == 1) {
1589 bits[bitnum++] = invert ^ 1;
1590 } else {
1591 bits[bitnum++] = 7;
1593 if (bitnum > maxBits) break;
1595 *size = bitnum;
1596 return bestErr;
1599 //by marshmellow
1600 //demodulates strong heavily clipped samples
1601 //RETURN: num of errors. if 0, is ok.
1602 static uint16_t cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int invert, int high, int low, int *startIdx) {
1603 *startIdx = 0;
1604 size_t bitCnt = 0, smplCnt = 1, errCnt = 0, pos = 0;
1605 uint8_t cl_4 = clk / 4;
1606 uint8_t cl_2 = clk / 2;
1607 bool waveHigh = true;
1609 getNextHigh(bits, *size, high, &pos);
1610 // getNextLow(bits, *size, low, &pos);
1612 // do not skip first transition
1613 if ((pos > cl_2 - cl_4 - 1) && (pos <= clk + cl_4 + 1)) {
1614 bits[bitCnt++] = invert ^ 1;
1617 // sample counts, like clock = 32.. it tries to find 32/4 = 8, 32/2 = 16
1618 for (size_t i = pos; i < *size; i++) {
1619 if (bits[i] >= high && waveHigh) {
1620 smplCnt++;
1621 } else if (bits[i] <= low && !waveHigh) {
1622 smplCnt++;
1623 } else {
1624 //transition
1625 if ((bits[i] >= high && !waveHigh) || (bits[i] <= low && waveHigh)) {
1627 // 8 :: 8-2-1 = 5 8+2+1 = 11
1628 // 16 :: 16-4-1 = 11 16+4+1 = 21
1629 // 32 :: 32-8-1 = 23 32+8+1 = 41
1630 // 64 :: 64-16-1 = 47 64+16+1 = 81
1631 if (smplCnt > clk - cl_4 - 1) { //full clock
1633 if (smplCnt > clk + cl_4 + 1) {
1634 //too many samples
1635 errCnt++;
1636 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod ASK Modulation Error FULL at: %zu [%zu > %u]", i, smplCnt, clk + cl_4 + 1);
1637 bits[bitCnt++] = 7;
1638 } else if (waveHigh) {
1639 bits[bitCnt++] = invert;
1640 bits[bitCnt++] = invert;
1641 } else {
1642 bits[bitCnt++] = invert ^ 1;
1643 bits[bitCnt++] = invert ^ 1;
1645 if (*startIdx == 0) {
1646 *startIdx = i - clk;
1647 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod minus clock [%d]", *startIdx);
1649 waveHigh = !waveHigh;
1650 smplCnt = 0;
1652 // 16-8-1 = 7
1653 } else if (smplCnt > cl_2 - cl_4 - 1) { //half clock
1655 if (smplCnt > cl_2 + cl_4 + 1) { //too many samples
1656 errCnt++;
1657 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod ASK Modulation Error HALF at: %zu [%zu]", i, smplCnt);
1658 bits[bitCnt++] = 7;
1661 if (waveHigh) {
1662 bits[bitCnt++] = invert;
1663 } else {
1664 bits[bitCnt++] = invert ^ 1;
1667 if (*startIdx == 0) {
1668 *startIdx = i - cl_2;
1669 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod minus half clock [%d]", *startIdx);
1671 waveHigh = !waveHigh;
1672 smplCnt = 0;
1673 } else {
1674 smplCnt++;
1675 //transition bit oops
1677 } else { //haven't hit new high or new low yet
1678 smplCnt++;
1683 *size = bitCnt;
1685 if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod Startidx %d", *startIdx);
1687 return errCnt;
1690 //by marshmellow
1691 //attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester
1692 int askdemod_ext(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType, int *startIdx) {
1694 if (*size == 0) return -1;
1696 if (signalprop.isnoise) {
1697 if (g_debugMode == 2) prnt("DEBUG (askdemod_ext) just noise detected - aborting");
1698 return -2;
1701 int start = DetectASKClock(bits, *size, clk, maxErr);
1702 if (*clk == 0 || start < 0) return -3;
1704 if (*invert != 1) *invert = 0;
1706 // amplify signal data.
1707 // ICEMAN todo,
1708 if (amp == 1) askAmp(bits, *size);
1710 if (g_debugMode == 2) prnt("DEBUG (askdemod_ext) clk %d, beststart %d, amp %d", *clk, start, amp);
1712 // Detect high and lows
1713 //25% clip in case highs and lows aren't clipped [marshmellow]
1714 int high, low;
1715 getHiLo(&high, &low, 75, 75);
1717 size_t errCnt = 0;
1718 // if clean clipped waves detected run alternate demod
1719 if (DetectCleanAskWave(bits, *size, high, low)) {
1721 //start pos from detect ask clock is 1/2 clock offset
1722 // NOTE: can be negative (demod assumes rest of wave was there)
1723 *startIdx = start - (*clk / 2);
1724 if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Clean wave detected --- startindex %d", *startIdx);
1726 errCnt = cleanAskRawDemod(bits, size, *clk, *invert, high, low, startIdx);
1728 if (askType) { //ask/manchester
1729 uint8_t alignPos = 0;
1730 errCnt = manrawdecode(bits, size, 0, &alignPos);
1731 *startIdx += ((*clk / 2) * alignPos);
1733 if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) CLEAN: startIdx %i, alignPos %u , bestError %zu", *startIdx, alignPos, errCnt);
1735 return errCnt;
1738 *startIdx = start - (*clk / 2);
1739 if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Weak wave detected: startIdx %i", *startIdx);
1741 int lastBit; // set first clock check - can go negative
1742 size_t i, bitnum = 0; // output counter
1743 uint8_t midBit = 0;
1744 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
1745 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
1746 size_t MaxBits = 3072; // max bits to collect
1747 lastBit = start - *clk;
1749 for (i = start; i < *size; ++i) {
1750 if (i - lastBit >= *clk - tol) {
1751 if (bits[i] >= high) {
1752 bits[bitnum++] = *invert;
1753 } else if (bits[i] <= low) {
1754 bits[bitnum++] = *invert ^ 1;
1755 } else if (i - lastBit >= *clk + tol) {
1756 if (bitnum > 0) {
1757 // if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Modulation Error at: %u", i);
1758 bits[bitnum++] = 7;
1759 errCnt++;
1761 } else { //in tolerance - looking for peak
1762 continue;
1764 midBit = 0;
1765 lastBit += *clk;
1766 } else if (i - lastBit >= (*clk / 2 - tol) && !midBit && !askType) {
1767 if (bits[i] >= high) {
1768 bits[bitnum++] = *invert;
1769 } else if (bits[i] <= low) {
1770 bits[bitnum++] = *invert ^ 1;
1771 } else if (i - lastBit >= *clk / 2 + tol) {
1772 if (bitnum > 0) {
1773 bits[bitnum] = bits[bitnum - 1];
1774 bitnum++;
1775 } else {
1776 bits[bitnum] = 0;
1777 bitnum++;
1779 } else { //in tolerance - looking for peak
1780 continue;
1782 midBit = 1;
1784 if (bitnum >= MaxBits) break;
1786 *size = bitnum;
1787 return errCnt;
1790 int askdemod(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType) {
1791 int start = 0;
1792 return askdemod_ext(bits, size, clk, invert, maxErr, amp, askType, &start);
1795 // by marshmellow - demodulate NRZ wave - requires a read with strong signal
1796 // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
1797 int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startIdx) {
1799 if (signalprop.isnoise) {
1800 if (g_debugMode == 2) prnt("DEBUG nrzRawDemod: just noise detected - quitting");
1801 return -1;
1804 size_t clkStartIdx = 0;
1805 *clk = DetectNRZClock(dest, *size, *clk, &clkStartIdx);
1806 if (*clk == 0) return -2;
1808 size_t i;
1809 int high, low;
1811 getHiLo(&high, &low, 75, 75);
1813 uint8_t bit = 0;
1814 //convert wave samples to 1's and 0's
1815 for (i = 20; i < *size - 20; i++) {
1816 if (dest[i] >= high) bit = 1;
1817 if (dest[i] <= low) bit = 0;
1818 dest[i] = bit;
1820 //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit)
1821 size_t lastBit = 0;
1822 size_t numBits = 0;
1823 for (i = 21; i < *size - 20; i++) {
1824 //if transition detected or large number of same bits - store the passed bits
1825 if (dest[i] != dest[i - 1] || (i - lastBit) == (10 * *clk)) {
1826 memset(dest + numBits, dest[i - 1] ^ *invert, (i - lastBit + (*clk / 4)) / *clk);
1827 numBits += (i - lastBit + (*clk / 4)) / *clk;
1828 if (lastBit == 0) {
1829 *startIdx = i - (numBits * *clk);
1830 if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx);
1832 lastBit = i - 1;
1835 *size = numBits;
1836 return 0;
1839 //translate wave to 11111100000 (1 for each short wave [higher freq] 0 for each long wave [lower freq])
1840 static size_t fsk_wave_demod(uint8_t *dest, size_t size, uint8_t fchigh, uint8_t fclow, int *startIdx) {
1842 if (size < 1024) return 0; // not enough samples
1844 if (fchigh == 0) fchigh = 10;
1845 if (fclow == 0) fclow = 8;
1847 //set the threshold close to 0 (graph) or 128 std to avoid static
1848 size_t preLastSample, LastSample = 0;
1849 size_t currSample = 0, last_transition = 0;
1850 size_t idx, numBits = 0;
1852 //find start of modulating data in trace
1853 idx = findModStart(dest, size, fchigh);
1854 // Need to threshold first sample
1855 dest[idx] = (dest[idx] < signalprop.mean) ? 0 : 1;
1857 last_transition = idx;
1858 idx++;
1860 // Definition: cycles between consecutive lo-hi transitions
1861 // Lets define some expected lengths. FSK1 is easier since it has bigger differences between.
1862 // FSK1 8/5
1863 // 50/8 = 6 | 40/8 = 5 | 64/8 = 8
1864 // 50/5 = 10 | 40/5 = 8 | 64/5 = 12
1866 // FSK2 10/8
1867 // 50/10 = 5 | 40/10 = 4 | 64/10 = 6
1868 // 50/8 = 6 | 40/8 = 5 | 64/8 = 8
1870 // count cycles between consecutive lo-hi transitions,
1871 // in practice due to noise etc we may end up with anywhere
1872 // To allow fuzz would mean +-1 on expected cycle width.
1873 // FSK1 8/5
1874 // 50/8 = 6 (5-7) | 40/8 = 5 (4-6) | 64/8 = 8 (7-9)
1875 // 50/5 = 10 (9-11) | 40/5 = 8 (7-9) | 64/5 = 12 (11-13)
1877 // FSK2 10/8
1878 // 50/10 = 5 (4-6) | 40/10 = 4 (3-5) | 64/10 = 6 (5-7)
1879 // 50/8 = 6 (5-7) | 40/8 = 5 (4-6) | 64/8 = 8 (7-9)
1881 // It easy to see to the overgaping, but luckily we the group value also, like 1111000001111
1882 // to separate between which bit to demodulate to.
1884 // process:
1885 // count width from 0-1 transition to 1-0.
1886 // determine the width is withing FUZZ_min and FUZZ_max tolerances
1887 // width should be divided with exp_one. i:e 6+7+6+2=21, 21/5 = 4,
1888 // the 1-0 to 0-1 width should be divided with exp_zero. Ie: 3+5+6+7 = 21/6 = 3
1890 for (; idx < size - 20; idx++) {
1892 // threshold current value
1893 dest[idx] = (dest[idx] < signalprop.mean) ? 0 : 1;
1895 // Check for 0->1 transition
1896 if (dest[idx - 1] < dest[idx]) {
1897 preLastSample = LastSample;
1898 LastSample = currSample;
1899 currSample = idx - last_transition;
1900 if (currSample < (fclow - 2)) { //0-5 = garbage noise (or 0-3)
1901 //do nothing with extra garbage
1902 } else if (currSample < (fchigh - 1)) { //6-8 = 8 sample waves (or 3-6 = 5)
1903 //correct previous 9 wave surrounded by 8 waves (or 6 surrounded by 5)
1904 if (numBits > 1 && LastSample > (fchigh - 2) && (preLastSample < (fchigh - 1))) {
1905 dest[numBits - 1] = 1;
1907 dest[numBits++] = 1;
1910 if (numBits > 0 && *startIdx == 0)
1911 *startIdx = idx - fclow;
1913 } else if (currSample > (fchigh + 1) && numBits < 3) { //12 + and first two bit = unusable garbage
1914 //do nothing with beginning garbage and reset.. should be rare..
1915 numBits = 0;
1916 } 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)
1917 dest[numBits++] = 1;
1918 if (numBits > 0 && *startIdx == 0) {
1919 *startIdx = idx - fclow;
1921 } else { //9+ = 10 sample waves (or 6+ = 7)
1922 dest[numBits++] = 0;
1923 if (numBits > 0 && *startIdx == 0) {
1924 *startIdx = idx - fchigh;
1927 last_transition = idx;
1930 return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
1933 //translate 11111100000 to 10
1934 //rfLen = clock, fchigh = larger field clock, fclow = smaller field clock
1935 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) {
1937 uint8_t lastval = dest[0];
1938 size_t i = 0;
1939 size_t numBits = 0;
1940 uint32_t n = 1;
1941 uint8_t hclk = clk / 2;
1943 for (i = 1; i < size; i++) {
1944 n++;
1945 if (dest[i] == lastval) continue; //skip until we hit a transition
1947 //find out how many bits (n) we collected (use 1/2 clk tolerance)
1949 if (dest[i - 1] == 1)
1950 //if lastval was 1, we have a 1->0 crossing
1951 n = (n * fclow + hclk) / clk;
1952 else
1953 // 0->1 crossing
1954 n = (n * fchigh + hclk) / clk;
1956 if (n == 0)
1957 n = 1;
1959 //first transition - save startidx
1960 if (numBits == 0) {
1961 if (lastval == 1) { //high to low
1962 *startIdx += (fclow * i) - (n * clk);
1963 if (g_debugMode == 2) prnt("DEBUG (aggregate_bits) FSK startIdx %i, fclow*idx %zu, n*clk %u", *startIdx, fclow * i, n * clk);
1964 } else {
1965 *startIdx += (fchigh * i) - (n * clk);
1966 if (g_debugMode == 2) prnt("DEBUG (aggregate_bits) FSK startIdx %i, fchigh*idx %zu, n*clk %u", *startIdx, fchigh * i, n * clk);
1970 //add to our destination the bits we collected
1971 memset(dest + numBits, dest[i - 1] ^ invert, n);
1973 numBits += n;
1974 n = 0;
1975 lastval = dest[i];
1977 }//end for
1979 // if valid extra bits at the end were all the same frequency - add them in
1980 if (n > clk / fchigh) {
1981 if (dest[i - 2] == 1) {
1982 n = (n * fclow + clk / 2) / clk;
1983 } else {
1984 n = (n * fchigh + clk / 2) / clk;
1986 memset(dest + numBits, dest[i - 1] ^ invert, n);
1987 numBits += n;
1988 if (g_debugMode == 2) prnt("DEBUG (aggregate_bits) extra bits in the end");
1990 return numBits;
1993 //by marshmellow (from holiman's base)
1994 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
1995 size_t fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow, int *start_idx) {
1996 if (signalprop.isnoise) return 0;
1997 // FSK demodulator
1998 size = fsk_wave_demod(dest, size, fchigh, fclow, start_idx);
1999 if (g_debugMode == 2) prnt("DEBUG (fskdemod) got %zu bits", size);
2000 size = aggregate_bits(dest, size, rfLen, invert, fchigh, fclow, start_idx);
2001 if (g_debugMode == 2) prnt("DEBUG (fskdemod) got %zu bits", size);
2002 return size;
2005 // by marshmellow
2006 // convert psk1 demod to psk2 demod
2007 // only transition waves are 1s
2008 //TODO: Iceman - hard coded value 7, should be #define
2009 void psk1TOpsk2(uint8_t *bits, size_t size) {
2010 uint8_t lastbit = bits[0];
2011 for (size_t i = 1; i < size; i++) {
2012 //ignore errors
2013 if (bits[i] == 7) continue;
2015 if (lastbit != bits[i]) {
2016 lastbit = bits[i];
2017 bits[i] = 1;
2018 } else {
2019 bits[i] = 0;
2024 // by marshmellow
2025 // convert psk2 demod to psk1 demod
2026 // from only transition waves are 1s to phase shifts change bit
2027 void psk2TOpsk1(uint8_t *bits, size_t size) {
2028 uint8_t phase = 0;
2029 for (size_t i = 0; i < size; i++) {
2030 if (bits[i] == 1) {
2031 phase ^= 1;
2033 bits[i] = phase;
2037 //by marshmellow - demodulate PSK1 wave
2038 //uses wave lengths (# Samples)
2039 //TODO: Iceman - hard coded value 7, should be #define
2040 int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *startIdx) {
2042 // sanity check
2043 if (*size < 170) return -1;
2045 uint8_t curPhase = *invert;
2046 uint8_t fc = 0;
2047 size_t i = 0, numBits = 0, waveStart = 1, waveEnd, firstFullWave = 0, lastClkBit = 0;
2048 uint16_t fullWaveLen = 0, waveLenCnt;
2049 //uint16_t avgWaveVal = 0;
2050 uint16_t errCnt = 0, errCnt2 = 0;
2052 *clock = DetectPSKClock(dest, *size, *clock, &firstFullWave, &curPhase, &fc);
2053 if (*clock <= 0) return -1;
2054 //if clock detect found firstfullwave...
2055 uint16_t tol = fc / 2;
2056 if (firstFullWave == 0) {
2057 //find start of modulating data in trace
2058 i = findModStart(dest, *size, fc);
2059 //find first phase shift
2060 firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, i, fc, &fullWaveLen);
2061 if (firstFullWave == 0) {
2062 // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
2063 // so skip a little to ensure we are past any Start Signal
2064 firstFullWave = 160;
2065 memset(dest, curPhase, firstFullWave / *clock);
2066 } else {
2067 memset(dest, curPhase ^ 1, firstFullWave / *clock);
2069 } else {
2070 memset(dest, curPhase ^ 1, firstFullWave / *clock);
2072 //advance bits
2073 numBits += (firstFullWave / *clock);
2074 *startIdx = firstFullWave - (*clock * numBits) + 2;
2075 //set start of wave as clock align
2076 lastClkBit = firstFullWave;
2077 if (g_debugMode == 2) {
2078 prnt("DEBUG PSK: firstFullWave: %zu, waveLen: %u, startIdx %i", firstFullWave, fullWaveLen, *startIdx);
2079 prnt("DEBUG PSK: clk: %d, lastClkBit: %zu, fc: %u", *clock, lastClkBit, fc);
2082 waveStart = 0;
2083 dest[numBits++] = curPhase; //set first read bit
2084 for (i = firstFullWave + fullWaveLen - 1; i < *size - 3; i++) {
2085 //top edge of wave = start of new wave
2086 if (dest[i] + fc < dest[i + 1] && dest[i + 1] >= dest[i + 2]) {
2087 if (waveStart == 0) {
2088 waveStart = i + 1;
2089 //avgWaveVal = dest[i + 1];
2090 } else { //waveEnd
2091 waveEnd = i + 1;
2092 waveLenCnt = waveEnd - waveStart;
2093 if (waveLenCnt > fc) {
2094 //this wave is a phase shift
2096 prnt("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d"
2097 , waveStart
2098 , waveLenCnt
2099 , lastClkBit + *clock - tol
2100 , i + 1
2101 , fc);
2103 if (i + 1 >= lastClkBit + *clock - tol) { //should be a clock bit
2104 curPhase ^= 1;
2105 dest[numBits++] = curPhase;
2106 lastClkBit += *clock;
2107 } else if (i < lastClkBit + 10 + fc) {
2108 //noise after a phase shift - ignore
2109 } else { //phase shift before supposed to based on clock
2110 errCnt++;
2111 dest[numBits++] = 7;
2113 } else if (i + 1 > lastClkBit + *clock + tol + fc) {
2114 lastClkBit += *clock; //no phase shift but clock bit
2115 dest[numBits++] = curPhase;
2116 } else if (waveLenCnt < fc - 1) { //wave is smaller than field clock (shouldn't happen often)
2117 errCnt2++;
2118 if (errCnt2 > 101) return errCnt2;
2119 //avgWaveVal += dest[i + 1];
2120 continue;
2122 //avgWaveVal = 0;
2123 waveStart = i + 1;
2126 //avgWaveVal += dest[i + 1];
2128 *size = numBits;
2129 return errCnt;
2132 int pskRawDemod(uint8_t *dest, size_t *size, int *clock, int *invert) {
2133 int start_idx = 0;
2134 return pskRawDemod_ext(dest, size, clock, invert, &start_idx);
2138 // **********************************************************************************************
2139 // -----------------Tag format detection section-------------------------------------------------
2140 // **********************************************************************************************
2143 // by marshmellow
2144 // FSK Demod then try to locate an AWID ID
2145 int detectAWID(uint8_t *dest, size_t *size, int *waveStartIdx) {
2146 //make sure buffer has enough data (96bits * 50clock samples)
2147 if (*size < 96 * 50) return -1;
2149 if (signalprop.isnoise) return -2;
2151 // FSK2a demodulator clock 50, invert 1, fcHigh 10, fcLow 8
2152 *size = fskdemod(dest, *size, 50, 1, 10, 8, waveStartIdx); //awid fsk2a
2154 //did we get a good demod?
2155 if (*size < 96) return -3;
2157 size_t start_idx = 0;
2158 uint8_t preamble[] = {0, 0, 0, 0, 0, 0, 0, 1};
2159 if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx))
2160 return -4; //preamble not found
2162 // wrong size? (between to preambles)
2163 if (*size != 96) return -5;
2165 return (int)start_idx;
2168 //by marshmellow
2169 //takes 1s and 0s and searches for EM410x format - output EM ID
2170 int Em410xDecode(uint8_t *bits, size_t *size, size_t *start_idx, uint32_t *hi, uint64_t *lo) {
2171 // sanity check
2172 if (bits[1] > 1) return -1;
2173 if (*size < 64) return -2;
2175 *start_idx = 0;
2177 // preamble 0111111111
2178 // include 0 in front to help get start pos
2179 uint8_t preamble[] = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
2180 if (!preambleSearch(bits, preamble, sizeof(preamble), size, start_idx))
2181 return -4;
2183 bool validShort = false;
2184 bool validShortExtended = false;
2185 bool validLong = false;
2186 *size = removeEm410xParity(bits, *start_idx + sizeof(preamble), *size == 128, &validShort, &validShortExtended, &validLong);
2188 if (validShort) {
2189 // std em410x format
2190 *hi = 0;
2191 *lo = ((uint64_t)(bytebits_to_byte(bits, 8)) << 32) | (bytebits_to_byte(bits + 8, 32));
2192 // 1 = Short
2193 return 1;
2195 if (validShortExtended || validLong) {
2196 // store in long em format
2197 *hi = (bytebits_to_byte(bits, 24));
2198 *lo = ((uint64_t)(bytebits_to_byte(bits + 24, 32)) << 32) | (bytebits_to_byte(bits + 24 + 32, 32));
2199 // 2 = Long
2200 // 4 = ShortExtended
2201 return ((int)validShortExtended << 2) + ((int)validLong << 1);
2203 return -6;
2206 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
2207 int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx) {
2208 //make sure buffer has data
2209 if (*size < 96 * 50) return -1;
2211 if (signalprop.isnoise) return -2;
2213 // FSK demodulator fsk2a so invert and fc/10/8
2214 *size = fskdemod(dest, *size, 50, 1, 10, 8, waveStartIdx); //hid fsk2a
2216 //did we get a good demod?
2217 if (*size < 96 * 2) return -3;
2219 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
2220 size_t start_idx = 0;
2221 uint8_t preamble[] = {0, 0, 0, 1, 1, 1, 0, 1};
2222 if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx))
2223 return -4; //preamble not found
2225 // wrong size? (between to preambles)
2226 //if (*size != 96) return -5;
2228 size_t num_start = start_idx + sizeof(preamble);
2229 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
2230 for (size_t idx = num_start; (idx - num_start) < *size - sizeof(preamble); idx += 2) {
2231 if (dest[idx] == dest[idx + 1]) {
2232 return -5; //not manchester data
2234 *hi2 = (*hi2 << 1) | (*hi >> 31);
2235 *hi = (*hi << 1) | (*lo >> 31);
2236 //Then, shift in a 0 or one into low
2237 *lo <<= 1;
2238 if (dest[idx] && !dest[idx + 1]) // 1 0
2239 *lo |= 1;
2240 else // 0 1
2241 *lo |= 0;
2243 return (int)start_idx;
2246 int detectIOProx(uint8_t *dest, size_t *size, int *waveStartIdx) {
2247 //make sure buffer has data
2248 if (*size < 66 * 64) return -1;
2250 if (signalprop.isnoise) return -2;
2252 // FSK demodulator RF/64, fsk2a so invert, and fc/10/8
2253 *size = fskdemod(dest, *size, 64, 1, 10, 8, waveStartIdx); //io fsk2a
2255 //did we get enough demod data?
2256 if (*size < 64) return -3;
2258 //Index map
2259 //0 10 20 30 40 50 60
2260 //| | | | | | |
2261 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
2262 //-----------------------------------------------------------------------------
2263 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
2265 //XSF(version)facility:codeone+codetwo
2267 size_t start_idx = 0;
2268 uint8_t preamble[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
2269 if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx))
2270 return -4; //preamble not found
2272 // wrong size? (between to preambles)
2273 if (*size != 64) return -5;
2275 if (!dest[start_idx + 8]
2276 && dest[start_idx + 17] == 1
2277 && dest[start_idx + 26] == 1
2278 && dest[start_idx + 35] == 1
2279 && dest[start_idx + 44] == 1
2280 && dest[start_idx + 53] == 1) {
2281 //confirmed proper separator bits found
2282 //return start position
2283 return (int) start_idx;
2285 return -6;