private processNewCaption()

in packages/calling-stateful-client/src/CallContext.ts [1283:1319]


  private processNewCaption(captions: CaptionsInfo[], newCaption: CaptionsInfo): void {
    // time stamp when new caption comes in
    newCaption.lastUpdatedTimestamp = new Date();
    // if this is the first caption, push it in
    if (captions.length === 0) {
      captions.push(newCaption);
    }
    // if the last caption is final, then push the new one in
    else if (captions[captions.length - 1]?.resultType === 'Final') {
      captions.push(newCaption);
    }
    // if the last caption is Partial, then check if the speaker is the same as the new caption, if so, update the last caption
    else {
      const lastCaption = captions[captions.length - 1];
      if (
        lastCaption &&
        lastCaption.speaker.identifier &&
        newCaption.speaker.identifier &&
        toFlatCommunicationIdentifier(lastCaption.speaker.identifier) ===
          toFlatCommunicationIdentifier(newCaption.speaker.identifier)
      ) {
        captions[captions.length - 1] = newCaption;
      }
      // if different speaker, ignore the interjector until the current speaker finishes
      // edge case: if we dont receive the final caption from the current speaker for 5 secs, we turn the current speaker caption to final and push in the new interjector
      else if (lastCaption?.lastUpdatedTimestamp) {
        if (Date.now() - lastCaption.lastUpdatedTimestamp.getTime() > 5000) {
          lastCaption.resultType = 'Final';
          captions.push(newCaption);
        }
      }
    }
    // If the array length exceeds 50, remove the oldest caption
    if (captions.length > 50) {
      captions.shift();
    }
  }