]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - processor-sdk/performance-audio-sr.git/blob - pasdk/test_dsp/framework/audioStreamInpProcNewIO.c
PASDK 564: Removed one dependency of hard coded number from the input task initializa...
[processor-sdk/performance-audio-sr.git] / pasdk / test_dsp / framework / audioStreamInpProcNewIO.c
2 /*
3 Copyright (c) 2016, Texas Instruments Incorporated - http://www.ti.com/
4 All rights reserved.
6 * Redistribution and use in source and binary forms, with or without 
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the
16 * distribution.
17 *
18 * Neither the name of Texas Instruments Incorporated nor the names of
19 * its contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 *
34 */
36 /*
37  *  ======== audioStreamInpProcNewIo.c ========
38  */
39 #include <xdc/runtime/Log.h>
40 #include <ti/sysbios/BIOS.h>
41 #include <xdc/runtime/Error.h>
42 #include <ti/sysbios/knl/Event.h>
44 #include "procsdk_audio_typ.h"
45 #include "audioStreamInpProc.h"
46 #include "audioStreamProc_common.h"
47 #include "aspMsg_common.h"
48 #include "aspMsg_master.h"
49 #include "asperr.h"
50 #include "common.h"
52 #include "audk2g.h"
53 #include "audk2g_audio.h"
54 #include "mcasp_cfg.h"
55 #include "ioConfig.h"    //TODO: remove this header
56 #include "ioBuff.h"
57 #include "ioPhy.h"
58 #include "ioData.h"
61 #define STRIDE_WORST_CASE 32  // 4-byte (32-bit) word, 2 slots, 4 serializers
63 //#define DEBUG_SKIP_DECODING
65 #define SYNC_PC_MASK         0x1F
66 #define SYNC_SUBTYPE_MASK    0x700
67 #define SYNC_SUBTYPE_SHIFT   8
68 #define SYNC_SUBTYPE_DTSHD   0x11
69 #define SYNC_DDP             0x15
70 #define SYNC_THD             0x16
72 #define IEC_HEADER_LENGTH    4
74 #define INPUT_SWITCH_HANGOVER 8
76 //table needed until PAF_SOURCE is reordered to match IEC numbering
77 const SmUns IECpafSource[23] =
78 {
79     PAF_SOURCE_UNKNOWN,  // 0: IEC NULL Type
80     PAF_SOURCE_AC3,      // 1: Comments on 1-15 match IEC 61937 part 2.
81     PAF_SOURCE_UNKNOWN,  // 2: IEC reserved
82     PAF_SOURCE_UNKNOWN,  // 3: IEC pause
83     PAF_SOURCE_UNKNOWN,  // 4: MPEG 1 layer 1
84     PAF_SOURCE_MP3,      // 5: MPEG layer 2 or 3
85     PAF_SOURCE_UNKNOWN,  // 6: MPEG 2 data with extension
86     PAF_SOURCE_AAC,      // 7: MPEG-2 AAC ADTS
87     PAF_SOURCE_UNKNOWN,  // 8: MPEG 2 layer 1 low sampling frequency
88     PAF_SOURCE_UNKNOWN,  // 9: MPEG 2 layer 2 or 3 low sampling frequency
89     PAF_SOURCE_UNKNOWN,  // 10: reserved
90     PAF_SOURCE_DTS,      // 11: DTS type 1 (11 bit: 512 sample repeat period)
91     PAF_SOURCE_DTS12,    // 12: DTS type 2 (12 bit: 1024 sample repeat period)
92     PAF_SOURCE_DTS13,    // 13: DTS type 3 (13 bit: 2048 sample repeat period)
93     PAF_SOURCE_DTS14,    // 14: ATRAC
94     PAF_SOURCE_UNKNOWN,  // 15: ATRAC 2/3
95     PAF_SOURCE_THD,      // 16
96     PAF_SOURCE_DTSHD,    // 17
97     PAF_SOURCE_WMA9PRO,  // 18
98     PAF_SOURCE_UNKNOWN,  // 19
99     PAF_SOURCE_UNKNOWN,  // 20
100     PAF_SOURCE_DDP,      // 21
101     PAF_SOURCE_THD,      // 22
102 };
104 /*
105  * Functions defined in other files and to be put into proper header files
106  */
107 extern Void taskAsipFxnInit(const PAF_ASIT_Params *pP,const PAF_ASIT_Patchs *pQ);
110 // avoid including sap_d10.h, which would cause symbol redefinition
111 // warning (MCASP_PFUNC_XXX)
112 extern XDAS_Int32 D10_init(void * pD10Params);
114 extern XDAS_Int32 D10_RxControl(const void *pD10RxParams,
115                                 XDAS_Int32 code, XDAS_Int32 arg);
117 /*
118  * Functions only used in this file
119  */
120 int asitPrepareProcessing();
121 int asitIoCompsInit(PAF_AST_InpBuf * pInpBuf, PAF_AST_IoInp * pInpIo);
122 void asitProcInit(PAF_AST_IoInp  *pInp, asipDecProc_t *pDec);
123 void asitIoPhyPrime(PAF_AST_IoInp *pInpIo);
124 void asitPhyTransferComplete(PAF_AST_IoInp * pInpIo);
125 void asitPhyTransferStart(PAF_AST_IoInp *pInpIo);
126 Int asitRecfgPhyXfer(PAF_AST_IoInp *pInp, size_t xferSize);
127 Int asitSelectDevices(const PAF_ASIT_Patchs *pQ, PAF_AST_Config *pAstCfg, PAF_AST_IoInp *pInp);
128 Int asitUpdateInputStatus(const void *pRxParams, PAF_InpBufStatus *pStatus,
129                           PAF_InpBufConfig *pInpBuf);
131 Int asitSourceDetection(const PAF_ASIT_Params *pP,
132                         const PAF_ASIT_Patchs *pQ,
133                         PAF_ASIT_Config       *pAsitCfg);
135 Int asitDecideSource(PAF_AST_Config *pAstCfg, PAF_AST_IoInp  *pInp,
136                      ioDataAutoDetStat_t *autoDetStatus);
137 Int asitUpdateIoComps(const PAF_ASIT_Params *pP, PAF_AST_Config *pAstCfg,
138                       PAF_AST_IoInp  *pInp, ioDataAutoDetStat_t *autoDetStatus);
139 Int asitBypassIoData(PAF_AST_IoInp *pInp);
140 Int asitPcmTransition(PAF_ASIT_Config *pAsitCfg);
142 void asitUpdateInpBufConfig(PAF_AST_Config *pAstCfg, PAF_AST_IoInp  *pInp);
143 Int asitInputDataProcess(PAF_AST_IoInp *pInp, ioDataAutoDetStat_t *pAutoDetStats);
145 UInt asitEventsToDecMsg(UInt asitEvents);
146 void asitErrorHandling(PAF_ASIT_Config *pAsitCfg, Int asitErr);
147 Int asitEvtErrCheck(UInt actualEvents, UInt expectedEvents);
149 void asitPostInfoEvent();
150 void asitPostDecEvent();
152 /*
153  * variables/structures to be put into proper global structures
154  */
155 extern PAF_ASIT_Config gPAF_ASIT_config;
156 extern const MdUns iecFrameLength[23];
157 extern Ptr hMcaspRxChan;
159 // temp for simulation
160 //#define ASIT_ALL_EVENTS (  ASIT_EVTMSK_INPDATA \
161 //                         + ASIT_EVTMSK_INFOACK \
162 //                         + ASIT_EVTMSK_DECACK )
163 #define ASIT_ALL_EVENTS (  ASIT_EVTMSK_INPDATA \
164                          + ASIT_EVTMSK_RXACK )
166 // temp for simulation
167 //#define ASIT_DEC_EVENTS (  ASIT_EVTMSK_INPDATA \
168 //                         + ASIT_EVTMSK_INFOACK \
169 //                         + ASIT_EVTMSK_DECACK )
170 #define ASIT_DEC_EVENTS (  ASIT_EVTMSK_INPDATA \
171                          + ASIT_EVTMSK_RXACK )
173 #define ASIP_DEBUG
175 #ifdef ASIP_DEBUG
176 /* define the following as global variables for easy debugging */
177 int asipLoopCount1, asipLoopCount2;
178 Int asipErrno;
179 Int inputReadyForProcessing;
181 // debug
182 #include "evmc66x_gpio_dbg.h"
183 #endif
185 Event_Handle gAsitEvtHandle;            // ASIT event handle
186 Int eventsOn;                           // flag indicating whether to process events
188 SyncEvent_Handle gAsitSyncEvtHandle;    // ASIT Sync event handle
190 /*
191  *  ======== taskAsipFxn ========
192  *  Audio Stream Input Processing task function
193  */
194 #ifndef PASDK_SIO_DEV
195 #ifndef IO_LOOPBACK_TEST
196 Void taskAsipFxn(                  // ASIP task function for new I/O
197 #else
198 Void taskAsipFxn_NewIO_Not_Used(   // not used for loopback test
199 #endif
200 #else
201 Void taskAsipFxn_NewIO_Not_USED(   // not used for SIO/DEV based I/O
202 #endif
203     const PAF_ASIT_Params *pP,
204         const PAF_ASIT_Patchs *pQ)
206     PAF_ASIT_Config *pAsitCfg;      /* ASIT configuration pointer */
207     PAF_AST_Config  *pAstCfg;       /* AST Common (shared) configuration pointer */
208     PAF_AST_IoInp *pInp;            /* Input I/O components */
209     Int as;                         /* Audio Stream Number (1, 2, etc.) */
210     Int z;                          /* input/encode/stream/decode/output counter */
211     Int zMI;
212 #ifndef ASIP_DEBUG
213 int asipLoopCount1, asipLoopCount2;
214 Int asipErrno;
215 Int inputReadyForProcessing;
216 #endif
217     Int asitErr;
218     UInt events;
219 //    Int eventsOn;
220 //    Error_Block  eb;
222     Log_info0("Enter taskAsipFxn()");
224     taskAsipFxnInit(pP, pQ);  // initialization of input task
225     
226     //
227     // Audio Stream Input Task Configuration (*pAsitCfg):
228     //
229     pAsitCfg = &gPAF_ASIT_config;       // initialize pointer to task configuration
230     pAstCfg  = pAsitCfg->pAstCfg;       // pointer to AST common (shared) configuration
232     /* Set Audio Stream Number (1, 2, etc.) */
233     as = pAstCfg->as;
235     //
236     // Determine decoder and stream indices associated with the master input
237     //
238     zMI  = pP->zone.master;
239     pInp = &pAsitCfg->pIoInp[zMI];        // pointer to input I/O components
241     for (z=STREAM1; z < STREAMN; z++)
242     {
243         TRACE_VERBOSE1("TaskAsip: AS%d: running", as+z);
244     }
246     Log_info0("TaskAsip: Entering Main Loop.");
248     //
249     // Main processing loop
250     //
251     asipLoopCount1 = 0;
252     asipLoopCount2 = 0;
253     asitErr = ASIT_NO_ERR;
255     // The events_on flag will be removed if the RESTART state is changed to
256     // event-based scheduling instead of polling
257     eventsOn = FALSE;
259     for (;;)
260     {
261         asipLoopCount1++;
263         if(eventsOn) {
264             events = Event_pend(gAsitEvtHandle, ASIT_EVTMSK_NONE, ASIT_ALL_EVENTS,
265                                 BIOS_WAIT_FOREVER);
266         }
267         switch (pInp->asipState)
268         {
269         case ASIT_RESET:    // No events pending in this state
270             // Indicate decoder no decoding yet
271             pP->fxns->sourceDecode(pP, pQ, pAsitCfg, PAF_SOURCE_NONE);
273             // 5 system tick, or 5 msec. Should remove this later when implementing
274             // event based scheduling.
275             Task_sleep(5);
277             inputReadyForProcessing = asitPrepareProcessing(pP, pQ, pAsitCfg, &asipErrno);
278             if (inputReadyForProcessing) {
279                 TRACE_VERBOSE0("TaskAsip: Input is ready. Initialize I/O components.");
280                 // Input is ready for processing, so we initialize the I/O components.
281                 // Note that the I/O components init. and I/O PHY prime are performed only
282                 // at the first time. This should be changed later - init. and prime
283                 // should be done whenever input interface has changed.
284                 asitErr = asitIoCompsInit(&pAstCfg->xInp[zMI], pInp);
286                 // Initialize ASIT processing
287                 asitProcInit(pInp, &pAsitCfg->inpDec);
288                 pInp->asipState = ASIT_SOURCE_DETECTION;
289                 eventsOn = TRUE;   // turn on events pending
290                 TRACE_VERBOSE0("TaskAsip: turn on events and go to source detection.");
291             }
292             break;
294         case ASIT_SOURCE_DETECTION:
295             // Source unknown - to detect & identify source
296             if(events == ASIT_EVTMSK_INPDATA) {  
297                 // Only this event is expected. If any other event, it's error.
298                 // Input data is ready - perform source detection.
299                 // New state will be decided inside the function
300                 asitErr = asitSourceDetection(pP, pQ, pAsitCfg);
301             }
302             else {
303                 //Error checking & debug
304                 asitErr = asitEvtErrCheck(events, ASIT_EVTMSK_INPDATA);
305             }
307             break;
309         case ASIT_PCM_TRANSITION:
310             // Source is PCM - transition to PCM decoding
311             if(events == ASIT_EVTMSK_INPDATA) {
312                 // Only this event is expected. If any other event, it's error.
313                 // Input data is ready - transition to PCM decoding
314                 // New state will be decided inside the function
315                 asitErr = asitPcmTransition(pAsitCfg);
316             }
317             else {
318                 //Error checking & debug
319                 asitErr = asitEvtErrCheck(events, ASIT_EVTMSK_INPDATA);
320             }
321             break;
323         case ASIT_DECODE_PROCESSING:
324             if(events & ASIT_DEC_EVENTS) {
325                 // Decode processing for either PCM or bitstream
326                 // New state will be decided inside the function
327                 asitErr = asitDecodeProcessing(pP, pQ, pAsitCfg, events);
328             }
329             else {
330                 //Error checking & debug
331                 asitErr = asitEvtErrCheck(events, ASIT_DEC_EVENTS);
332             }
333             break;
335         default:
336             break;
337         }
339         if(asitErr) {
340             asitErrorHandling(pAsitCfg, asitErr);
342             if(pInp->asipState == ASIT_RESET) {
343                 eventsOn = FALSE;
344             }
346             asitErr = ASIT_NO_ERR;
347         }
349     }  // for (;;)
351 }  /* taskAsipFxn */
354 /*===========================================================================
355  * ASIT Processing Preparation
356  * Output:
357  *        - return        TRUE (input is ready) or FALSE (input is not ready)
358  *        - *asipErrno    Error number
359 ============================================================================*/
360 Int asitPrepareProcessing(const PAF_ASIT_Params *pP,
361                           const PAF_ASIT_Patchs *pQ,
362                           PAF_ASIT_Config       *pC,
363                           Int                   *asipErrno)
365     Int as, zMS, zMI, zMD;
366     Int sourceConfig, mode;
367     PAF_AST_Config  *pAstCfg;
368     PAF_AST_IoInp *pInp;            /* I/O components for input */
370     pAstCfg  = pC->pAstCfg;         // pointer to AST common (shared) configuration
371     as  = pAstCfg->as;
372     zMI = pP->zone.master;
373     zMD = pAstCfg->masterDec;
374     zMS = pAstCfg->masterStr;
375     pInp = pC->pIoInp;              // pointer to input I/O components
377     *asipErrno = 0;
379     // Select source and initialize physical layer / HW interface
380     *asipErrno = asitSelectDevices(pQ, pAstCfg, pInp);
381     if (*asipErrno) {
382         TRACE_TERSE2("asitSelectDevices returned asipErrno = 0x%04x at line %d. AS%d",
383                      *asipErrno, as+zMS);
384         return FALSE;    // Input is not ready for processing due to error
385     }
387     // If no master input selected then we don't know what may be at the input,
388     // so set to unknown and skip any remaining processing
389     if (!pInp[zMI].pRxParams) {
390         sharedMemWriteInt8(&(pAstCfg->xDec[zMD].decodeStatus.sourceProgram),
391                            (Int8)PAF_SOURCE_UNKNOWN, GATEMP_INDEX_DEC);
393         TRACE_VERBOSE1("TaskAsip: AS%d: No input selected...", as+zMS);
394         return FALSE;    // No error, but input is not ready for processing
395     }
397     // If here then we have a valid input so query its status
398     *asipErrno = asitUpdateInputStatus(pInp[zMI].pRxParams,
399                                    &pAstCfg->xInp[zMI].inpBufStatus,
400                                    &pAstCfg->xInp[zMI].inpBufConfig);
401     if(*asipErrno) {
402         TRACE_VERBOSE1("TaskAsip: updateInputStatus returns 0x%x", *asipErrno);
403         return FALSE;   // Input is not ready for processing due to error
404     }
406     // If master decoder is not enabled, or the input is unlocked, then do nothing
407     mode = (Int)sharedMemReadInt8(&(pAstCfg->xDec[zMD].decodeStatus.mode),
408                                   GATEMP_INDEX_DEC);
409     if (!mode || !pAstCfg->xInp[zMI].inpBufStatus.lock)
410     {
411         TRACE_VERBOSE0("TaskAsip: Not locked, continue");
412         return FALSE;  // No error, but input is not ready for processing
413     }
415     // Check selected source: sourceSelect is set by another task, AIP or AFP
416     sourceConfig = (Int)sharedMemReadInt8(&(pAstCfg->xDec[zMD].decodeStatus.sourceSelect),
417                                           GATEMP_INDEX_DEC);
418     // If no source selected then do nothing
419     if(sourceConfig == PAF_SOURCE_NONE) {
420         sharedMemWriteInt8(&(pAstCfg->xDec[zMD].decodeStatus.sourceProgram),
421                            (Int8)PAF_SOURCE_NONE, GATEMP_INDEX_DEC);
422         TRACE_VERBOSE1("TaskAsip: AS%d: no source selected, continue", as+zMS);
423         return FALSE;  // No error, but input is not ready for processing
424     }
426     // If we want pass processing then proceed directly
427     if (sourceConfig == PAF_SOURCE_PASS)
428     {
429         TRACE_VERBOSE1("TaskAsip: AS%d: Pass processing ...", as+zMS);
430         sharedMemWriteInt8(&(pAstCfg->xDec[zMD].decodeStatus.sourceProgram),
431                            (Int8)PAF_SOURCE_PASS, GATEMP_INDEX_DEC);
433         pP->fxns->sourceDecode(pP, pQ, pC, PAF_SOURCE_PASS);
434         if (pP->fxns->passProcessing) {
435             *asipErrno = pP->fxns->passProcessing(pP, pQ, pC, NULL);
436         }
437         else {
438             TRACE_TERSE2("TaskAsip: AS%d: Pass Processing not supported, asipErrno 0x%x",
439                          as+zMS, ASPERR_PASS);
440             *asipErrno = ASPERR_PASS;
441         }
443         TRACE_VERBOSE0("TaskAsip: continue");
444         return FALSE;  // Error or not, input is not ready for processing
445     }
447     // No error and input processing is ready
448     return TRUE;
449 } /* asitPrepareProcessing */
452 /*===========================================================================
453  * ASIT Source Detection:
454  *     ASIT processing for input source identification:
455  *     - mark I/O PHY transfer completion
456  *     - run auto-detection via I/O DATA in asitInputDataProcess
457  *     - mark I/O DATA read completion
458  *     - check auto-detection status and take corresponding actions if either
459  *       PCM or bitstream is identified:
460  *       - decide input source
461  *       - update I/O components
462  *       - reconfigure McASP LLD if it is PCM
463  *     - start next I/O PHY transfer
464 ============================================================================*/
465 Int asitSourceDetection(const PAF_ASIT_Params *pP,
466                         const PAF_ASIT_Patchs *pQ,
467                         PAF_ASIT_Config       *pAsitCfg)
469     PAF_AST_Config  *pAstCfg;
470     PAF_AST_IoInp *pInp;                // I/O components for input
471     Int zMD, mcaspErr, asitErr;
472     ioDataAutoDetStat_t autoDetStatus;
474     pAstCfg  = pAsitCfg->pAstCfg;               // pointer to AST common (shared) configuration
475     zMD = pAstCfg->masterDec;
476     pInp = &pAsitCfg->pIoInp[zMD];              // pointer to input I/O components
478     // Marks I/O PHY transfer and I/O BUFF write complete
479     asitPhyTransferComplete(pInp);
481     // Process input data - either searching SYNC for PCM or checking SYNC for bitstream
482     asitErr = asitInputDataProcess(pInp, &autoDetStatus);
483     if(asitErr != ASIT_NO_ERR) {
484         // Even though there is error, still need to start next transfer to
485         // maintain McASP transfer.
486         asitPhyTransferStart(pInp);
488         return asitErr;
489     }
491     // Mark input data read complete
492     ioDataReadComplete(pInp->hIoData);
494     // Check if bitstream or PCM is detected
495     if(   autoDetStatus.syncState == IODATA_SYNC_BITSTREAM
496        || autoDetStatus.syncState == IODATA_SYNC_PCM) {
497         // Decide input source and inform decoder
498         asitErr = asitDecideSource(pAstCfg, pInp, &autoDetStatus);
499         if(asitErr != ASIT_NO_ERR) {
500             return asitErr;
501         }
502         else {
503             // Update I/O components and input buffer config
504             asitUpdateIoComps(pP, pAstCfg, pInp, &autoDetStatus);
506             // set to unknown so that we can ensure, for IOS purposes, that
507             // sourceDecode = NONE iff we are in this top level state machine
508             // and specifically not in decodeProcessing
509 #ifndef DEBUG_SKIP_DECODING
510             pP->fxns->sourceDecode(pP, pQ, pAsitCfg, PAF_SOURCE_UNKNOWN);
511 #endif
513             if(autoDetStatus.syncState == IODATA_SYNC_BITSTREAM) {
514                 // Input is bit stream: go to decoding
515                 pInp->asipState = ASIT_DECODE_PROCESSING;
516             }
517             else  {
518                 // Input is PCM: stop swapping data
519                 pInp->swapData = FALSE;
521                 // Reconfigure McASP LLD to transfer 32-bit unpacked data
522                 mcaspErr = mcaspRecfgWordWidth(pInp->hMcaspChan, Mcasp_WordLength_32);
523                 if(mcaspErr != Audk2g_EOK) {
524                     return ASIT_ERR_MCASP_CFG;
525                 }
527                 // Adjust I/O BUFF delay and read pointer - to make sure read pointers
528                 // always point to PCM data from 1st I2S (out of 4 for HDMI 4xI2S)
529                 ioBuffAdjustDelay(pInp->hIoBuff, pInp->phyXferSize);
531                 // Go to transition state to switch to PCM
532                 pInp->asipState = ASIT_PCM_TRANSITION;
533             }
534         }
535     }
537     // Start next transfer
538     asitPhyTransferStart(pInp);
540     return (ASIT_NO_ERR);
541 }  /* asitSourceDetection */
544 /*===========================================================================
545     //
546     // which will cause all 0's in one McASP LLD transfer. This will
547     // be detected as loss of SYNC by auto detection. To prevent that,
548     // skip I/O DATA process for hangover period so that this all 0's
549     // frame will not be seen by auto-detection. Also, playing out PCM
550     // needs to be skipped as well, to prevent from playing out garbage
551     // (16-bit packed data).
552  *
553  * ASIT Transition to PCM decoding.
554  *     When PCM is detected, McASP LLD will be reconfigured to transmit 32-bit
555  *     words, which will modify the RFMT register. This will cause all 0's in
556  *     one McASP LLD transfer, which would be detected as loss of SYNC by auto
557  *     detection (performed by I/O DATA). To prevent that, skip I/O DATA process
558  *     for hangover period so that this all-0's frame will not be seen by the
559  *     auto-detection.
560  *
561  *     In addition, playing out PCM should be skipped as well to prevent from
562  *     playing out the 16-bit packed data that's still in the input buffer.
563  *
564  *     This function does the following:
565  *     - mark I/O PHY transfer completion
566  *     - bypass I/O DATA
567  *     - start next I/O PHY transfer
568 ============================================================================*/
569 Int asitPcmTransition(PAF_ASIT_Config *pAsitCfg)
571     Int asitErr;
572     PAF_AST_IoInp *pInp;                  // I/O components for input
573     Int zMD;
575     zMD = pAsitCfg->pAstCfg->masterDec;   // pointer to AST common (shared) configuration
576     pInp = &pAsitCfg->pIoInp[zMD];        // pointer to input I/O components
578     // Marks I/O PHY transfer and I/O BUFF write complete
579     asitPhyTransferComplete(pInp);
581     // Bypass I/O data processing due to McASP LLD work around
582     // (refer to comments inside the function)
583     asitErr = asitBypassIoData(pInp);
585     pInp->pcmSwitchHangOver--;
586     if(pInp->pcmSwitchHangOver == 0) {
587         pInp->asipState = ASIT_DECODE_PROCESSING;
588     }
589     else {
590         ; // stay in this state
591     }
593     // Start next transfer
594     asitPhyTransferStart(pInp);
596     return asitErr;
598 } /* asitPcmTransition */
600 /*============================================================================
601  * ASIT Bypass I/O DATA Processing
602  *     This function bypasses the I/O DATA processing. It maintains the read
603  *     operation of I/O BUFF by directly calling I/O BUFF APIs. When I/O DATA
604  *     is not bypassed, I/O BUFF read operation is invoked by I/O DATA.
605  *
606 ============================================================================*/
607 Int asitBypassIoData(PAF_AST_IoInp *pInp)
609     void *buff1, *buff2;
610     size_t size1, size2;
612     // Get read pointers (or sub-buffers) of the input buffer
613     if (ioBuffGetReadPtrs(pInp->hIoBuff, pInp->phyXferSize,
614                           &buff1, &size1, &buff2, &size2)
615         == IOBUFF_ERR_UNDERFLOW) {
616         pInp->numUnderflow += 1;
618         // Return since there is no enough data to process
619         return ASIT_ERR_INPBUF_UNDERFLOW;
620     }
622     ioBuffReadComplete(pInp->hIoBuff, buff1, size1);
624     if(buff2 != NULL) {
625         ioBuffReadComplete(pInp->hIoBuff, buff2, size2);
626     }
628     return ASIT_NO_ERR;
629 } /* asitBypassIoData */
632 /*============================================================================
633  * ASIT Decode Processing
634  *     This function performs the decode processing and does the following based
635  *     on the ASIT events:
636  *     - initialize the decode processing if it is the first time
637  *     - if there is ASIT INPUT DATA event (ASIT_EVTMSK_INPDATA):
638  *        - mark I/O PHY transfer completion
639  *        - run auto-detection via I/O DATA in asitInputDataProcess
640  *        - check auto-detection status and take corresponding actions if SYNC
641  *          is lost.
642  *        - start next I/O PHY transfer
643  *     - map ASIT events to decoding messages
644  *     - invoke decDecodeFsm() and pass the mapped decoding messages
645  *     - if there is ASIT DECODE ACK event (ASIT_EVTMSK_DECACK)
646  *        - mark I/O DATA read completion
647  *     - error handling
648 ============================================================================*/
649 Int asitDecodeProcessing(const PAF_ASIT_Params *pP,
650                          const PAF_ASIT_Patchs *pQ,
651                          PAF_ASIT_Config       *pAsitCfg,
652                          UInt asitEvents)
654     Int asitErr, decErr;
655     PAF_AST_IoInp *pInp;                  // I/O components for input
656     AspMsgMaster_Handle hAspMsgMaster;    // ASIT message master handle
657     asipDecProc_t *pDec;
658     ioDataAutoDetStat_t autoDetStatus;
659     Int zMD;
660     UInt decMsg;
661     Int status;
663     zMD = pAsitCfg->pAstCfg->masterDec;         // pointer to AST common (shared) configuration
664     pInp = &pAsitCfg->pIoInp[zMD];              // pointer to input I/O components
665     hAspMsgMaster = pAsitCfg->hAspMsgMaster;    // get ASIT message master handle
666     pDec = &pAsitCfg->inpDec;
668     // Initialization for decode processing when this function is called the first time
669 #ifndef DEBUG_SKIP_DECODING
670     if(!pDec->initDone) {
671         // Initialize decoder
672         decDecodeInit(pP, pAsitCfg, pInp->sourceSelect);
674         pDec->initDone = TRUE;
675     }
676 #endif
678     // Process input data if this is a data ready message
679     if(asitEvents & ASIT_EVTMSK_INPDATA) {
680         TRACE_TERSE0("asitDecodeProcessing: process input data.");
682         // Marks I/O PHY transfer and I/O BUFF write complete
683         asitPhyTransferComplete(pInp);
685         // Process input data - either search SYNC for PCM or check SYNC for bitstream
686         asitErr = asitInputDataProcess(pInp, &autoDetStatus);
688         if(asitErr == ASIT_NO_ERR) {
689             ioDataReadComplete(pInp->hIoData);
691             // Check if SYNC is maintained or lost (stream stops or format changes)
692             if(autoDetStatus.syncState == IODATA_SYNC_NONE) {
693                 // SYNC lost: change I/O PHY transfer size to default for auto-detection
694                 //asitErr = asitRecfgPhyXfer(pInp, INPUT_FRAME_SIZE_DEF);
695                 //if(asitErr != ASIT_NO_ERR) {
696                 //    return asitErr;
697                 //}
699                 // Inform decoder to complete the decoding of previous frame - is this good?
700                 pInp->sourceSelect = PAF_SOURCE_NONE;
701                 pInp->numFrameReceived = 0;    // for debugging
702                 TRACE_TERSE0("asitDecodeProcessing: SYNC lost.");
704 #ifdef DEBUG_SKIP_DECODING
705                 asitErr = ASIT_ERR_DECODE_QUIT;
706 #endif
707             }
708             else {
709                 pInp->numFrameReceived += 1;    // for debugging
711                 // Communicate input stream information to decoder through input
712                 // buffer configuration
713                 asitUpdateInpBufConfig(pAsitCfg->pAstCfg, pInp);
715                 // Start next transfer
716                 asitPhyTransferStart(pInp);
717             }
719             // Start next transfer
720             //asitPhyTransferStart(pInp);
722 #ifdef DEBUG_SKIP_DECODING
723             return asitErr;
724 #endif
725         }
726         else if(asitErr == ASIT_ERR_INPBUF_UNDERFLOW) {
727             TRACE_TERSE0("asitDecodeProcessing: Input buffer underflows.");
729             // When input buffer underflows, it is not an error but decoding needs
730             // to be skipped as there is not enough data in the buffer.
731             asitPhyTransferStart(pInp);
733             return asitErr;
734         }
735         else {
736             // Inform decoder to complete the decoding of previous frame - is this good?
737             pInp->sourceSelect = PAF_SOURCE_NONE;
738             pInp->numFrameReceived = 0;    // for debugging
739             TRACE_TERSE1("asitDecodeProcessing: asitInputDataProcess error: %d", asitErr);
741 #ifdef DEBUG_SKIP_DECODING
742             return ASIT_ERR_DECODE_QUIT;
743 #endif
744         }
745     } /* ASIT_EVTMSK_INPDATA */
746 #ifdef DEBUG_SKIP_DECODING
747     else {
748         TRACE_TERSE0("asitDecodeProcessing: events error.");
749         return ASIT_ERR_EVENTS;
750     }
751 #endif
753 #ifndef DEBUG_SKIP_DECODING
754     // Map ASIT events to decode messages
755     decMsg = asitEventsToDecMsg(asitEvents);
757     // Pass messages (corresponding to events) to decode FSM
758     decErr = decDecodeFsm(pP, pQ, pAsitCfg, pInp->sourceSelect, decMsg);
760     // Mark I/O DATA read complete if decoder indicates decoding is done.
761     if((asitEvents & ASIT_EVTMSK_DECACK)) {  // DECACK -> decoding done
762         //ioDataReadComplete(pInp->hIoData);
763     }
765     if(decErr != DEC_NO_ERR) {
766         TRACE_VERBOSE0("TaskAsip: send DEC_EXIT message to slave decoder.");
768         // Send dec exit message to slave decoder
769         status = AspMsgSnd(hAspMsgMaster, ASP_SLAVE_DEC_EXIT, NULL);
770         if (status != ASP_MSG_NO_ERR)
771         {
772             TRACE_VERBOSE0("TaskAsip: error in sending DEC_EXIT message");
773             SW_BREAKPOINT;
774         }
775         status = AspMsgRcvAck(hAspMsgMaster, ASP_MASTER_DEC_EXIT_DONE, NULL, TRUE);
776         if (status != ASP_MSG_NO_ERR) 
777         {
778             TRACE_VERBOSE0("TaskAsip: error in sending DEC_EXIT message");
779             SW_BREAKPOINT;
780         }
782         return ASIT_ERR_DECODE_QUIT;  // This is not necessarily an error
783     }
784     else {
785         return ASIT_NO_ERR;
786     }
787 #endif
788 }  /* asitDecodeProcessing */
791 /*============================================================================
792  * ASIT Input Data Processing:
793  *    - invoke ioDataProcess() to inspect input data for
794  *       - initial auto-detection,  or
795  *       - background scanning for PCM data, or
796  *       - SYNC check for bitstream
797  *    - return auto-detection status (SYNC detected, SYNC loss, etc)
798 ============================================================================*/
799 Int asitInputDataProcess(PAF_AST_IoInp *pInp, ioDataAutoDetStat_t *pAutoDetStats)
801     Int ioDataErr, retVal;
802     ioDataCtl_t ioDataCtl;
804     // Perform auto-detection inside I/O DATA component
805     ioDataErr = ioDataProcess(pInp->hIoData);
807     if(ioDataErr == IODATA_NO_ERR) {
808         // Normal operation - check auto-detection status
809         ioDataCtl.code = IODATA_CTL_GET_AUTODET_STATUS;
810         ioDataControl(pInp->hIoData, &ioDataCtl);
812         *pAutoDetStats = ioDataCtl.param.autoDetStats;
814         retVal = ASIT_NO_ERR;
815     }
816     else if(ioDataErr == IODATA_ERR_IOBUF_UNDERFLOW) {
817         // Input buffer underflows - there is no enough data to process.
818         // This is not error and no action is needed.
819         pInp->numUnderflow += 1; // debug
821         retVal = ASIT_ERR_INPBUF_UNDERFLOW;
822     }
823     else {
824         // Something is wrong: print error log and return
825         //printf("IODATA processing error!\n");
826         retVal = ASIT_ERR_INPDATA_PROC;
827     }
829     return retVal;
830 } /* asitInputDataProcess */
832 /*============================================================================
833  * Mapping ASIT Events to Decoding Messages
834 ============================================================================*/
835 UInt asitEventsToDecMsg(UInt asitEvents)
837     UInt decMsg = 0;
839     if (asitEvents & ASIT_EVTMSK_INPDATA) {
840         // Input data event
841         decMsg |= DEC_MSGMSK_INPDATA;
842     }
844     // temp, simulation
845     //if(asitEvents & ASIT_EVTMSK_INFOACK) {
846     //    decMsg |= DEC_MSGMSK_INFOACK;
847     //}
849     // temp, simulation
850     //if(asitEvents & ASIT_EVTMSK_DECACK) {
851     //    decMsg |= DEC_MSGMSK_DECACK;
852     //}
854     if (asitEvents & ASIT_EVTMSK_RXACK)
855     {
856        // Receive acknowledge message event
857         decMsg |= DEC_MSGMSK_RXACK;
858     }
859     
860     return decMsg;
861 } /* asitEventsToDecMsg */
863 /*===========================================================================
864  * Initialize I/O components for input processing
865 ============================================================================*/
866 int asitIoCompsInit(PAF_AST_InpBuf * pInpBuf, PAF_AST_IoInp * pInpIo)
868     ioBuffParams_t ioBuffParams;
869     ioPhyParams_t  ioPhyParams;
870     ioDataParam_t  ioDataCfg;
871     ioPhyCtl_t     ioPhyCtl;
873     //pInpIo->phyXferSize = INPUT_FRAME_SIZE_DEF;
874     pInpIo->phyXferSize = pInpIo->stride * NUM_CYCLE_PER_FRAME_DEF * WORD_SIZE_BITSTREAM;
876     if(pInpIo->firstTimeInit) {
877         TRACE_VERBOSE0("Initialize I/O BUFF and I/O PHY.");
878         ioBuffParams.base         = pInpBuf->inpBufConfig.base.pVoid;
879         ioBuffParams.size         = pInpBuf->inpBufConfig.allocation / STRIDE_WORST_CASE
880                                                                      * STRIDE_WORST_CASE;
881         ioBuffParams.sync         = IOBUFF_WRITE_SYNC;
882         ioBuffParams.nominalDelay = INPUT_FRAME_SIZE_DEF;
883         if(ioBuffInit(pInpIo->hIoBuff, &ioBuffParams) != IOBUFF_NOERR) {
884             return (ASIT_ERR_IOBUFF_INIT);   // to remove magic number
885         }
887         ioPhyParams.ioBuffHandle    = pInpIo->hIoBuff;
888         ioPhyParams.xferFrameSize   = pInpIo->phyXferSize;
889         ioPhyParams.mcaspChanHandle = pInpIo->hMcaspChan;
890         ioPhyParams.ioBuffOp        = IOPHY_IOBUFFOP_WRITE;
891         if(ioPhyInit(pInpIo->hIoPhy, &ioPhyParams) != IOPHY_NOERR) {
892             return (ASIT_ERR_IOPYH_INIT);   // to remove magic number
893         }
895         pInpIo->numPrimeXfers = NUM_PRIME_XFERS;
896     }
898     /* Reinitialize I/O DATA every time when ASIT restarts */
899     TRACE_VERBOSE0("Initialize I/O DATA.");
900     ioDataCfg.ioBuffHandle         = pInpIo->hIoBuff;
901     ioDataCfg.unknownSourceTimeOut = pInpBuf->inpBufConfig.pBufStatus->unknownTimeout;
902     ioDataCfg.frameLengthsIEC      = (uint_least16_t *)&iecFrameLength[0];
903     ioDataCfg.frameLengthPCM       = pInpIo->stride * NUM_CYCLE_PER_FRAME_DEF;
904     ioDataCfg.frameLengthDef       = pInpIo->stride * NUM_CYCLE_PER_FRAME_DEF;
905     ioDataCfg.ibMode               = pInpBuf->inpBufConfig.pBufStatus->mode;
906     ioDataCfg.zeroRunRestart       = pInpBuf->inpBufConfig.pBufStatus->zeroRunRestart;
907     ioDataCfg.zeroRunTrigger       = pInpBuf->inpBufConfig.pBufStatus->zeroRunTrigger;
909     if(ioDataInit(pInpIo->hIoData, &ioDataCfg) != IODATA_NO_ERR) {
910         return (ASIT_ERR_IODATA_INIT);   // to remove magic number
911     }
913     if(pInpIo->firstTimeInit) {
914         /* Initialize I/O BUFF and I/O PHY only when input interface changes. */
915         TRACE_VERBOSE0("Prime I/O PHY.");
917         // Start I/O physical layer by priming McASP LLD for input
918         asitIoPhyPrime(pInpIo);
920         pInpIo->firstTimeInit = FALSE;
921     }
922     else {
923         // Reconfigure I/O PHY transfer size
924         ioPhyCtl.code = IOPHY_CTL_FRAME_SIZE;
925         ioPhyCtl.params.xferFrameSize = pInpIo->phyXferSize;
926         ioPhyControl(pInpIo->hIoPhy, &ioPhyCtl);
927 #if 0
928         // If previous stream before reset was PCM, reconfigure McASP LLD to receive 16-bit packed bits
929         if(!pInpIo->swapData) {
930             Int mcaspErr;
931             mcaspErr = mcaspRecfgWordWidth(pInpIo->hMcaspChan, Mcasp_WordLength_16);
932             if(mcaspErr != Audk2g_EOK) {
933                 return ASIT_ERR_MCASP_CFG;
934             }
936             // Start swapping data
937             pInpIo->swapData = TRUE;
938             TRACE_VERBOSE0("Reconfigure McASP word length and start swapping data.");
939         }
940 #endif
941         // Start PHY transfer
942         TRACE_VERBOSE0("Start I/O PHY transfer.");
943         asitPhyTransferStart(pInpIo);
944     }
946     return 0;
947 } /* asitIoCompsInit */
949 /*======================================================================================
950  *  This function initializes ASIT processing
951  *====================================================================================*/
952 void asitProcInit(PAF_AST_IoInp  *pInp, asipDecProc_t *pDec)
954 //    pInp->swapData = TRUE;
955     pInp->pcmSwitchHangOver = INPUT_SWITCH_HANGOVER;
956     pDec->initDone = FALSE;
957     pInp->numFrameReceived = 0;
960 /*======================================================================================
961  *  I/O physical layer prime operation required by McASP LLD
962  *====================================================================================*/
963 void asitIoPhyPrime(PAF_AST_IoInp *pInp)
965     Int32        count;
967     for(count = 0; count < pInp->numPrimeXfers; count++)
968     {
969         ioPhyXferSubmit(pInp->hIoPhy);
970 #ifdef ASIP_DEBUG
971         //pInp->numXferStart++;
972 #endif
973     }
974 } /* asitIoPhyPrime */
977 /*======================================================================================
978  *  This function marks the I/O PHY transfer as complete
979  *====================================================================================*/
980 void asitPhyTransferComplete(PAF_AST_IoInp * pInpIo)
982     // Mark underlining I/O BUFF write complete and swap data if needed
983     ioPhyXferComplete(pInpIo->hIoPhy, pInpIo->swapData);
984 } /* asitPhyTransferComplete */
986 #if 0
987 Int asitRecfgPhyXfer(PAF_AST_IoInp *pInp, size_t xferSize)
989     ioPhyCtl_t ioPhyCtl;
990     Int mcaspErr;
992     ioPhyCtl.code = IOPHY_CTL_FRAME_SIZE;
993     ioPhyCtl.params.xferFrameSize = xferSize;
994     ioPhyControl(pInp->hIoPhy, &ioPhyCtl);
996     pInp->phyXferSize  = ioPhyCtl.params.xferFrameSize;
998     if(!pInp->swapData) {
999         // If it was PCM, reconfigure McASP LLD to receive 16-bit packed bits
1000         mcaspErr = mcaspRecfgWordWidth(pInp->hMcaspChan, Mcasp_WordLength_16);
1001         if(mcaspErr != Audk2g_EOK) {
1002             return ASIT_ERR_MCASP_CFG;
1003         }
1005         // Start swapping data
1006         pInp->swapData = TRUE;
1007     }
1009     return ASIT_NO_ERR;
1011 } /* asitRecfgPhyXfer */
1012 #endif
1014 /*======================================================================================
1015  *  McASP LLD call back function
1016  *====================================================================================*/
1017 void asipMcaspCallback(void* arg, MCASP_Packet *mcasp_packet)
1019     /* post semaphore */
1020     if(mcasp_packet->arg == IOPHY_XFER_FINAL) {
1021         //Semaphore_post(asipSemRx);
1022         Event_post(gAsitEvtHandle, ASIT_EVTMSK_INPDATA);
1023     } else {
1024         ;    // intermediate packet due to buffer wrapping around
1025     }
1028 /*======================================================================================
1029  *  This function checks if McASP Rx for input overruns
1030  *====================================================================================*/
1031 int asipCheckMcaspRxOverrun(Ptr mcaspChanHandle)
1033     Mcasp_errCbStatus mcaspErrStat;
1035     mcaspControlChan(mcaspChanHandle, Mcasp_IOCTL_CHAN_QUERY_ERROR_STATS, &mcaspErrStat);
1037     return (mcaspErrStat.isRcvOvrRunOrTxUndRunErr);
1040 #if 0
1041 /*======================================================================================
1042  *  This function restarts McASP LLD channel for input
1043  *====================================================================================*/
1044 void asipMcaspRxRestart(PAF_AST_IoInp *pInpIo)
1046     mcaspRxReset();
1047     mcaspRxCreate();
1049 #endif
1051 /*======================================================================================
1052  *  This function starts an I/O PHY transfer
1053  *====================================================================================*/
1054 void asitPhyTransferStart(PAF_AST_IoInp *pInpIo)
1056     Int ioPhyErr;
1058     if(asipCheckMcaspRxOverrun(pInpIo->hMcaspChan)) {
1059 #ifdef ASIP_DEBUG
1060         pInpIo->numInputOverrun++;
1061 #endif
1062         //asipMcaspRxRestart(pInpIo);
1063         System_abort("\nMcASP for input overruns! %d!\n");
1064     }
1065     else {
1066         ioPhyErr = ioPhyXferSubmit(pInpIo->hIoPhy);
1067         //if(ioPhyXferSubmit(pInpIo->hIoPhy)==IOPHY_ERR_BUFF_OVERFLOW) {
1068         if(ioPhyErr!=IOPHY_NOERR){
1069             printf("\n I/O PHY ioPhyXferSubmit fails with error %d!\n", ioPhyErr);
1070             // Input buffer overflows!
1071             //printf("\nInput buffer overflows!\n");
1072             exit(0);
1073         }
1074         else {
1075             // Input buffer operates normally
1076             ;
1077         }
1078 #ifdef ASIP_DEBUG
1079         //pInpIo->numXferStart++;
1080 #endif
1081     }
1084 Int d10Initialized = 0;
1085 //extern Audk2g_STATUS mcaspAudioConfig(void);
1086 extern void McaspDevice_init(void);
1088 /*======================================================================================
1089  *  This function initializes HW interface and selects the right device for input
1090  *====================================================================================*/
1091 Int asitSelectDevices(const PAF_ASIT_Patchs *pQ, PAF_AST_Config *pAstCfg, PAF_AST_IoInp *pInp)
1093     Audk2g_STATUS status;
1094     mcaspLLDconfig *lldCfg;
1095     Ptr mcaspChanHandle;
1096     Int zMD, interface;
1098     zMD = pAstCfg->masterDec;
1100     interface = pAstCfg->xInp[zMD].inpBufStatus.sioSelect; // obtain SIO select for input
1102     if (interface <= 0) {
1103         pInp->pRxParams = NULL;
1105         return ASIT_NO_ERR;
1106     }
1108     // Initialize D10
1109     if(!d10Initialized) {
1110         void * pD10Params = (void *)pQ->devinp->x[interface];
1112         /* Initialize McASP HW details */
1113         McaspDevice_init();
1115         D10_init(pD10Params);
1117         d10Initialized = 1;
1118     }
1120     /* Get the McASP LLD channel for this interface. Create one if not yet created. */
1121     lldCfg = (mcaspLLDconfig *)pQ->devinp->x[interface]->sio.pConfig;
1122     if(lldCfg->hMcaspChan == NULL) {
1123         mcaspChanHandle = NULL;
1124         status = mcasplldChanCreate(lldCfg, &mcaspChanHandle);
1125         if(status != Audk2g_EOK) {
1126             Log_info0("McASP channel creation failed!\n");
1127             return ASIT_ERR_MCASP_CFG;
1128         }
1130         lldCfg->hMcaspChan = mcaspChanHandle;
1131     }
1132     else {
1133         /* Configure McASP to receive 16/32-bit data according to default configuration */
1134         status = mcaspRecfgWordWidth(pInp->hMcaspChan, lldCfg->mcaspChanParams->wordWidth);
1135         if(status != Audk2g_EOK) {
1136             return ASIT_ERR_MCASP_CFG;
1137         }
1138     }
1140     pInp->pRxParams = pQ->devinp->x[interface];
1141     pInp->hMcaspChan = lldCfg->hMcaspChan;
1142     pInp->stride     = lldCfg->mcaspChanParams->noOfSerRequested * lldCfg->mcaspChanParams->noOfChannels;
1144     /* Set flag to swap HDMI data if it is 4xI2S and word length is 16 */
1145     if(   (lldCfg->mcaspChanParams->wordWidth == Mcasp_WordLength_16)
1146         &&(lldCfg->mcaspChanParams->noOfSerRequested == 4)
1147       ) {
1148         pInp->swapData = TRUE;
1149     }
1150     else {
1151         pInp->swapData = FALSE;
1152     }
1154     return ASIT_NO_ERR;
1155 }  /* asitSelectDevices */
1157 /*======================================================================================
1158  *  This function updates input status
1159  *====================================================================================*/
1160 Int asitUpdateInputStatus(const void *pRxParams, PAF_InpBufStatus *pStatus,
1161                           PAF_InpBufConfig *pInpBuf)
1163     Int asipErrno;
1165     PAF_SIO_InputStatus inputStatus;
1167     // initialize all values to unknown so that device specific
1168     //   driver layer need only fill in those entries that it is aware of.
1169     //   This allows extensibility of the structure without requiring users
1170     //   to re-code.
1171     inputStatus.lock = 0;
1172     inputStatus.sampleRateData = PAF_SAMPLERATE_UNKNOWN;
1173     inputStatus.sampleRateMeasured = PAF_SAMPLERATE_UNKNOWN;
1174     inputStatus.nonaudio = PAF_IEC_AUDIOMODE_UNKNOWN;
1175     inputStatus.emphasis = PAF_IEC_PREEMPHASIS_UNKNOWN;
1177     //more configuration is needed to abstract out D10
1178     asipErrno = D10_RxControl(pRxParams,
1179                           (Uns)PAF_SIO_CONTROL_GET_INPUT_STATUS,
1180                           (Arg) &inputStatus);
1181     if (asipErrno) {
1182         return asipErrno;
1183     }
1184     pStatus->sampleRateData = inputStatus.sampleRateData;
1185     pStatus->sampleRateMeasured = inputStatus.sampleRateMeasured;
1186     pStatus->nonaudio = inputStatus.nonaudio;
1187     pStatus->emphasisData = inputStatus.emphasis;
1189     // if MSB of override clear then use as reported lock
1190     // if = 0x80 then use default [0x81]
1191     // if = 0x81 then use measured (from device)
1192     // others not defined or implemented
1193     if ((pStatus->lockOverride & (XDAS_Int8)0x80) == 0)
1194         pStatus->lock = pStatus->lockOverride;
1195     else if (pStatus->lockOverride == (XDAS_Int8)0x80)
1196         pStatus->lock = inputStatus.lock;
1197     else if (pStatus->lockOverride == (XDAS_Int8)0x81)
1198         pStatus->lock = inputStatus.lock;
1200     // if MSB of override clear then use it as sample rate for system,
1201     // if = 0x80 then use default [0x82]
1202     // if = 0x81 then use data
1203     // if = 0x82 then use measured
1204     // others not defined or implemented
1205     if ((pStatus->sampleRateOverride & (XDAS_Int8)0x80) == 0)
1206         pStatus->sampleRateStatus = pStatus->sampleRateOverride;
1207     else if (pStatus->sampleRateOverride == (XDAS_Int8)0x80)
1208         pStatus->sampleRateStatus = pStatus->sampleRateMeasured;
1209     else if (pStatus->sampleRateOverride == (XDAS_Int8)0x81)
1210         pStatus->sampleRateStatus = pStatus->sampleRateData;
1211     else if (pStatus->sampleRateOverride == (XDAS_Int8)0x82)
1212         pStatus->sampleRateStatus = pStatus->sampleRateMeasured;
1214     // Update emphasis status:
1215     if ((pStatus->emphasisOverride & (XDAS_Int8)0x80) == 0) {
1216         if (pStatus->emphasisData == PAF_IEC_PREEMPHASIS_YES)
1217             pStatus->emphasisStatus = PAF_IEC_PREEMPHASIS_YES;
1218         else
1219             pStatus->emphasisStatus = PAF_IEC_PREEMPHASIS_NO;
1220     }
1221     else if (pStatus->emphasisOverride ==
1222              (XDAS_Int8 )(0x80+PAF_IEC_PREEMPHASIS_YES))
1223         pStatus->emphasisStatus = PAF_IEC_PREEMPHASIS_YES;
1224     else /* IBEmphasisOverrideNo or other */
1225         pStatus->emphasisStatus = PAF_IEC_PREEMPHASIS_NO;
1227     // Update precision control
1228     pInpBuf->precision = pStatus->precisionInput =
1229         pStatus->precisionOverride < 0
1230         ? pStatus->precisionDefault
1231         : pStatus->precisionOverride > 0
1232         ? pStatus->precisionOverride
1233         : pStatus->precisionDetect > 0
1234         ? pStatus->precisionDetect
1235         : pStatus->precisionDefault;
1237     return 0;
1241 /*==============================================================================
1242  * This function updates input buffer config based on frame information provided
1243  * by I/O DATA.
1244  ==============================================================================*/
1245 void asitUpdateInpBufConfig(PAF_AST_Config *pAstCfg, PAF_AST_IoInp  *pInp)
1247     PAF_InpBufConfig *pBufConfig;
1248     ioDataCtl_t ioDataCtl;
1250     /* Get information for reading input data */
1251     ioDataCtl.code = IODATA_CTL_GET_INPBUFFINFO;
1252     ioDataControl(pInp->hIoData, &ioDataCtl);
1254     if(ioDataCtl.param.dataReadInfo.frameSize != pInp->phyXferSize) {
1255         // Fatal error!
1256         TRACE_VERBOSE0("TaskAsip: error in updating I/O");
1257         SW_BREAKPOINT;
1258     }
1260     pBufConfig = &(pAstCfg->xInp[pAstCfg->masterDec].inpBufConfig);
1262     //JXTODO: do we need to gate here?
1263     //key = GateMP_enter(gateHandle);
1265     pBufConfig->base.pVoid   = ioDataCtl.param.dataReadInfo.buffBase;
1266     pBufConfig->sizeofBuffer = ioDataCtl.param.dataReadInfo.buffSize;
1267     pBufConfig->pntr.pSmInt  = ioDataCtl.param.dataReadInfo.startAddress;
1269     // Leave the gate
1270     //GateMP_leave(gateHandle, key);
1272     TRACE_TERSE2("Frame start address: 0x%x., preamble: 0x%x",
1273                  (UInt)ioDataCtl.param.dataReadInfo.startAddress,
1274                  *(UInt *)ioDataCtl.param.dataReadInfo.startAddress);
1277 /*==============================================================================
1278  * Decide source after SYNC is found, i.e. either bitstream preamble is detected
1279  * or it times out to PCM.
1280  ==============================================================================*/
1281 Int asitDecideSource(PAF_AST_Config *pAstCfg, PAF_AST_IoInp  *pInp, 
1282                      ioDataAutoDetStat_t *autoDetStatus)
1284     Int sourceConfig, sourceSelect, sourceProgram;
1285     Int zMD;
1286     char asipMsgBuf[ASP_MSG_BUF_LEN];
1287     Int status;
1289     // Get the configured source
1290     zMD = pAstCfg->masterDec;
1291     sourceConfig = (Int)sharedMemReadInt8(&(pAstCfg->xDec[zMD].decodeStatus.sourceSelect),
1292                                           GATEMP_INDEX_DEC);
1294     if(autoDetStatus->syncState == IODATA_SYNC_PCM) {
1295         if (sourceConfig == PAF_SOURCE_DSD1 || sourceConfig == PAF_SOURCE_DSD2 ||
1296             sourceConfig == PAF_SOURCE_DSD3) {
1297             sourceProgram = sourceConfig;
1298         }
1299         else {
1300             sourceProgram = PAF_SOURCE_PCM;
1301         }
1302     }
1304     if(autoDetStatus->syncState == IODATA_SYNC_BITSTREAM) {
1305         uint_least16_t pc = autoDetStatus->bitStreamInfo & SYNC_PC_MASK; //0x001F
1306         sourceProgram = IECpafSource[pc];
1307     }
1309     // write the decided source program to memory
1310     sharedMemWriteInt8(&(pAstCfg->xDec[zMD].decodeStatus.sourceProgram), sourceProgram,
1311                        GATEMP_INDEX_DEC);
1313     // now that we have some input classification, and possibly an outstanding
1314     // input frame, we determine whether or not to call decodeProcessing and with
1315     // what decAlg.
1316     sourceSelect = PAF_SOURCE_NONE;
1318     switch (sourceConfig)
1319     {
1320         // If autodetecting, decoding everything, and input is something
1321         // (i.e. bitstream or PCM) then decode.
1322         case PAF_SOURCE_AUTO:
1323             if (sourceProgram >= PAF_SOURCE_PCM)  {
1324                 sourceSelect = sourceProgram; // use whatever from autodet
1325             }
1326             break;
1328         // If autodetecting, decoding only PCM, and input is PCM then decode.
1329         case PAF_SOURCE_PCMAUTO:
1330             if (sourceProgram == PAF_SOURCE_PCM) {
1331                 // only expect autodet to give PAF_SOURCE_PCM, otherwise set to NONE
1332                 sourceSelect = sourceProgram;
1333             }
1334             break;
1336         // If autodetecting, decoding only bitstreams, and input is a bitstream then decode.
1337         case PAF_SOURCE_BITSTREAM:
1338             if (sourceProgram >= PAF_SOURCE_AC3) {
1339                 sourceSelect = sourceProgram;
1340             }
1341             break;
1343         // If autodetecting, decoding only DTS, and input is DTS then decode.
1344         case PAF_SOURCE_DTSALL:
1345             switch (sourceProgram)
1346             {
1347                 case PAF_SOURCE_DTS11:
1348                 case PAF_SOURCE_DTS12:
1349                 case PAF_SOURCE_DTS13:
1350                 case PAF_SOURCE_DTS14:
1351                 case PAF_SOURCE_DTS16:
1352                 case PAF_SOURCE_DTSHD:
1353                     sourceSelect = sourceProgram;
1354                     break;
1355             }
1356             break;
1358         // All others, e.g., force modes, fall through to here.
1359         // If user made specific selection then program must match select.
1360         // (NB: this compare relies on ordering of PAF_SOURCE)
1361         default:
1362             sourceSelect = sourceConfig;
1363             if ((sourceSelect >= PAF_SOURCE_PCM) && (sourceSelect <= PAF_SOURCE_N)) {
1364                 if (sourceProgram != sourceSelect) {
1365                     sourceSelect = PAF_SOURCE_NONE;
1366                 }
1367             }
1368             break;
1369     }
1371     // if we didn't find any matches then skip
1372     if (sourceSelect == PAF_SOURCE_NONE) {
1373         TRACE_VERBOSE0("TaskAsip: no matching source type, continue");
1374         return ASIT_ERR_NO_MATCHING_SOURCE;
1375     }
1377 #ifndef DEBUG_SKIP_DECODING
1378     // send source select message to slave
1379     *(Int32 *)&asipMsgBuf[0] = sourceSelect;
1380     status = AspMsgSnd(gPAF_ASIT_config.hAspMsgMaster, ASP_SLAVE_DEC_SOURCE_SELECT, asipMsgBuf);
1381     if (status != ASP_MSG_NO_ERR) 
1382     {
1383         TRACE_VERBOSE0("TaskAsip: error in sending SOURCE_SELECT message");
1384         SW_BREAKPOINT;
1385     }
1386     status = AspMsgRcvAck(gPAF_ASIT_config.hAspMsgMaster, ASP_MASTER_DEC_SOURCE_SELECT_DONE, NULL, TRUE);
1387     if (status != ASP_MSG_NO_ERR)
1388     {
1389         TRACE_VERBOSE0("TaskAsip: error in receiving SOURCE_SELECT ack message");
1390         SW_BREAKPOINT;
1391     }
1392 #endif
1394     pInp->sourceSelect  = sourceSelect;
1395     pInp->sourceProgram = sourceProgram;
1397     return ASIT_NO_ERR;
1398 } /* asitDecideSource */
1400 /*==============================================================================
1401  * After SYNC is found, i.e. either bitstream preamble is detected or it times
1402  * out to PCM, update input buffer config and I/o components accordingly.
1403  ==============================================================================*/
1404 Int asitUpdateIoComps(const PAF_ASIT_Params *pP, PAF_AST_Config *pAstCfg,
1405                       PAF_AST_IoInp  *pInp, ioDataAutoDetStat_t *autoDetStatus)
1407     Int sourceConfig;
1408     Int zMD, deliverZeros;
1409     int ioFrameLength, decFrameLength;
1410     PAF_InpBufConfig *pBufConfig;
1411     ioPhyCtl_t  ioPhyCtl;
1412     ioDataCtl_t ioDataCtl;
1414     zMD = pAstCfg->masterDec;
1415     pBufConfig = &pAstCfg->xInp[zMD].inpBufConfig;
1417     // Compute decoder frame length based on source selection
1418     decFrameLength = getFrameLengthSourceSel(pP, pInp->sourceSelect);
1420     pAstCfg->xDec[zMD].decodeControl.frameLength  = decFrameLength;
1421     pAstCfg->xDec[zMD].decodeInStruct.sampleCount = decFrameLength;
1422     pAstCfg->xDec[zMD].decodeControl.sampleRate   = PAF_SAMPLERATE_UNKNOWN;
1424     // Decide frame length for I/O DATA and I/O PHY
1425     if(autoDetStatus->syncState == IODATA_SYNC_PCM) {
1426         // For PCM, I/O frame length is decode frame length multiplied by stride
1427         ioFrameLength = decFrameLength * pInp->stride;
1429         pBufConfig->sizeofElement = WORD_SIZE_PCM;
1430         pBufConfig->frameLength   = pBufConfig->lengthofData = ioFrameLength;
1432         // Configure I/O DATA PCM frame length
1433         ioDataCtl.code = IODATA_CTL_SET_PCM_FRAME_LENGTH;
1434         ioDataCtl.param.frameLengthPcm = ioFrameLength;
1435         ioDataControl(pInp->hIoData, &ioDataCtl);
1437         // Change I/O PHY transfer size to PCM frame size
1438         pInp->phyXferSize = ioFrameLength*(WORD_SIZE_PCM);
1440         // Adjust I/O BUFF delay and read pointer - to make sure read pointers always point to
1441         // PCM data from 1st I2S (out of 4 for HDMI 4xI2S)
1442         // Adjust delay and don't mark input buffer as read complete
1443         //ioBuffAdjustDelay(pInp->hIoBuff, pInp->phyXferSize);
1445         // Stop swapping data
1446         //pInp->swapData = FALSE;
1447     }
1448     else {
1449         // For bitstream, I/O frame length is the frame length of the bitstream
1450         uint_least16_t pc = autoDetStatus->bitStreamInfo & SYNC_PC_MASK; //0x001F
1451         ioFrameLength = iecFrameLength[pc];
1453 /*
1454         if(   (pc == 0x11) && (DTSHDSubType == 3)
1455            && (PAF_ASP_sampleRateHzTable[pBufConfig->pBufStatus->sampleRateStatus][PAF_SAMPLERATEHZ_STD] <=48000.0))
1456             pDevExt->sourceProgram = PAF_SOURCE_DXP;    // LBR is 23
1458         if (pc == 1)
1459             pDevExt->elementSize = 4288;
1460         else if (pc == 0x11) {
1461             pDevExt->frameLength = (pDevExt->pIECFrameLength[pc] << DTSHDSubType);
1462             pDevExt->lengthofData = pDevExt->frameLength;
1463         }
1464 */
1466         pBufConfig->sizeofElement = WORD_SIZE_BITSTREAM;
1467         pBufConfig->frameLength   = ioFrameLength;
1468         pBufConfig->lengthofData  = ioFrameLength - IEC_HEADER_LENGTH;
1470         // Change I/O PHY transfer size to bitstream frame size
1471         pInp->phyXferSize = ioFrameLength*WORD_SIZE_BITSTREAM;
1472     }
1474     pBufConfig->stride = pInp->stride;   // common for PCM and bitstream
1476     // Configure I/O PHY transfer size
1477     ioPhyCtl.code = IOPHY_CTL_FRAME_SIZE;
1478     ioPhyCtl.params.xferFrameSize = pInp->phyXferSize;
1479     ioPhyControl(pInp->hIoPhy, &ioPhyCtl);
1481     // Decide if zeros should be delivered based on the configured source
1482     sourceConfig = (Int)sharedMemReadInt8(&(pAstCfg->xDec[zMD].decodeStatus.sourceSelect),
1483                                           GATEMP_INDEX_DEC);
1485     if(autoDetStatus->syncState == IODATA_SYNC_PCM) {
1486         // Bitstream preamble is not found and it times out -> assume this is PCM
1487         deliverZeros = autoDetStatus->deliverZeros;
1488         if (sourceConfig == PAF_SOURCE_PCM || sourceConfig == PAF_SOURCE_DSD1 ||
1489             sourceConfig == PAF_SOURCE_DSD2 || sourceConfig == PAF_SOURCE_DSD3) {
1490             // set to one -- ensures that PCM decode calls made before data is
1491             // available will result in zero output.
1492             // (mostly needed for PA15 since, currently, all other frameworks
1493             // require a frame of data before the first decode call.
1494             deliverZeros = TRUE;  // override deliverZeros returned by ioDataControl
1495         }
1497         // update input buffer config structure
1498         pBufConfig->deliverZeros  = deliverZeros;
1499     }
1501     //JXTODO: decide what to do with hRxSio
1502     //temporary - does ARM use hRxSio or just check if it is not NULL?
1503     pAstCfg->xInp[zMD].hRxSio = pInp->hIoData;
1504     pAstCfg->xInp[zMD].pInpBuf = &(pAstCfg->xInp[zMD].inpBufConfig);
1506     return ASIT_NO_ERR;
1507 } /* asitUpdateIoComps */
1509 #if 0
1510 #ifndef IO_LOOPBACK_TEST
1511 #if OUTPUT_FRAME_LENGTH == INPUT_FRAME_LENGTH
1512 U8 pcmbuf[OUTPUT_FRAME_SIZE];
1513 #else
1514 #error Input frame length is not equal to output frame length!
1515 #endif
1517 Int rxDecodePcm(PAF_AST_IoInp  *pInp)
1519     ioDataCtl_t ioDataCtl;
1520     void *buffBase;
1521     void *dataStartAddress;
1522     size_t buffSize, frameSize, size1, size2;
1524     /* Get information for reading input data */
1525     ioDataCtl.code = IODATA_CTL_GET_INPBUFFINFO;
1526     ioDataControl(pInp->hIoData, &ioDataCtl);
1528     buffBase = ioDataCtl.param.dataReadInfo.buffBase;
1529     buffSize = ioDataCtl.param.dataReadInfo.buffSize;
1530     dataStartAddress = ioDataCtl.param.dataReadInfo.startAddress;
1531     frameSize        = ioDataCtl.param.dataReadInfo.frameSize;
1533     // Copy PCM data to output buffer
1534     if(((size_t)dataStartAddress+frameSize) <= ((size_t)buffBase+buffSize)) {
1535         // Input buffer doesn't wrap around
1536         Cache_inv(dataStartAddress, frameSize, Cache_Type_ALL, TRUE);
1537         memcpy((void *)&pcmbuf[0], dataStartAddress, frameSize);
1538     }
1539     else {
1540         // Input buffer wraps around
1541         size1 = (size_t)buffBase + buffSize - (size_t)dataStartAddress;
1542         size2 = frameSize - size1;
1543         Cache_inv(dataStartAddress, size1, Cache_Type_ALL, TRUE);
1544         memcpy((void *)&pcmbuf[0], dataStartAddress, size1);
1546         Cache_inv(buffBase, size2, Cache_Type_ALL, TRUE);
1547         memcpy((void *)&pcmbuf[size1], buffBase, size2);
1548     }
1551     return ASIT_NO_ERR;
1555 Int rxDecodePlayZero(PAF_AST_IoInp  *pInp)
1557     return ASIT_NO_ERR;
1559 #endif
1561 #endif
1563 Int asitEvtErrCheck(UInt actualEvents, UInt expectedEvents)
1565     TRACE_VERBOSE2("ASIT events error: actual events are: %d, expected events are: %d.",
1566                    actualEvents, expectedEvents);
1568     return ASIT_ERR_EVENTS;
1571 void asitErrorHandling(PAF_ASIT_Config *pAsitCfg, Int asitErr)
1573     //UInt events;
1575     if(asitErr == ASIT_ERR_INPBUF_UNDERFLOW) {
1576         TRACE_VERBOSE0("ASIT error handling: input buffer underflows. No actions needed.");
1577     }
1579     if(asitErr == ASIT_ERR_DECODE_QUIT) {
1580         TRACE_VERBOSE0("ASIT error handling: DECODE_QUIT - clear INPDATA event.");
1581 #if 0
1582         // Pend on INPTDATA event that should have been posted before decoding quits.
1583         events = Event_pend(asitEvent, ASIT_EVTMSK_NONE, ASIT_EVTMSK_INPDATA,
1584                             BIOS_WAIT_FOREVER);
1586         // Marks I/O PHY transfer and I/O BUFF write complete
1587         asitPhyTransferComplete(&pAsitCfg->pIoInp[0]);
1589         // Keep I/O BUFF read pointers going
1590         asitBypassIoData(&pAsitCfg->pIoInp[0]);
1591 #endif
1592         pAsitCfg->pIoInp[0].asipState = ASIT_RESET;
1593         pAsitCfg->pIoInp[0].numAsitRestart++;
1594         TRACE_VERBOSE0("ASIT error handling finished. Go to state ASIT_RESET.");
1595     }
1597     if(asitErr == ASIT_ERR_EVENTS) {
1598         pAsitCfg->pIoInp[0].asipState = ASIT_RESET;
1599         pAsitCfg->pIoInp[0].numAsitRestart++;
1600         TRACE_VERBOSE0("ASIT error handling: events error. Go to state ASIT_RESET.");
1601     }
1603     return;
1604 }  /* asitErrorHandling */
1607 //////////////////////////////////////////////////////////////////////////////
1608 void asitPostInfoEvent()
1610     Event_post(gAsitEvtHandle, ASIT_EVTMSK_INFOACK);
1613 void asitPostDecEvent()
1615     Event_post(gAsitEvtHandle, ASIT_EVTMSK_DECACK);
1617 //////////////////////////////////////////////////////////////////////////////
1619 /* Nothing past this line */