Note: We no longer publish the latest version of our code here. We primarily use a kumc-bmi github organization. The heron ETL repository, in particular, is not public. Peers in the informatics community should see MultiSiteDev for details on requesting access.

source: webrtc/webrtc/modules/audio_coding/neteq/automode.c @ 0:4bda6873e34c

pub_scrub_3792 tip
Last change on this file since 0:4bda6873e34c was 0:4bda6873e34c, checked in by Michael Prittie <mprittie@…>, 6 years ago

Scrubbed password for publication.

File size: 25.6 KB
Line 
1/*
2 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11/*
12 * This file contains the implementation of automatic buffer level optimization.
13 */
14
15#include "automode.h"
16
17#include <assert.h>
18
19#include "signal_processing_library.h"
20
21#include "neteq_defines.h"
22
23#ifdef NETEQ_DELAY_LOGGING
24/* special code for offline delay logging */
25#include <stdio.h>
26#include "delay_logging.h"
27
28extern FILE *delay_fid2; /* file pointer to delay log file */
29#endif /* NETEQ_DELAY_LOGGING */
30
31// These two functions are copied from module_common_types.h, but adapted for C.
32int WebRtcNetEQ_IsNewerSequenceNumber(uint16_t sequence_number,
33                                      uint16_t prev_sequence_number) {
34  return sequence_number != prev_sequence_number &&
35         ((uint16_t) (sequence_number - prev_sequence_number)) < 0x8000;
36}
37
38int WebRtcNetEQ_IsNewerTimestamp(uint32_t timestamp, uint32_t prev_timestamp) {
39  return timestamp != prev_timestamp &&
40         ((uint32_t) (timestamp - prev_timestamp)) < 0x80000000;
41}
42
43int WebRtcNetEQ_UpdateIatStatistics(AutomodeInst_t *inst, int maxBufLen,
44                                    uint16_t seqNumber, uint32_t timeStamp,
45                                    int32_t fsHz, int mdCodec, int streamingMode)
46{
47    uint32_t timeIat; /* inter-arrival time */
48    int i;
49    int32_t tempsum = 0; /* temp summation */
50    int32_t tempvar; /* temporary variable */
51    int retval = 0; /* return value */
52    int16_t packetLenSamp; /* packet speech length in samples */
53
54    /****************/
55    /* Sanity check */
56    /****************/
57
58    if (maxBufLen <= 1 || fsHz <= 0)
59    {
60        /* maxBufLen must be at least 2 and fsHz must both be strictly positive */
61        return -1;
62    }
63
64    /****************************/
65    /* Update packet statistics */
66    /****************************/
67
68    /* Try calculating packet length from current and previous timestamps */
69    if (!WebRtcNetEQ_IsNewerTimestamp(timeStamp, inst->lastTimeStamp) ||
70        !WebRtcNetEQ_IsNewerSequenceNumber(seqNumber, inst->lastSeqNo))
71    {
72        /* Wrong timestamp or sequence order; revert to backup plan */
73        packetLenSamp = inst->packetSpeechLenSamp; /* use stored value */
74    }
75    else
76    {
77        /* calculate timestamps per packet */
78        packetLenSamp = (int16_t) WebRtcSpl_DivU32U16(timeStamp - inst->lastTimeStamp,
79            seqNumber - inst->lastSeqNo);
80    }
81
82    /* Check that the packet size is positive; if not, the statistics cannot be updated. */
83    if (inst->firstPacketReceived && packetLenSamp > 0)
84    { /* packet size ok */
85
86        /* calculate inter-arrival time in integer packets (rounding down) */
87        timeIat = WebRtcSpl_DivW32W16(inst->packetIatCountSamp, packetLenSamp);
88
89        /* Special operations for streaming mode */
90        if (streamingMode != 0)
91        {
92            /*
93             * Calculate IAT in Q8, including fractions of a packet (i.e., more accurate
94             * than timeIat).
95             */
96            int16_t timeIatQ8 = (int16_t) WebRtcSpl_DivW32W16(
97                WEBRTC_SPL_LSHIFT_W32(inst->packetIatCountSamp, 8), packetLenSamp);
98
99            /*
100             * Calculate cumulative sum iat with sequence number compensation (ideal arrival
101             * times makes this sum zero).
102             */
103            inst->cSumIatQ8 += (timeIatQ8
104                - WEBRTC_SPL_LSHIFT_W32(seqNumber - inst->lastSeqNo, 8));
105
106            /* subtract drift term */
107            inst->cSumIatQ8 -= CSUM_IAT_DRIFT;
108
109            /* ensure not negative */
110            inst->cSumIatQ8 = WEBRTC_SPL_MAX(inst->cSumIatQ8, 0);
111
112            /* remember max */
113            if (inst->cSumIatQ8 > inst->maxCSumIatQ8)
114            {
115                inst->maxCSumIatQ8 = inst->cSumIatQ8;
116                inst->maxCSumUpdateTimer = 0;
117            }
118
119            /* too long since the last maximum was observed; decrease max value */
120            if (inst->maxCSumUpdateTimer > (uint32_t) WEBRTC_SPL_MUL_32_16(fsHz,
121                MAX_STREAMING_PEAK_PERIOD))
122            {
123                inst->maxCSumIatQ8 -= 4; /* remove 1000*4/256 = 15.6 ms/s */
124            }
125        } /* end of streaming mode */
126
127        /* check for discontinuous packet sequence and re-ordering */
128        if (WebRtcNetEQ_IsNewerSequenceNumber(seqNumber, inst->lastSeqNo + 1))
129        {
130            /* Compensate for gap in the sequence numbers.
131             * Reduce IAT with expected extra time due to lost packets, but ensure that
132             * the IAT is not negative.
133             */
134            timeIat -= WEBRTC_SPL_MIN(timeIat,
135                (uint16_t) (seqNumber - (uint16_t) (inst->lastSeqNo + 1)));
136        }
137        else if (!WebRtcNetEQ_IsNewerSequenceNumber(seqNumber, inst->lastSeqNo))
138        {
139            /* compensate for re-ordering */
140            timeIat += (uint16_t) (inst->lastSeqNo + 1 - seqNumber);
141        }
142
143        /* saturate IAT at maximum value */
144        timeIat = WEBRTC_SPL_MIN( timeIat, MAX_IAT );
145
146        /* update iatProb = forgetting_factor * iatProb for all elements */
147        for (i = 0; i <= MAX_IAT; i++)
148        {
149            int32_t tempHi, tempLo; /* Temporary variables */
150
151            /*
152             * Multiply iatProbFact (Q15) with iatProb (Q30) and right-shift 15 steps
153             * to come back to Q30. The operation is done in two steps:
154             */
155
156            /*
157             * 1) Multiply the high 16 bits (15 bits + sign) of iatProb. Shift iatProb
158             * 16 steps right to get the high 16 bits in a int16_t prior to
159             * multiplication, and left-shift with 1 afterwards to come back to
160             * Q30 = (Q15 * (Q30>>16)) << 1.
161             */
162            tempHi = WEBRTC_SPL_MUL_16_16(inst->iatProbFact,
163                (int16_t) WEBRTC_SPL_RSHIFT_W32(inst->iatProb[i], 16));
164            tempHi = WEBRTC_SPL_LSHIFT_W32(tempHi, 1); /* left-shift 1 step */
165
166            /*
167             * 2) Isolate and multiply the low 16 bits of iatProb. Right-shift 15 steps
168             * afterwards to come back to Q30 = (Q15 * Q30) >> 15.
169             */
170            tempLo = inst->iatProb[i] & 0x0000FFFF; /* sift out the 16 low bits */
171            tempLo = WEBRTC_SPL_MUL_16_U16(inst->iatProbFact,
172                (uint16_t) tempLo);
173            tempLo = WEBRTC_SPL_RSHIFT_W32(tempLo, 15);
174
175            /* Finally, add the high and low parts */
176            inst->iatProb[i] = tempHi + tempLo;
177
178            /* Sum all vector elements while we are at it... */
179            tempsum += inst->iatProb[i];
180        }
181
182        /*
183         * Increase the probability for the currently observed inter-arrival time
184         * with 1 - iatProbFact. The factor is in Q15, iatProb in Q30;
185         * hence, left-shift 15 steps to obtain result in Q30.
186         */
187        inst->iatProb[timeIat] += (32768 - inst->iatProbFact) << 15;
188
189        tempsum += (32768 - inst->iatProbFact) << 15; /* add to vector sum */
190
191        /*
192         * Update iatProbFact (changes only during the first seconds after reset)
193         * The factor converges to IAT_PROB_FACT.
194         */
195        inst->iatProbFact += (IAT_PROB_FACT - inst->iatProbFact + 3) >> 2;
196
197        /* iatProb should sum up to 1 (in Q30). */
198        tempsum -= 1 << 30; /* should be zero */
199
200        /* Check if it does, correct if it doesn't. */
201        if (tempsum > 0)
202        {
203            /* tempsum too large => decrease a few values in the beginning */
204            i = 0;
205            while (i <= MAX_IAT && tempsum > 0)
206            {
207                /* Remove iatProb[i] / 16 from iatProb, but not more than tempsum */
208                tempvar = WEBRTC_SPL_MIN(tempsum, inst->iatProb[i] >> 4);
209                inst->iatProb[i++] -= tempvar;
210                tempsum -= tempvar;
211            }
212        }
213        else if (tempsum < 0)
214        {
215            /* tempsum too small => increase a few values in the beginning */
216            i = 0;
217            while (i <= MAX_IAT && tempsum < 0)
218            {
219                /* Add iatProb[i] / 16 to iatProb, but not more than tempsum */
220                tempvar = WEBRTC_SPL_MIN(-tempsum, inst->iatProb[i] >> 4);
221                inst->iatProb[i++] += tempvar;
222                tempsum += tempvar;
223            }
224        }
225
226        /* Calculate optimal buffer level based on updated statistics */
227        tempvar = (int32_t) WebRtcNetEQ_CalcOptimalBufLvl(inst, fsHz, mdCodec, timeIat,
228            streamingMode);
229        if (tempvar > 0)
230        {
231            int high_lim_delay;
232            /* Convert the minimum delay from milliseconds to packets in Q8.
233             * |fsHz| is sampling rate in Hertz, and |packetLenSamp|
234             * is the number of samples per packet (according to the last
235             * decoding).
236             */
237            int32_t minimum_delay_q8 = ((inst->minimum_delay_ms *
238                (fsHz / 1000)) << 8) / packetLenSamp;
239
240            int32_t maximum_delay_q8 = ((inst->maximum_delay_ms *
241              (fsHz / 1000)) << 8) / packetLenSamp;
242
243            inst->optBufLevel = tempvar;
244
245            if (streamingMode != 0)
246            {
247                inst->optBufLevel = WEBRTC_SPL_MAX(inst->optBufLevel,
248                    inst->maxCSumIatQ8);
249            }
250
251            /* The required delay. */
252            inst->required_delay_q8 = inst->optBufLevel;
253
254            // Maintain the target delay.
255            inst->optBufLevel = WEBRTC_SPL_MAX(inst->optBufLevel,
256                                               minimum_delay_q8);
257
258            if (maximum_delay_q8 > 0) {
259              // Make sure that max is at least one packet length.
260              maximum_delay_q8 = WEBRTC_SPL_MAX(maximum_delay_q8, (1 << 8));
261              inst->optBufLevel = WEBRTC_SPL_MIN(inst->optBufLevel,
262                                                 maximum_delay_q8);
263            }
264            /*********/
265            /* Limit */
266            /*********/
267
268            /* Subtract extra delay from maxBufLen */
269            if (inst->extraDelayMs > 0 && inst->packetSpeechLenSamp > 0)
270            {
271                maxBufLen -= inst->extraDelayMs / inst->packetSpeechLenSamp * fsHz / 1000;
272                maxBufLen = WEBRTC_SPL_MAX(maxBufLen, 1); // sanity: at least one packet
273            }
274
275            maxBufLen = WEBRTC_SPL_LSHIFT_W32(maxBufLen, 8); /* shift to Q8 */
276
277            /* Enforce upper limit; 75% of maxBufLen */
278            /* 1/2 + 1/4 = 75% */
279            high_lim_delay = (maxBufLen >> 1) + (maxBufLen >> 2);
280            inst->optBufLevel = WEBRTC_SPL_MIN(inst->optBufLevel,
281                                               high_lim_delay);
282            inst->required_delay_q8 = WEBRTC_SPL_MIN(inst->required_delay_q8,
283                                                     high_lim_delay);
284        }
285        else
286        {
287            retval = (int) tempvar;
288        }
289
290    } /* end if */
291
292    /*******************************/
293    /* Update post-call statistics */
294    /*******************************/
295
296    /* Calculate inter-arrival time in ms = packetIatCountSamp / (fsHz / 1000) */
297    timeIat = WEBRTC_SPL_UDIV(
298        WEBRTC_SPL_UMUL_32_16(inst->packetIatCountSamp, (int16_t) 1000),
299        (uint32_t) fsHz);
300
301    /* Increase counter corresponding to current inter-arrival time */
302    if (timeIat > 2000)
303    {
304        inst->countIAT2000ms++;
305    }
306    else if (timeIat > 1000)
307    {
308        inst->countIAT1000ms++;
309    }
310    else if (timeIat > 500)
311    {
312        inst->countIAT500ms++;
313    }
314
315    if (timeIat > inst->longestIATms)
316    {
317        /* update maximum value */
318        inst->longestIATms = timeIat;
319    }
320
321    /***********************************/
322    /* Prepare for next packet arrival */
323    /***********************************/
324
325    inst->packetIatCountSamp = 0; /* reset inter-arrival time counter */
326
327    inst->lastSeqNo = seqNumber; /* remember current sequence number */
328
329    inst->lastTimeStamp = timeStamp; /* remember current timestamp */
330
331    inst->firstPacketReceived = 1;
332
333    return retval;
334}
335
336
337int16_t WebRtcNetEQ_CalcOptimalBufLvl(AutomodeInst_t *inst, int32_t fsHz,
338                                      int mdCodec, uint32_t timeIatPkts,
339                                      int streamingMode)
340{
341
342    int32_t sum1 = 1 << 30; /* assign to 1 in Q30 */
343    int16_t B;
344    uint16_t Bopt;
345    int i;
346    int32_t betaInv; /* optimization parameter */
347
348#ifdef NETEQ_DELAY_LOGGING
349    /* special code for offline delay logging */
350    int temp_var;
351#endif
352
353    /****************/
354    /* Sanity check */
355    /****************/
356
357    if (fsHz <= 0)
358    {
359        /* fsHz must be strictly positive */
360        return -1;
361    }
362
363    /***********************************************/
364    /* Get betaInv parameter based on playout mode */
365    /***********************************************/
366
367    if (streamingMode)
368    {
369        /* streaming (listen-only) mode */
370        betaInv = AUTOMODE_STREAMING_BETA_INV_Q30;
371    }
372    else
373    {
374        /* normal mode */
375        betaInv = AUTOMODE_BETA_INV_Q30;
376    }
377
378    /*******************************************************************/
379    /* Calculate optimal buffer level without considering jitter peaks */
380    /*******************************************************************/
381
382    /*
383     * Find the B for which the probability of observing an inter-arrival time larger
384     * than or equal to B is less than or equal to betaInv.
385     */
386    B = 0; /* start from the beginning of iatProb */
387    sum1 -= inst->iatProb[B]; /* ensure that optimal level is not less than 1 */
388
389    do
390    {
391        /*
392         * Subtract the probabilities one by one until the sum is no longer greater
393         * than betaInv.
394         */
395        sum1 -= inst->iatProb[++B];
396    }
397    while ((sum1 > betaInv) && (B < MAX_IAT));
398
399    Bopt = B; /* This is our primary value for the optimal buffer level Bopt */
400
401    if (mdCodec)
402    {
403        /*
404         * Use alternative cost function when multiple description codec is in use.
405         * Do not have to re-calculate all points, just back off a few steps from
406         * previous value of B.
407         */
408        int32_t sum2 = sum1; /* copy sum1 */
409
410        while ((sum2 <= betaInv + inst->iatProb[Bopt]) && (Bopt > 0))
411        {
412            /* Go backwards in the sum until the modified cost function solution is found */
413            sum2 += inst->iatProb[Bopt--];
414        }
415
416        Bopt++; /* This is the optimal level when using an MD codec */
417
418        /* Now, Bopt and B can have different values. */
419    }
420
421#ifdef NETEQ_DELAY_LOGGING
422    /* special code for offline delay logging */
423    temp_var = NETEQ_DELAY_LOGGING_SIGNAL_OPTBUF;
424    if (fwrite( &temp_var, sizeof(int), 1, delay_fid2 ) != 1) {
425      return -1;
426    }
427    temp_var = (int) (Bopt * inst->packetSpeechLenSamp);
428#endif
429
430    /******************************************************************/
431    /* Make levelFiltFact adaptive: Larger B <=> larger levelFiltFact */
432    /******************************************************************/
433
434    switch (B)
435    {
436        case 0:
437        case 1:
438        {
439            inst->levelFiltFact = 251;
440            break;
441        }
442        case 2:
443        case 3:
444        {
445            inst->levelFiltFact = 252;
446            break;
447        }
448        case 4:
449        case 5:
450        case 6:
451        case 7:
452        {
453            inst->levelFiltFact = 253;
454            break;
455        }
456        default: /* B > 7 */
457        {
458            inst->levelFiltFact = 254;
459            break;
460        }
461    }
462
463    /************************/
464    /* Peak mode operations */
465    /************************/
466
467    /* Compare current IAT with peak threshold
468     *
469     * If IAT > optimal level + threshold (+1 for MD codecs)
470     * or if IAT > 2 * optimal level (note: optimal level is in Q8):
471     */
472    if (timeIatPkts > (uint32_t) (Bopt + inst->peakThresholdPkt + (mdCodec != 0))
473        || timeIatPkts > (uint32_t) WEBRTC_SPL_LSHIFT_U16(Bopt, 1))
474    {
475        /* A peak is observed */
476
477        if (inst->peakIndex == -1)
478        {
479            /* this is the first peak; prepare for next peak */
480            inst->peakIndex = 0;
481            /* set the mode-disable counter */
482            inst->peakModeDisabled = WEBRTC_SPL_LSHIFT_W16(1, NUM_PEAKS_REQUIRED-2);
483        }
484        else if (inst->peakIatCountSamp
485            <=
486            (uint32_t) WEBRTC_SPL_MUL_32_16(fsHz, MAX_PEAK_PERIOD))
487        {
488            /* This is not the first peak and the period time is valid */
489
490            /* store time elapsed since last peak */
491            inst->peakPeriodSamp[inst->peakIndex] = inst->peakIatCountSamp;
492
493            /* saturate height to 16 bits */
494            inst->peakHeightPkt[inst->peakIndex]
495                =
496                (int16_t) WEBRTC_SPL_MIN(timeIatPkts, WEBRTC_SPL_WORD16_MAX);
497
498            /* increment peakIndex and wrap/modulo */
499            inst->peakIndex = (inst->peakIndex + 1) & PEAK_INDEX_MASK;
500
501            /* process peak vectors */
502            inst->curPeakHeight = 0;
503            inst->curPeakPeriod = 0;
504
505            for (i = 0; i < NUM_PEAKS; i++)
506            {
507                /* Find maximum of peak heights and peak periods */
508                inst->curPeakHeight
509                    = WEBRTC_SPL_MAX(inst->curPeakHeight, inst->peakHeightPkt[i]);
510                inst->curPeakPeriod
511                    = WEBRTC_SPL_MAX(inst->curPeakPeriod, inst->peakPeriodSamp[i]);
512
513            }
514
515            inst->peakModeDisabled >>= 1; /* decrease mode-disable "counter" */
516
517        }
518        else if (inst->peakIatCountSamp > (uint32_t) WEBRTC_SPL_MUL_32_16(fsHz,
519            WEBRTC_SPL_LSHIFT_W16(MAX_PEAK_PERIOD, 1)))
520        {
521            /*
522             * More than 2 * MAX_PEAK_PERIOD has elapsed since last peak;
523             * too long time => reset peak statistics
524             */
525            inst->curPeakHeight = 0;
526            inst->curPeakPeriod = 0;
527            for (i = 0; i < NUM_PEAKS; i++)
528            {
529                inst->peakHeightPkt[i] = 0;
530                inst->peakPeriodSamp[i] = 0;
531            }
532
533            inst->peakIndex = -1; /* Next peak is first peak */
534            inst->peakIatCountSamp = 0;
535        }
536
537        inst->peakIatCountSamp = 0; /* Reset peak interval timer */
538    } /* end if peak is observed */
539
540    /* Evaluate peak mode conditions */
541
542    /*
543     * If not disabled (enough peaks have been observed) and
544     * time since last peak is less than two peak periods.
545     */
546    inst->peakFound = 0;
547    if ((!inst->peakModeDisabled) && (inst->peakIatCountSamp
548        <= WEBRTC_SPL_LSHIFT_W32(inst->curPeakPeriod , 1)))
549    {
550        /* Engage peak mode */
551        inst->peakFound = 1;
552        /* Set optimal buffer level to curPeakHeight (if it's not already larger) */
553        Bopt = WEBRTC_SPL_MAX(Bopt, inst->curPeakHeight);
554
555#ifdef NETEQ_DELAY_LOGGING
556        /* special code for offline delay logging */
557        temp_var = (int) -(Bopt * inst->packetSpeechLenSamp);
558#endif
559    }
560
561    /* Scale Bopt to Q8 */
562    Bopt = WEBRTC_SPL_LSHIFT_U16(Bopt,8);
563
564#ifdef NETEQ_DELAY_LOGGING
565    /* special code for offline delay logging */
566    if (fwrite( &temp_var, sizeof(int), 1, delay_fid2 ) != 1) {
567      return -1;
568    }
569#endif
570
571    /* Sanity check: Bopt must be strictly positive */
572    if (Bopt <= 0)
573    {
574        Bopt = WEBRTC_SPL_LSHIFT_W16(1, 8); /* 1 in Q8 */
575    }
576
577    return Bopt; /* return value in Q8 */
578}
579
580
581int WebRtcNetEQ_BufferLevelFilter(int32_t curSizeMs8, AutomodeInst_t *inst,
582                                  int sampPerCall, int16_t fsMult)
583{
584
585    int16_t curSizeFrames;
586
587    /****************/
588    /* Sanity check */
589    /****************/
590
591    if (sampPerCall <= 0 || fsMult <= 0)
592    {
593        /* sampPerCall and fsMult must both be strictly positive */
594        return -1;
595    }
596
597    /* Check if packet size has been detected */
598    if (inst->packetSpeechLenSamp > 0)
599    {
600        /*
601         * Current buffer level in packet lengths
602         * = (curSizeMs8 * fsMult) / packetSpeechLenSamp
603         */
604        curSizeFrames = (int16_t) WebRtcSpl_DivW32W16(
605            WEBRTC_SPL_MUL_32_16(curSizeMs8, fsMult), inst->packetSpeechLenSamp);
606    }
607    else
608    {
609        curSizeFrames = 0;
610    }
611
612    /* Filter buffer level */
613    if (inst->levelFiltFact > 0) /* check that filter factor is set */
614    {
615        /* Filter:
616         * buffLevelFilt = levelFiltFact * buffLevelFilt
617         *                  + (1-levelFiltFact) * curSizeFrames
618         *
619         * levelFiltFact is in Q8
620         */
621        inst->buffLevelFilt = ((inst->levelFiltFact * inst->buffLevelFilt) >> 8) +
622            (256 - inst->levelFiltFact) * curSizeFrames;
623    }
624
625    /* Account for time-scale operations (accelerate and pre-emptive expand) */
626    if (inst->prevTimeScale)
627    {
628        /*
629         * Time-scaling has been performed since last filter update.
630         * Subtract the sampleMemory from buffLevelFilt after converting sampleMemory
631         * from samples to packets in Q8. Make sure that the filtered value is
632         * non-negative.
633         */
634        inst->buffLevelFilt = WEBRTC_SPL_MAX( inst->buffLevelFilt -
635            WebRtcSpl_DivW32W16(
636                WEBRTC_SPL_LSHIFT_W32(inst->sampleMemory, 8), /* sampleMemory in Q8 */
637                inst->packetSpeechLenSamp ), /* divide by packetSpeechLenSamp */
638            0);
639
640        /*
641         * Reset flag and set timescaleHoldOff timer to prevent further time-scaling
642         * for some time.
643         */
644        inst->prevTimeScale = 0;
645        inst->timescaleHoldOff = AUTOMODE_TIMESCALE_LIMIT;
646    }
647
648    /* Update time counters and HoldOff timer */
649    inst->packetIatCountSamp += sampPerCall; /* packet inter-arrival time */
650    inst->peakIatCountSamp += sampPerCall; /* peak inter-arrival time */
651    inst->timescaleHoldOff >>= 1; /* time-scaling limiter */
652    inst->maxCSumUpdateTimer += sampPerCall; /* cumulative-sum timer */
653
654    return 0;
655
656}
657
658
659int WebRtcNetEQ_SetPacketSpeechLen(AutomodeInst_t *inst, int16_t newLenSamp,
660                                   int32_t fsHz)
661{
662
663    /* Sanity check for newLenSamp and fsHz */
664    if (newLenSamp <= 0 || fsHz <= 0)
665    {
666        return -1;
667    }
668
669    inst->packetSpeechLenSamp = newLenSamp; /* Store packet size in instance */
670
671    /* Make NetEQ wait for first regular packet before starting the timer */
672    inst->lastPackCNGorDTMF = 1;
673
674    inst->packetIatCountSamp = 0; /* Reset packet time counter */
675
676    /*
677     * Calculate peak threshold from packet size. The threshold is defined as
678     * the (fractional) number of packets that corresponds to PEAK_HEIGHT
679     * (in Q8 seconds). That is, threshold = PEAK_HEIGHT/256 * fsHz / packLen.
680     */
681    inst->peakThresholdPkt = (uint16_t) WebRtcSpl_DivW32W16ResW16(
682        WEBRTC_SPL_MUL_16_16_RSFT(PEAK_HEIGHT,
683            (int16_t) WEBRTC_SPL_RSHIFT_W32(fsHz, 6), 2), inst->packetSpeechLenSamp);
684
685    return 0;
686}
687
688
689int WebRtcNetEQ_ResetAutomode(AutomodeInst_t *inst, int maxBufLenPackets)
690{
691
692    int i;
693    uint16_t tempprob = 0x4002; /* 16384 + 2 = 100000000000010 binary; */
694
695    /* Sanity check for maxBufLenPackets */
696    if (maxBufLenPackets <= 1)
697    {
698        /* Invalid value; set to 10 instead (arbitary small number) */
699        maxBufLenPackets = 10;
700    }
701
702    /* Reset filtered buffer level */
703    inst->buffLevelFilt = 0;
704
705    /* Reset packet size to unknown */
706    inst->packetSpeechLenSamp = 0;
707
708    /*
709     * Flag that last packet was special payload, so that automode will treat the next speech
710     * payload as the first payload received.
711     */
712    inst->lastPackCNGorDTMF = 1;
713
714    /* Reset peak detection parameters */
715    inst->peakModeDisabled = 1; /* disable peak mode */
716    inst->peakIatCountSamp = 0;
717    inst->peakIndex = -1; /* indicates that no peak is registered */
718    inst->curPeakHeight = 0;
719    inst->curPeakPeriod = 0;
720    for (i = 0; i < NUM_PEAKS; i++)
721    {
722        inst->peakHeightPkt[i] = 0;
723        inst->peakPeriodSamp[i] = 0;
724    }
725
726    /*
727     * Set the iatProb PDF vector to an exponentially decaying distribution
728     * iatProb[i] = 0.5^(i+1), i = 0, 1, 2, ...
729     * iatProb is in Q30.
730     */
731    for (i = 0; i <= MAX_IAT; i++)
732    {
733        /* iatProb[i] = 0.5^(i+1) = iatProb[i-1] / 2 */
734        tempprob = WEBRTC_SPL_RSHIFT_U16(tempprob, 1);
735        /* store in PDF vector */
736        inst->iatProb[i] = WEBRTC_SPL_LSHIFT_W32((int32_t) tempprob, 16);
737    }
738
739    /*
740     * Calculate the optimal buffer level corresponding to the initial PDF.
741     * No need to call WebRtcNetEQ_CalcOptimalBufLvl() since we have just hard-coded
742     * all the variables that the buffer level depends on => we know the result
743     */
744    inst->optBufLevel = WEBRTC_SPL_MIN(4,
745        (maxBufLenPackets >> 1) + (maxBufLenPackets >> 1)); /* 75% of maxBufLenPackets */
746    inst->required_delay_q8 = inst->optBufLevel;
747    inst->levelFiltFact = 253;
748
749    /*
750     * Reset the iat update forgetting factor to 0 to make the impact of the first
751     * incoming packets greater.
752     */
753    inst->iatProbFact = 0;
754
755    /* Reset packet inter-arrival time counter */
756    inst->packetIatCountSamp = 0;
757
758    /* Clear time-scaling related variables */
759    inst->prevTimeScale = 0;
760    inst->timescaleHoldOff = AUTOMODE_TIMESCALE_LIMIT; /* don't allow time-scaling immediately */
761
762    inst->cSumIatQ8 = 0;
763    inst->maxCSumIatQ8 = 0;
764
765    return 0;
766}
767
768int32_t WebRtcNetEQ_AverageIAT(const AutomodeInst_t *inst) {
769  int i;
770  int32_t sum_q24 = 0;
771  assert(inst);
772  for (i = 0; i <= MAX_IAT; ++i) {
773    /* Shift 6 to fit worst case: 2^30 * 64. */
774    sum_q24 += (inst->iatProb[i] >> 6) * i;
775  }
776  /* Subtract the nominal inter-arrival time 1 = 2^24 in Q24. */
777  sum_q24 -= (1 << 24);
778  /*
779   * Multiply with 1000000 / 2^24 = 15625 / 2^18 to get in parts-per-million.
780   * Shift 7 to Q17 first, then multiply with 15625 and shift another 11.
781   */
782  return ((sum_q24 >> 7) * 15625) >> 11;
783}
Note: See TracBrowser for help on using the repository browser.