1 /* fsk_demod_state.h */
2 
3 #ifndef FSK_DEMOD_STATE_H
4 
5 #include "rpack.h"
6 
7 #include "audio.h"		// for enum modem_t
8 
9 /*
10  * Demodulator state.
11  * The name of the file is from we only had FSK.  Now we have other techniques.
12  * Different copy is required for each channel & subchannel being processed concurrently.
13  */
14 
15 // TODO1.2:  change prefix from BP_ to DSP_
16 
17 typedef enum bp_window_e { BP_WINDOW_TRUNCATED,
18 				BP_WINDOW_COSINE,
19 				BP_WINDOW_HAMMING,
20 				BP_WINDOW_BLACKMAN,
21 				BP_WINDOW_FLATTOP } bp_window_t;
22 
23 
24 struct demodulator_state_s
25 {
26 /*
27  * These are set once during initialization.
28  */
29 	enum modem_t modem_type;		// MODEM_AFSK, MODEM_8PSK, etc.
30 
31 //	enum v26_e v26_alt;			// Which alternative when V.26.
32 
33 	char profile;			// 'A', 'B', etc.	Upper case.
34 					// Only needed to see if we are using 'F' to take fast path.
35 
36 #define TICKS_PER_PLL_CYCLE ( 256.0 * 256.0 * 256.0 * 256.0 )
37 
38 	int pll_step_per_sample;	// PLL is advanced by this much each audio sample.
39 					// Data is sampled when it overflows.
40 
41 
42 	int ms_filter_size;		/* Size of mark & space filters, in audio samples. */
43 					/* Started off as a guess of one bit length */
44 					/* but about 2 bit times turned out to be better. */
45 					/* Currently using same size for any prefilter. */
46 
47 
48 #define MAX_FILTER_SIZE 320		/* 304 is needed for profile C, 300 baud & 44100. */
49 
50 /*
51  * Filter length for Mark & Space in bit times.
52  * e.g.  1 means 1/1200 second for 1200 baud.
53  */
54 	float ms_filter_len_bits;
55 	float lp_delay_fract;
56 
57 /*
58  * Window type for the various filters.
59  */
60 
61 	bp_window_t pre_window;
62 	bp_window_t ms_window;
63 	bp_window_t lp_window;
64 
65 
66 /*
67  * Alternate Low pass filters.
68  * First is arbitrary number for quick IIR.
69  * Second is frequency as ratio to baud rate for FIR.
70  */
71 	int lpf_use_fir;		/* 0 for IIR, 1 for FIR. */
72 
73 	float lpf_iir;			/* Only if using IIR. */
74 
75 	float lpf_baud;			/* Cutoff frequency as fraction of baud. */
76 					/* Intuitively we'd expect this to be somewhere */
77 					/* in the range of 0.5 to 1. */
78 					/* In practice, it turned out a little larger */
79 					/* for profiles B, C, D. */
80 
81 	float lp_filter_len_bits;  	/* Length in number of bit times. */
82 
83 	int lp_filter_size;		/* Size of Low Pass filter, in audio samples. */
84 					/* Previously it was always the same as the M/S */
85 					/* filters but in version 1.2 it's now independent. */
86 
87 	int lp_filter_delay;		/* Number of samples that the low pass filter */
88 					/* delays the signal. */
89 
90 					/* New in 1.6. */
91 
92 
93 /*
94  * Automatic gain control.  Fast attack and slow decay factors.
95  */
96 	float agc_fast_attack;
97 	float agc_slow_decay;
98 
99 /*
100  * Use a longer term view for reporting signal levels.
101  */
102 	float quick_attack;
103 	float sluggish_decay;
104 
105 /*
106  * Hysteresis before final demodulator 0 / 1 decision.
107  */
108 	float hysteresis;
109 	int num_slicers;		/* >1 for multiple slicers. */
110 
111 /*
112  * Phase Locked Loop (PLL) inertia.
113  * Larger number means less influence by signal transitions.
114  */
115 	float pll_locked_inertia;
116 	float pll_searching_inertia;
117 
118 
119 /*
120  * Optional band pass pre-filter before mark/space detector.
121  */
122 	int use_prefilter;	/* True to enable it. */
123 
124 	float prefilter_baud;	/* Cutoff frequencies, as fraction of */
125 				/* baud rate, beyond tones used.  */
126 				/* Example, if we used 1600/1800 tones at */
127 				/* 300 baud, and this was 0.5, the cutoff */
128 				/* frequencies would be: */
129 				/* lower = min(1600,1800) - 0.5 * 300 = 1450 */
130 				/* upper = max(1600,1800) + 0.5 * 300 = 1950 */
131 
132 	float pre_filter_len_bits;  /* Length in number of bit times. */
133 
134 	int pre_filter_size;	/* Size of pre filter, in audio samples. */
135 
136 	float pre_filter[MAX_FILTER_SIZE] __attribute__((aligned(16)));
137 
138 
139 /*
140  * Kernel for the mark and space detection filters.
141  */
142 
143 	float m_sin_table[MAX_FILTER_SIZE] __attribute__((aligned(16)));
144 	float m_cos_table[MAX_FILTER_SIZE] __attribute__((aligned(16)));
145 
146 	float s_sin_table[MAX_FILTER_SIZE] __attribute__((aligned(16)));
147 	float s_cos_table[MAX_FILTER_SIZE] __attribute__((aligned(16)));
148 
149 
150 /*
151  * The rest are continuously updated.
152  */
153 
154 	unsigned int lo_phase;	/* Local oscillator for PSK. */
155 
156 
157 /*
158  * Most recent raw audio samples, before/after prefiltering.
159  */
160 	float raw_cb[MAX_FILTER_SIZE] __attribute__((aligned(16)));
161 
162 /*
163  * Use half of the AGC code to get a measure of input audio amplitude.
164  * These use "quick" attack and "sluggish" decay while the
165  * AGC uses "fast" attack and "slow" decay.
166  */
167 
168 	float alevel_rec_peak;
169 	float alevel_rec_valley;
170 	float alevel_mark_peak;
171 	float alevel_space_peak;
172 
173 /*
174  * Input to the mark/space detector.
175  * Could be prefiltered or raw audio.
176  */
177 	float ms_in_cb[MAX_FILTER_SIZE] __attribute__((aligned(16)));
178 
179 /*
180  * Outputs from the mark and space amplitude detection,
181  * used as inputs to the FIR lowpass filters.
182  * Kernel for the lowpass filters.
183  */
184 
185 	float m_amp_cb[MAX_FILTER_SIZE] __attribute__((aligned(16)));
186 	float s_amp_cb[MAX_FILTER_SIZE] __attribute__((aligned(16)));
187 
188 	float lp_filter[MAX_FILTER_SIZE] __attribute__((aligned(16)));
189 
190 
191 	float m_peak, s_peak;
192 	float m_valley, s_valley;
193 	float m_amp_prev, s_amp_prev;
194 
195 
196 /*
197  * For the PLL and data bit timing.
198  * starting in version 1.2 we can have multiple slicers for one demodulator.
199  * Each slicer has its own PLL and HDLC decoder.
200  */
201 
202 /*
203  * Version 1.3: Clean up subchan vs. slicer.
204  *
205  * Originally some number of CHANNELS (originally 2, later 6)
206  * which can have multiple parallel demodulators called SUB-CHANNELS.
207  * This was originally for staggered frequencies for HF SSB.
208  * It can also be used for multiple demodulators with the same
209  * frequency but other differing parameters.
210  * Each subchannel has its own demodulator and HDLC decoder.
211  *
212  * In version 1.2 we added multiple SLICERS.
213  * The data structure, here, has multiple slicers per
214  * demodulator (subchannel).  Due to fuzzy thinking or
215  * expediency, the multiple slicers got mapped into subchannels.
216  * This means we can't use both multiple decoders and
217  * multiple slicers at the same time.
218  *
219  * Clean this up in 1.3 and keep the concepts separate.
220  * This means adding a third variable many places
221  * we are passing around the origin.
222  *
223  */
224 	struct {
225 
226 		signed int data_clock_pll;		// PLL for data clock recovery.
227 							// It is incremented by pll_step_per_sample
228 							// for each audio sample.
229 							// Must be 32 bits!!!
230 							// So far, this is the case for every compiler used.
231 
232 		signed int prev_d_c_pll;		// Previous value of above, before
233 							// incrementing, to detect overflows.
234 
235 		int prev_demod_data;			// Previous data bit detected.
236 							// Used to look for transitions.
237 		float prev_demod_out_f;
238 
239 		/* This is used only for "9600" baud data. */
240 
241 		int lfsr;				// Descrambler shift register.
242 
243 		// This is for detecting phase lock to incoming signal.
244 
245 		int good_flag;				// Set if transition is near where expected,
246 							// i.e. at a good time.
247 		int bad_flag;				// Set if transition is not where expected,
248 							// i.e. at a bad time.
249 		unsigned char good_hist;		// History of good transitions for past octet.
250 		unsigned char bad_hist;			// History of bad transitions for past octet.
251 		unsigned int score;			// History of whether good triumphs over bad
252 							// for past 32 symbols.
253 		int data_detect;			// True when locked on to signal.
254 
255 	} slicer [MAX_SLICERS];				// Actual number in use is num_slicers.
256 							// Should be in range 1 .. MAX_SLICERS,
257 /*
258  * Version 1.6:
259  *
260  *	This has become quite disorganized and messy with different combinations of
261  *	fields used for different demodulator types.  Start to reorganize it into a common
262  *	part (with things like the DPLL for clock recovery), and separate sections
263  *	for each of the demodulator types.
264  *	Still a lot to do here.
265  */
266 
267 	union {
268 
269 //////////////////////////////////////////////////////////////////////////////////
270 //										//
271 //					PSK only.				//
272 //										//
273 //////////////////////////////////////////////////////////////////////////////////
274 
275 
276 	  struct psk_only_s {
277 
278 		enum v26_e v26_alt;		// Which alternative when V.26.
279 
280 		float sin_table256[256];	// Precomputed sin table for speed.
281 
282 
283 	// Optional band pass pre-filter before phase detector.
284 
285 // TODO? put back into common section?
286 // TODO? Why was I thinking that?
287 
288 		int use_prefilter;	// True to enable it.
289 
290 		float prefilter_baud;	// Cutoff frequencies, as fraction of baud rate, beyond tones used.
291 					// In the case of PSK, we use only a single tone of 1800 Hz.
292 					// If we were using 2400 bps (= 1200 baud), this would be
293 					// the fraction of 1200 for the cutoff below and above 1800.
294 
295 
296 		float pre_filter_width_sym;  /* Length in number of symbol times. */
297 
298 		int pre_filter_taps;	/* Size of pre filter, in audio samples. */
299 
300 		bp_window_t pre_window;
301 
302 		float audio_in[MAX_FILTER_SIZE] __attribute__((aligned(16)));
303 		float pre_filter[MAX_FILTER_SIZE] __attribute__((aligned(16)));
304 
305 	// Use local oscillator or correlate with previous sample.
306 
307 		int psk_use_lo;		/* Use local oscillator rather than self correlation. */
308 
309 		unsigned int lo_step;	/* How much to advance the local oscillator */
310 					/* phase for each audio sample. */
311 
312 		unsigned int lo_phase;	/* Local oscillator phase accumulator for PSK. */
313 
314 		// After mixing with LO before low pass filter.
315 
316 		float I_raw[MAX_FILTER_SIZE] __attribute__((aligned(16)));	// signal * LO cos.
317 		float Q_raw[MAX_FILTER_SIZE] __attribute__((aligned(16)));	// signal * LO sin.
318 
319 		// Number of delay line taps into previous symbol.
320 		// They are one symbol period and + or - 45 degrees of the carrier frequency.
321 
322 		int boffs;		/* symbol length based on sample rate and baud. */
323 		int coffs;		/* to get cos component of previous symbol. */
324 		int soffs;		/* to get sin component of previous symbol. */
325 
326 		float delay_line_width_sym;
327 		int delay_line_taps;	// In audio samples.
328 
329 		float delay_line[MAX_FILTER_SIZE] __attribute__((aligned(16)));
330 
331 	// Low pass filter Second is frequency as ratio to baud rate for FIR.
332 
333 // TODO? put back into common section?
334 // TODO? What are the tradeoffs?
335 		float lpf_baud;			/* Cutoff frequency as fraction of baud. */
336 						/* Intuitively we'd expect this to be somewhere */
337 						/* in the range of 0.5 to 1. */
338 
339 		float lp_filter_width_sym;  	/* Length in number of symbol times. */
340 
341 		int lp_filter_taps;		/* Size of Low Pass filter, in audio samples (i.e. filter taps). */
342 
343 		bp_window_t lp_window;
344 
345 		float lp_filter[MAX_FILTER_SIZE] __attribute__((aligned(16)));
346 
347 	  } psk;
348 
349 	} u;	// end of union for different demodulator types.
350 
351 };
352 
353 
354 /*-------------------------------------------------------------------
355  *
356  * Name:        pll_dcd_signal_transition2
357  *		dcd_each_symbol2
358  *
359  * Purpose:     New DCD strategy for 1.6.
360  *
361  * Inputs:	D		Pointer to demodulator state.
362  *
363  *		chan		Radio channel: 0 to MAX_CHANS - 1
364  *
365  *		subchan		Which of multiple demodulators: 0 to MAX_SUBCHANS - 1
366  *
367  *		slice		Slicer number: 0 to MAX_SLICERS - 1.
368  *
369  *		dpll_phase	Signed 32 bit counter for DPLL phase.
370  *				Wraparound is where data is sampled.
371  *				Ideally transitions would occur close to 0.
372  *
373  * Output:	D->slicer[slice].data_detect - true when PLL is locked to incoming signal.
374  *
375  * Description:	From the beginning, DCD was based on finding several flag octets
376  *		in a row and dropping when eight bits with no transitions.
377  *		It was less than ideal but we limped along with it all these years.
378  *		This fell apart when FX.25 came along and a couple of the
379  *		correlation tags have eight "1" bits in a row.
380  *
381  * 		Our new strategy is to keep a running score of how well demodulator
382  *		output transitions match to where expected.
383  *
384  *--------------------------------------------------------------------*/
385 
386 #include "hdlc_rec.h"        // for dcd_change
387 
388 // These are good for 1200 bps AFSK.
389 // Might want to override for other modems.
390 
391 #ifndef DCD_THRESH_ON
392 #define DCD_THRESH_ON 30		// Hysteresis: Can miss 2 out of 32 for detecting lock.
393 					// 31 is best for TNC Test CD.  30 almost as good.
394 					// 30 better for 1200 regression test.
395 #endif
396 
397 #ifndef DCD_THRESH_OFF
398 #define DCD_THRESH_OFF 6		// Might want a little more fine tuning.
399 #endif
400 
401 #ifndef DCD_GOOD_WIDTH
402 #define DCD_GOOD_WIDTH 512		// No more than 1024!!!
403 #endif
404 
405 __attribute__((always_inline))
pll_dcd_signal_transition2(struct demodulator_state_s * D,int slice,int dpll_phase)406 inline static void pll_dcd_signal_transition2 (struct demodulator_state_s *D, int slice, int dpll_phase)
407 {
408 	if (dpll_phase > - DCD_GOOD_WIDTH * 1024 * 1024 && dpll_phase < DCD_GOOD_WIDTH * 1024 * 1024) {
409 	  D->slicer[slice].good_flag = 1;
410 	}
411 	else {
412 	  D->slicer[slice].bad_flag = 1;
413 	}
414 }
415 
416 __attribute__((always_inline))
pll_dcd_each_symbol2(struct demodulator_state_s * D,int chan,int subchan,int slice)417 inline static void pll_dcd_each_symbol2 (struct demodulator_state_s *D, int chan, int subchan, int slice)
418 {
419 	D->slicer[slice].good_hist <<= 1;
420 	D->slicer[slice].good_hist |= D->slicer[slice].good_flag;
421 	D->slicer[slice].good_flag = 0;
422 
423 	D->slicer[slice].bad_hist <<= 1;
424 	D->slicer[slice].bad_hist |= D->slicer[slice].bad_flag;
425 	D->slicer[slice].bad_flag = 0;
426 
427 	D->slicer[slice].score <<= 1;
428 	// 2 is to detect 'flag' patterns with 2 transitions per octet.
429 	D->slicer[slice].score |= (signed)__builtin_popcount(D->slicer[slice].good_hist)
430 					- (signed)__builtin_popcount(D->slicer[slice].bad_hist) >= 2;
431 
432 	int s = __builtin_popcount(D->slicer[slice].score);
433 	if (s >= DCD_THRESH_ON) {
434 	  if (D->slicer[slice].data_detect == 0) {
435 	    D->slicer[slice].data_detect = 1;
436 	    dcd_change (chan, subchan, slice, D->slicer[slice].data_detect);
437 	  }
438 	}
439 	else if (s <= DCD_THRESH_OFF) {
440 	  if (D->slicer[slice].data_detect != 0) {
441 	    D->slicer[slice].data_detect = 0;
442 	    dcd_change (chan, subchan, slice, D->slicer[slice].data_detect);
443 	  }
444 	}
445 }
446 
447 
448 #define FSK_DEMOD_STATE_H 1
449 #endif
450