Fix SBR encoder element mapping for channel configurations with more than one layer

Bug: 149489652
Test: atest android.media.cts.EncoderTest#testAACEncoders
Change-Id: I8cd9e7f9aaeb62629f916f8d0dba7422d9a5e878
diff --git a/libAACenc/src/aacenc_lib.cpp b/libAACenc/src/aacenc_lib.cpp
index 0f0094f..15b06bd 100644
--- a/libAACenc/src/aacenc_lib.cpp
+++ b/libAACenc/src/aacenc_lib.cpp
@@ -446,6 +446,24 @@
   return sbrSignaling;
 }
 
+static inline INT getAssociatedChElement(SBR_ELEMENT_INFO *elInfoSbr,
+                                         CHANNEL_MAPPING *channelMapping) {
+  ELEMENT_INFO *elInfo = channelMapping->elInfo;
+  INT nElements = channelMapping->nElements;
+  INT associatedChElement = -1;
+  int i;
+
+  for (i = 0; i < nElements; i++) {
+    if (elInfoSbr->elType == elInfo[i].elType &&
+        elInfoSbr->instanceTag == elInfo[i].instanceTag) {
+      associatedChElement = i;
+      break;
+    }
+  }
+
+  return associatedChElement;
+}
+
 /****************************************************************************
                                Allocate Encoder
 ****************************************************************************/
@@ -1921,7 +1939,15 @@
           {
             hAacEncoder->extPayload[nExtensions].dataSize =
                 hAacEncoder->pSbrPayload->dataSize[nPayload][i];
-            hAacEncoder->extPayload[nExtensions].associatedChElement = i;
+            hAacEncoder->extPayload[nExtensions].associatedChElement =
+                getAssociatedChElement(
+                    &hAacEncoder->hEnvEnc->sbrElement[i]->elInfo,
+                    &hAacEncoder->hAacEnc->channelMapping);
+            if (hAacEncoder->extPayload[nExtensions].associatedChElement ==
+                -1) {
+              err = AACENC_ENCODE_ERROR;
+              goto bail;
+            }
           }
           hAacEncoder->extPayload[nExtensions].dataType =
               EXT_SBR_DATA; /* Once SBR Encoder supports SBR CRC set