2 * This file is part of the libsigrok project.
4 * Copyright (C) 2014 Bert Vermeulen <bert@biot.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
30 #define LOG_PREFIX "analog"
36 * Handling and converting analog data.
40 * @defgroup grp_analog Analog data handling
42 * Handling and converting analog data.
47 struct unit_mq_string {
52 /* Please use the same order as in enum sr_unit (libsigrok.h). */
53 static struct unit_mq_string unit_strings[] = {
54 { SR_UNIT_VOLT, "V" },
55 { SR_UNIT_AMPERE, "A" },
56 { SR_UNIT_OHM, "\xe2\x84\xa6" },
57 { SR_UNIT_FARAD, "F" },
58 { SR_UNIT_KELVIN, "K" },
59 { SR_UNIT_CELSIUS, "\xc2\xb0""C" },
60 { SR_UNIT_FAHRENHEIT, "\xc2\xb0""F" },
61 { SR_UNIT_HERTZ, "Hz" },
62 { SR_UNIT_PERCENTAGE, "%" },
63 { SR_UNIT_BOOLEAN, "" },
64 { SR_UNIT_SECOND, "s" },
65 { SR_UNIT_SIEMENS, "S" },
66 { SR_UNIT_DECIBEL_MW, "dBm" },
67 { SR_UNIT_DECIBEL_VOLT, "dBV" },
68 { SR_UNIT_UNITLESS, "" },
69 { SR_UNIT_DECIBEL_SPL, "dB" },
70 { SR_UNIT_CONCENTRATION, "ppm" },
71 { SR_UNIT_REVOLUTIONS_PER_MINUTE, "RPM" },
72 { SR_UNIT_VOLT_AMPERE, "VA" },
73 { SR_UNIT_WATT, "W" },
74 { SR_UNIT_WATT_HOUR, "Wh" },
75 { SR_UNIT_METER_SECOND, "m/s" },
76 { SR_UNIT_HECTOPASCAL, "hPa" },
77 { SR_UNIT_HUMIDITY_293K, "%rF" },
78 { SR_UNIT_DEGREE, "\xc2\xb0" },
79 { SR_UNIT_HENRY, "H" },
80 { SR_UNIT_GRAM, "g" },
81 { SR_UNIT_CARAT, "ct" },
82 { SR_UNIT_OUNCE, "oz" },
83 { SR_UNIT_TROY_OUNCE, "oz t" },
84 { SR_UNIT_POUND, "lb" },
85 { SR_UNIT_PENNYWEIGHT, "dwt" },
86 { SR_UNIT_GRAIN, "gr" },
87 { SR_UNIT_TAEL, "tael" },
88 { SR_UNIT_MOMME, "momme" },
89 { SR_UNIT_TOLA, "tola" },
90 { SR_UNIT_PIECE, "pcs" },
91 { SR_UNIT_JOULE, "J" },
92 { SR_UNIT_COULOMB, "C" },
93 { SR_UNIT_AMPERE_HOUR, "Ah" },
97 /* Please use the same order as in enum sr_mqflag (libsigrok.h). */
98 static struct unit_mq_string mq_strings[] = {
99 { SR_MQFLAG_AC, " AC" },
100 { SR_MQFLAG_DC, " DC" },
101 { SR_MQFLAG_RMS, " RMS" },
102 { SR_MQFLAG_DIODE, " DIODE" },
103 { SR_MQFLAG_HOLD, " HOLD" },
104 { SR_MQFLAG_MAX, " MAX" },
105 { SR_MQFLAG_MIN, " MIN" },
106 { SR_MQFLAG_AUTORANGE, " AUTO" },
107 { SR_MQFLAG_RELATIVE, " REL" },
108 { SR_MQFLAG_SPL_FREQ_WEIGHT_A, "(A)" },
109 { SR_MQFLAG_SPL_FREQ_WEIGHT_C, "(C)" },
110 { SR_MQFLAG_SPL_FREQ_WEIGHT_Z, "(Z)" },
111 { SR_MQFLAG_SPL_FREQ_WEIGHT_FLAT, "(SPL)" },
112 { SR_MQFLAG_SPL_TIME_WEIGHT_S, " S" },
113 { SR_MQFLAG_SPL_TIME_WEIGHT_F, " F" },
114 { SR_MQFLAG_SPL_LAT, " LAT" },
115 /* Not a standard function for SLMs, so this is a made-up notation. */
116 { SR_MQFLAG_SPL_PCT_OVER_ALARM, "%oA" },
117 { SR_MQFLAG_DURATION, " DURATION" },
118 { SR_MQFLAG_AVG, " AVG" },
119 { SR_MQFLAG_REFERENCE, " REF" },
120 { SR_MQFLAG_UNSTABLE, " UNSTABLE" },
121 { SR_MQFLAG_FOUR_WIRE, " 4-WIRE" },
126 SR_PRIV int sr_analog_init(struct sr_datafeed_analog *analog,
127 struct sr_analog_encoding *encoding,
128 struct sr_analog_meaning *meaning,
129 struct sr_analog_spec *spec,
132 memset(analog, 0, sizeof(*analog));
133 memset(encoding, 0, sizeof(*encoding));
134 memset(meaning, 0, sizeof(*meaning));
135 memset(spec, 0, sizeof(*spec));
137 analog->encoding = encoding;
138 analog->meaning = meaning;
141 encoding->unitsize = sizeof(float);
142 encoding->is_float = TRUE;
143 #ifdef WORDS_BIGENDIAN
144 encoding->is_bigendian = TRUE;
146 encoding->is_bigendian = FALSE;
148 encoding->digits = digits;
149 encoding->is_digits_decimal = TRUE;
150 encoding->scale.p = 1;
151 encoding->scale.q = 1;
152 encoding->offset.p = 0;
153 encoding->offset.q = 1;
155 spec->spec_digits = digits;
161 * Convert an analog datafeed payload to an array of floats.
163 * Sufficient memory for outbuf must have been pre-allocated by the caller,
164 * who is also responsible for freeing it when no longer needed.
166 * @param[in] analog The analog payload to convert. Must not be NULL.
167 * analog->data, analog->meaning, and analog->encoding
169 * @param[out] outbuf Memory where to store the result. Must not be NULL.
171 * @retval SR_OK Success.
172 * @retval SR_ERR Unsupported encoding.
173 * @retval SR_ERR_ARG Invalid argument.
177 SR_API int sr_analog_to_float(const struct sr_datafeed_analog *analog,
180 unsigned int b, count;
182 uint8_t conv_buf[sizeof(double)];
183 float *conv_f = (float*)conv_buf;
184 double *conv_d = (double*)conv_buf;
186 if (!analog || !(analog->data) || !(analog->meaning)
187 || !(analog->encoding) || !outbuf)
190 count = analog->num_samples * g_slist_length(analog->meaning->channels);
192 #ifdef WORDS_BIGENDIAN
198 if (!analog->encoding->is_float) {
199 float offset = analog->encoding->offset.p / (float)analog->encoding->offset.q;
200 float scale = analog->encoding->scale.p / (float)analog->encoding->scale.q;
201 gboolean is_signed = analog->encoding->is_signed;
202 gboolean is_bigendian = analog->encoding->is_bigendian;
203 int8_t *data8 = (int8_t *)(analog->data);
204 int16_t *data16 = (int16_t *)(analog->data);
205 int32_t *data32 = (int32_t *)(analog->data);
207 switch (analog->encoding->unitsize) {
210 for (unsigned int i = 0; i < count; i++) {
211 outbuf[i] = scale * data8[i];
215 for (unsigned int i = 0; i < count; i++) {
216 outbuf[i] = scale * R8(data8 + i);
222 if (is_signed && is_bigendian) {
223 for (unsigned int i = 0; i < count; i++) {
224 outbuf[i] = scale * RB16S(&data16[i]);
227 } else if (is_bigendian) {
228 for (unsigned int i = 0; i < count; i++) {
229 outbuf[i] = scale * RB16(&data16[i]);
232 } else if (is_signed) {
233 for (unsigned int i = 0; i < count; i++) {
234 outbuf[i] = scale * RL16S(&data16[i]);
238 for (unsigned int i = 0; i < count; i++) {
239 outbuf[i] = scale * RL16(&data16[i]);
245 if (is_signed && is_bigendian) {
246 for (unsigned int i = 0; i < count; i++) {
247 outbuf[i] = scale * RB32S(&data32[i]);
250 } else if (is_bigendian) {
251 for (unsigned int i = 0; i < count; i++) {
252 outbuf[i] = scale * RB32(&data32[i]);
255 } else if (is_signed) {
256 for (unsigned int i = 0; i < count; i++) {
257 outbuf[i] = scale * RL32S(&data32[i]);
261 for (unsigned int i = 0; i < count; i++) {
262 outbuf[i] = scale * RL32(&data32[i]);
268 sr_err("Unsupported unit size '%d' for analog-to-float"
269 " conversion.", analog->encoding->unitsize);
275 if (analog->encoding->unitsize == sizeof(float)
276 && analog->encoding->is_bigendian == bigendian
277 && analog->encoding->scale.p == 1
278 && analog->encoding->scale.q == 1
279 && analog->encoding->offset.p / (float)analog->encoding->offset.q == 0) {
280 /* The data is already in the right format. */
281 memcpy(outbuf, analog->data, count * sizeof(float));
283 for (unsigned int i = 0; i < count; i++) {
284 for (b = 0; b < analog->encoding->unitsize; b++) {
285 if (analog->encoding->is_bigendian == bigendian)
287 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
289 conv_buf[analog->encoding->unitsize - b - 1] =
290 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
293 if (analog->encoding->unitsize == sizeof(float)) {
294 if (analog->encoding->scale.p != 1
295 || analog->encoding->scale.q != 1)
296 *conv_f = (*conv_f * analog->encoding->scale.p) / analog->encoding->scale.q;
297 float offset = ((float)analog->encoding->offset.p / (float)analog->encoding->offset.q);
302 else if (analog->encoding->unitsize == sizeof(double)) {
303 if (analog->encoding->scale.p != 1
304 || analog->encoding->scale.q != 1)
305 *conv_d = (*conv_d * analog->encoding->scale.p) / analog->encoding->scale.q;
306 double offset = ((double)analog->encoding->offset.p / (double)analog->encoding->offset.q);
312 sr_err("Unsupported floating-point unit size '%d' for analog-to-float"
313 " conversion.", analog->encoding->unitsize);
323 * Scale a float value to the appropriate SI prefix.
325 * @param[in,out] value The float value to convert to appropriate SI prefix.
326 * @param[in,out] digits The number of significant decimal digits in value.
328 * @return The SI prefix to which value was scaled, as a printable string.
332 SR_API const char *sr_analog_si_prefix(float *value, int *digits)
335 #define NEG_PREFIX_COUNT 5 /* number of prefixes below unity */
336 #define POS_PREFIX_COUNT (int)(ARRAY_SIZE(prefixes) - NEG_PREFIX_COUNT - 1)
338 static const char *prefixes[] = { "f", "p", "n", "µ", "m", "", "k", "M", "G", "T" };
340 if (!value || !digits || isnan(*value))
341 return prefixes[NEG_PREFIX_COUNT];
343 float logval = log10f(fabsf(*value));
344 int prefix = (logval / 3) - (logval < 1);
346 if (prefix < -NEG_PREFIX_COUNT)
347 prefix = -NEG_PREFIX_COUNT;
348 if (3 * prefix < -*digits)
349 prefix = (-*digits + 2 * (*digits < 0)) / 3;
350 if (prefix > POS_PREFIX_COUNT)
351 prefix = POS_PREFIX_COUNT;
353 *value *= powf(10, -3 * prefix);
354 *digits += 3 * prefix;
356 return prefixes[prefix + NEG_PREFIX_COUNT];
360 * Check if a unit "accepts" an SI prefix.
362 * E.g. SR_UNIT_VOLT is SI prefix friendly while SR_UNIT_DECIBEL_MW or
363 * SR_UNIT_PERCENTAGE are not.
365 * @param[in] unit The unit to check for SI prefix "friendliness".
367 * @return TRUE if the unit "accept" an SI prefix.
371 SR_API gboolean sr_analog_si_prefix_friendly(enum sr_unit unit)
373 static const enum sr_unit prefix_friendly_units[] = {
385 SR_UNIT_METER_SECOND,
391 for (i = 0; i < ARRAY_SIZE(prefix_friendly_units); i++)
392 if (unit == prefix_friendly_units[i])
399 * Convert the unit/MQ/MQ flags in the analog struct to a string.
401 * The string is allocated by the function and must be freed by the caller
402 * after use by calling g_free().
404 * @param[in] analog Struct containing the unit, MQ and MQ flags.
405 * Must not be NULL. analog->meaning must not be NULL.
406 * @param[out] result Pointer to store result. Must not be NULL.
408 * @retval SR_OK Success.
409 * @retval SR_ERR_ARG Invalid argument.
413 SR_API int sr_analog_unit_to_string(const struct sr_datafeed_analog *analog,
419 if (!analog || !(analog->meaning) || !result)
422 buf = g_string_new(NULL);
424 for (i = 0; unit_strings[i].value; i++) {
425 if (analog->meaning->unit == unit_strings[i].value) {
426 g_string_assign(buf, unit_strings[i].str);
431 /* More than one MQ flag may apply. */
432 for (i = 0; mq_strings[i].value; i++)
433 if (analog->meaning->mqflags & mq_strings[i].value)
434 g_string_append(buf, mq_strings[i].str);
437 g_string_free(buf, FALSE);
443 * Set sr_rational r to the given value.
445 * @param[out] r Rational number struct to set. Must not be NULL.
446 * @param[in] p Numerator.
447 * @param[in] q Denominator.
451 SR_API void sr_rational_set(struct sr_rational *r, int64_t p, uint64_t q)
460 #ifndef HAVE___INT128_T
466 struct sr_uint128_t {
471 static void mult_int64(struct sr_int128_t *res, const int64_t a,
474 uint64_t t1, t2, t3, t4;
476 t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
477 t2 = (UINT32_MAX & a) * (b >> 32);
478 t3 = (a >> 32) * (UINT32_MAX & b);
479 t4 = (a >> 32) * (b >> 32);
481 res->low = t1 + (t2 << 32) + (t3 << 32);
482 res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
484 res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
487 static void mult_uint64(struct sr_uint128_t *res, const uint64_t a,
490 uint64_t t1, t2, t3, t4;
492 // (x1 + x2) * (y1 + y2) = x1*y1 + x1*y2 + x2*y1 + x2*y2
493 t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
494 t2 = (UINT32_MAX & a) * (b >> 32);
495 t3 = (a >> 32) * (UINT32_MAX & b);
496 t4 = (a >> 32) * (b >> 32);
498 res->low = t1 + (t2 << 32) + (t3 << 32);
499 res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
501 res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
506 * Compare two sr_rational for equality.
508 * The values are compared for numerical equality, i.e. 2/10 == 1/5.
510 * @param[in] a First value.
511 * @param[in] b Second value.
513 * @retval 1 if both values are equal.
514 * @retval 0 Otherwise.
518 SR_API int sr_rational_eq(const struct sr_rational *a, const struct sr_rational *b)
520 #ifdef HAVE___INT128_T
523 /* p1/q1 = p2/q2 <=> p1*q2 = p2*q1 */
524 m1 = ((__int128_t)(b->p)) * ((__uint128_t)a->q);
525 m2 = ((__int128_t)(a->p)) * ((__uint128_t)b->q);
530 struct sr_int128_t m1, m2;
532 mult_int64(&m1, a->q, b->p);
533 mult_int64(&m2, a->p, b->q);
535 return (m1.high == m2.high) && (m1.low == m2.low);
540 * Multiply two sr_rational.
542 * The resulting nominator/denominator are reduced if the result would not fit
543 * otherwise. If the resulting nominator/denominator are relatively prime,
544 * this may not be possible.
546 * It is safe to use the same variable for result and input values.
548 * @param[in] a First value.
549 * @param[in] b Second value.
550 * @param[out] res Result.
552 * @retval SR_OK Success.
553 * @retval SR_ERR_ARG Resulting value too large.
557 SR_API int sr_rational_mult(struct sr_rational *res, const struct sr_rational *a,
558 const struct sr_rational *b)
560 #ifdef HAVE___INT128_T
564 p = (__int128_t)(a->p) * (__int128_t)(b->p);
565 q = (__uint128_t)(a->q) * (__uint128_t)(b->q);
567 if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
568 while (!((p & 1) || (q & 1))) {
574 if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
575 // TODO: determine gcd to do further reduction
580 res->q = (uint64_t)q;
585 struct sr_int128_t p;
586 struct sr_uint128_t q;
588 mult_int64(&p, a->p, b->p);
589 mult_uint64(&q, a->q, b->q);
591 while (!(p.low & 1) && !(q.low & 1)) {
594 p.low |= (1ll << 63);
598 q.low |= (1ll << 63);
604 if ((p.high >= 0) && (p.low > INT64_MAX))
609 res->p = (int64_t)p.low;
617 * Divide rational a by rational b.
619 * The resulting nominator/denominator are reduced if the result would not fit
620 * otherwise. If the resulting nominator/denominator are relatively prime,
621 * this may not be possible.
623 * It is safe to use the same variable for result and input values.
625 * @param[in] num Numerator.
626 * @param[in] div Divisor.
627 * @param[out] res Result.
629 * @retval SR_OK Success.
630 * @retval SR_ERR_ARG Division by zero, denominator of divisor too large,
631 * or resulting value too large.
635 SR_API int sr_rational_div(struct sr_rational *res, const struct sr_rational *num,
636 const struct sr_rational *div)
638 struct sr_rational t;
640 if (div->q > INT64_MAX)
653 return sr_rational_mult(res, num, &t);