]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - processor-sdk/performance-audio-sr.git/blob - pasdk/test_dsp/mib/mib.c
Tested McASP configuration for I/O shortcut HDMIStereo.
[processor-sdk/performance-audio-sr.git] / pasdk / test_dsp / mib / mib.c
2 /*
3 Copyright (c) 2017, 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 //
38 // Stacking Input Buffer Driver implementations
39 //
40 //
41 // Derived from /c/ti/c6000/src/drivers/dgs.c
43 #include <xdc/std.h>
44 #include <xdc/cfg/global.h>
45 #include <xdc/runtime/Memory.h>
46 #include <xdc/runtime/System.h>
47 #include <xdc/runtime/Error.h>
48 #include <xdc/runtime/IHeap.h>
49 #include <ti/sysbios/knl/Queue.h>
50 #include <ti/sysbios/knl/Semaphore.h>
51 #include <ti/sysbios/heaps/HeapMem.h>
53 #include <dev2.h>
54 #include "mib.h"
55 #include "miberr.h"
56 #include <inpbuf.h>
57 #include <pafdec.h>
58 #include <pafsio.h>
59 #include <pafsio_ialg.h>
61 #include <limits.h> //INT_MAX
62 #include <string.h>
64 typedef xdc_Short MdInt;
65 typedef xdc_UShort MdUns;
66 typedef xdc_Char SmInt;
67 typedef xdc_UChar SmUns;
70 extern const ti_sysbios_heaps_HeapMem_Handle heapMemDdr3;
71 #define HEAPMALLOC (IHeap_Handle)heapMemDdr3
72 extern HeapMem_Handle DEV2_memSpaceToHeap (IALG_MemSpace space);
74 #include "pafhjt.h"
76 #include <ti/sysbios/knl/Clock.h>
77 #include <xdc/runtime/Log.h>
79 //grab from samrat.c
80 #include <paftyp.h>
81 #include <stdasp.h>
83 #include <logp.h>
84 #include <stdio.h>  // printf in case of programming error
86 // allows you to set a different trace module in pa.cfg
87 #define TR_MOD  trace
89 //#define TRACE_ENABLE
90 #ifdef TRACE_ENABLE
91   #include "dp.h"
92   #define TRACE(a)  dp a    // LOG_printf a
93 #else
94   #define TRACE(a)
95 #endif
97 extern const PAF_SampleRateHz
98 PAF_ASP_sampleRateHzTable[PAF_SAMPLERATE_N][PAF_SAMPLERATEHZ_N];
100 #define SCANATSAMPLERATELIMIT ((float) 48000.)
102 // Likely needs to be 7 when/if AC3 handling is changed to
103 // throw away fill.
104 #define NUM_CHILD_BUFFERS 6
106 Int   DIB_ctrl (DEV2_Handle device, Uns code, Arg Arg);
107 Int   DIB_idle (DEV2_Handle device, Bool Flush);
108 Int   DIB_issue (DEV2_Handle device);
109 Int   DIB_open (DEV2_Handle device, String Name);
110 Int   DIB_reclaim (DEV2_Handle device);
111 Int   DIB_getSync (DEV2_Handle device, PAF_InpBufConfig *pBufConfig);
112 Int   DIB_initFrame (DEV2_Handle device, PAF_InpBufConfig *pBufConfig);
113 Int   DIB_requestFrame (DEV2_Handle device, PAF_InpBufConfig *pBufConfig);
114 Int   DIB_issueChild (DEV2_Handle device, PAF_InpBufConfig *pBufConfig, Int size, Int forTotal);
115 Int   DIB_reclaimChild (DEV2_Handle device, PAF_InpBufConfig *pBufConfig);
116 Int   DIB_reset (DEV2_Handle device, PAF_InpBufConfig *pBufConfig);
117 Int   DIB_syncScan (DEV2_Handle device, PAF_InpBufConfig *pBufConfig, XDAS_UInt32 *pTimeout);
118 Int   DIB_waitForData (DEV2_Handle device, PAF_InpBufConfig *pBufConfig, XDAS_UInt32 count);
119 Int   DIB_syncScanDTS (DEV2_Handle device, PAF_InpBufConfig *pBufConfig, XDAS_UInt32 *pTimeout, XDAS_UInt16 *pHeaderEnd);
121 // Driver function table.
122 DIB_Fxns DIB_FXNS  = {
123     NULL,                // close not used in PA/F systems
124     DIB_ctrl,
125     DIB_idle,
126     DIB_issue,
127     DIB_open,
128     NULL,                // ready not used in PA/F systems
129     DIB_reclaim,
130     DIB_getSync,
131     DIB_initFrame,
132     DIB_requestFrame,
133     DIB_issueChild,
134     DIB_reclaimChild,
135     DIB_reset,
136     DIB_syncScan,
137     DIB_waitForData,
138     DIB_syncScanDTS
139 };
141 // macros assume pDevExt is available and pDevExt->pFxns is valid
142 #define DIB_FTABLE_getSync(_a,_b)             (*pDevExt->pFxns->getSync)(_a,_b)
143 #define DIB_FTABLE_initFrame(_a,_b)           (*pDevExt->pFxns->initFrame)(_a,_b)
144 #define DIB_FTABLE_requestFrame(_a,_b)        (*pDevExt->pFxns->requestFrame)(_a,_b)
145 #define DIB_FTABLE_issueChild(_a,_b,_c,_d)    (*pDevExt->pFxns->issueChild)(_a,_b,_c,_d)
146 #define DIB_FTABLE_reclaimChild(_a,_b)        (*pDevExt->pFxns->reclaimChild)(_a,_b)
147 #define DIB_FTABLE_reset(_a,_b)               (*pDevExt->pFxns->reset)(_a,_b)
148 #define DIB_FTABLE_syncScan(_a,_b,_c)         (*pDevExt->pFxns->syncScan)(_a,_b,_c)
149 #define DIB_FTABLE_waitForData(_a,_b,_c)      (*pDevExt->pFxns->waitForData)(_a,_b,_c)
150 #define DIB_FTABLE_syncScanDTS(_a,_b,_c,_d)   (*pDevExt->pFxns->syncScanDTS)(_a,_b,_c,_d)
152 // .............................................................................
154 //IBMODE
155 enum
157     MODE_DEFAULT = 0,
158     MODE_NO_ZERORUNRESTART = 1,
159     MODE_NO_ZERORUN = 2
160 };
162 // syncState
163 enum
165     SYNC_NONE,
166     SYNC_ONE,
167     SYNC_ONGOING,
168     SYNC_PCM,
169     SYNC_PCM_FORCED,
170     SYNC_AUTO
171 };
173 // scanState
174 enum
176     SCANNED_NONE,
177     SCANNED_IEC_PA,
178     SCANNED_IEC_PB,
179     SCANNED_IEC_PC,
180     SCANNED_DTS14_SYNC_A,
181     SCANNED_DTS14_SYNC_B,
182     SCANNED_DTS14_SYNC_C,
183     SCANNED_DTS14_SYNC_D,
184     SCANNED_DTS16_SYNC_A,
185     SCANNED_DTS16_SYNC_B,
186     SCANNED_DTS16_SYNC_C
187 };
189 // all sizes in number of 16bit words words
190 #define IEC_HEADER_SIZE   4 //PA PB PC PD
191 #define DTS14_HEADER_SIZE 6
192 #define DTS16_HEADER_SIZE 4
194 //table needed until PAF_SOURCE is reordered to match IEC numbering
195 const SmUns iecPafSource[23] =
197     PAF_SOURCE_UNKNOWN,  // 0: IEC NULL Type
198     PAF_SOURCE_AC3,      // 1: Comments on 1-15 match IEC 61937 part 2.
199     PAF_SOURCE_UNKNOWN,  // 2: IEC reserved
200     PAF_SOURCE_UNKNOWN,  // 3: IEC pause
201     PAF_SOURCE_UNKNOWN,  // 4: MPEG 1 layer 1
202     PAF_SOURCE_MP3,      // 5: MPEG layer 2 or 3
203     PAF_SOURCE_UNKNOWN,  // 6: MPEG 2 data with extension
204     PAF_SOURCE_AAC,      // 7: MPEG-2 AAC ADTS
205     PAF_SOURCE_UNKNOWN,  // 8: MPEG 2 layer 1 low sampling frequency
206     PAF_SOURCE_UNKNOWN,  // 9: MPEG 2 layer 2 or 3 low sampling frequency
207     PAF_SOURCE_UNKNOWN,  // 10: reserved
208     PAF_SOURCE_DTS,      // 11: DTS type 1 (11 bit: 512 sample repeat period)
209     PAF_SOURCE_DTS12,    // 12: DTS type 2 (12 bit: 1024 sample repeat period)
210     PAF_SOURCE_DTS13,    // 13: DTS type 3 (13 bit: 2048 sample repeat period)
211     PAF_SOURCE_DTS14,    // 14: ATRAC
212     PAF_SOURCE_UNKNOWN,  // 15: ATRAC 2/3
213     PAF_SOURCE_THD,      // 16
214     PAF_SOURCE_DTSHD,    // 17
215     PAF_SOURCE_WMA9PRO,  // 18
216     PAF_SOURCE_UNKNOWN,  // 19
217     PAF_SOURCE_UNKNOWN,  // 20
218     PAF_SOURCE_DDP,      // 21
219     PAF_SOURCE_THD,      // 22
220 };
222 // IEC framelengths (in 16bit words)
223 const MdUns iecFrameLength[23] =
225     0,
226     1536*2,
227     0,
228     0,
229     0,
230     1152*2,
231     0,
232     1024*2,
233     0,
234     0,
235     0,
236     512*2,
237     1024*2,
238     2048*2,
239     0,
240     0,
241     15*1024*2, //THD
242     1*1024, // DTSHD, actual framelength is adjusted by DTSsubType
243     4096*2,
244     0,
245     0,
246     1536*2*4,
247     15*1024*2 //THD
248 };
250 #define IEC_PA       ((short) 0xF872)
251 #define IEC_PB       ((short) 0x4E1F)
252 #define DTS16_SYNC_A ((short) 0x7FFE)
253 #define DTS16_SYNC_B ((short) 0x8001)
254 #define DTS16_SYNC_C ((short) 0xFC00)
255 #define DTS14_SYNC_A ((short) 0x1FFF)
256 #define DTS14_SYNC_B ((short) 0xE800)
257 #define DTS14_SYNC_C ((short) 0x07F0)
259 #define  DTS_BURST_TYPE_I  0x008B
260 #define  DTS_BURST_TYPE_II 0x018C
261 #define  DTS_BURST_TYPE_III 0x028D
262 #define  DTS_BURST_TYPE_IV  0x0491
264 #define  DTS_BURST_TYPE_IV_CBR  0x02
265 #define  DTS_BURST_TYPE_IV_LBR  0x03
266 #define  DTS_BURST_TYPE_IV_HBR  0x04
268 #define DEFAULT_AUTOREQUESTSIZE  128
269 //#define DEFAULT_AUTOREQUESTSIZE  256
271 // This is used at a couple of locations to ensure the transfer
272 // size is sufficiently long to be useful.
273 #define NOMINAL_XFERSIZE         128 //GJ Debug
275 #define min(a, b)  (((a) < (b)) ? (a) : (b))
276 #define max(a, b)  (((a) > (b)) ? (a) : (b))
278 // debug
279 //#include "evmc66x_gpio_dbg.h"
281 // -----------------------------------------------------------------------------
283 inline void IncrementPtr (PAF_InpBufConfig *pBufConfig, Ptr *pPtr, int numWords)
285     int addr;
288     addr = (int) *pPtr + numWords*pBufConfig->sizeofElement;
289     if (addr > ((int) pBufConfig->base.pVoid + pBufConfig->sizeofBuffer - 1))
290         addr -= pBufConfig->sizeofBuffer;
292     *pPtr = (Ptr) addr;
293     return;
294 } // IncrementPtr
296 // -----------------------------------------------------------------------------
298 inline int GetNumAvail (PAF_InpBufConfig *pBufConfig)
300     int numBytes;
303     if ( (Uns) pBufConfig->head.pVoid >= (Uns) pBufConfig->pntr.pVoid)
304         numBytes = ((int)pBufConfig->head.pVoid - (int)pBufConfig->pntr.pVoid);
305     else
306         numBytes = ((int)pBufConfig->head.pVoid - (int)pBufConfig->pntr.pVoid + pBufConfig->sizeofBuffer);
308     // return in words
309     return (numBytes / pBufConfig->sizeofElement);
310 } // GetNumAvail
312 // -----------------------------------------------------------------------------
313 // compute how much data we have including outstanding requests
315 inline int GetFutureAvail (PAF_InpBufConfig *pBufConfig)
317     int numBytes;
320     if ( (Uns) pBufConfig->futureHead.pVoid >= (Uns) pBufConfig->pntr.pVoid)
321         numBytes = ((int)pBufConfig->futureHead.pVoid - (int)pBufConfig->pntr.pVoid);
322     else
323         numBytes = ((int)pBufConfig->futureHead.pVoid - (int)pBufConfig->pntr.pVoid + pBufConfig->sizeofBuffer);
325     // return in words
326     return (numBytes / pBufConfig->sizeofElement);
327 } // GetFutureAvail
329 // -----------------------------------------------------------------------------
331 Int DIB_issue (DEV2_Handle device)
333     DIB_DeviceExtension   *pDevExt = (DIB_DeviceExtension *)device->object;
334     DEV2_Frame             *srcFrame;
335     Int                    status;
336     PAF_InpBufConfig      *pBufConfig;
339     srcFrame = Queue_get (device->todevice);
340     pBufConfig = (PAF_InpBufConfig *) srcFrame->addr;
341     if (!pBufConfig || !pBufConfig->pBufStatus)
342         return SIO2_EINVAL;
344     Queue_put (device->fromdevice, (Queue_Elem *)srcFrame);
346     if (srcFrame->arg == PAF_SIO_REQUEST_NEWFRAME) {
348         // do nothing if not synced since syncing done in reclaim
349         // This is executed in force modes from the first call to PAF_AST_decodeInit
350         // which calls SIO2_issue for NEWFRAME before all other calls.
351         if (pDevExt->syncState == SYNC_NONE)
352             return 0;
354         status = DIB_FTABLE_requestFrame (device, &pDevExt->bufConfig);
355         if (status)
356             return status;
357     }
359     return 0;
360 } // DIB_issue
362 // -----------------------------------------------------------------------------
363 // Although interface allows for arbitrary BufConfigs we only support 1 -- so
364 // we can assume the one on the fromdevice is the one we want
366 extern int gIsrInputCnt;
367 extern int gIsrOutputCnt;
369 Int DIB_reclaim (DEV2_Handle device)
371     DIB_DeviceExtension   *pDevExt = (DIB_DeviceExtension *) device->object;
372     DEV2_Frame             *dstFrame;
373     Int                    status = 0;
374     PAF_InpBufConfig      *pBufConfig;
376     dstFrame = (DEV2_Frame *) Queue_head (device->fromdevice);
378     if (dstFrame == (DEV2_Frame *) device->fromdevice)
379         return DIBERR_UNSPECIFIED;
380     if (!dstFrame->addr)
381         return DIBERR_UNSPECIFIED;
383     // if deferred error from last request frame then return now
384     status = pDevExt->deferredError;
385     if (status) {
386         pDevExt->deferredError = 0;
387         pDevExt->sourceProgram = PAF_SOURCE_UNKNOWN;
388         return status;
389     }
391     pBufConfig = (Ptr) dstFrame->addr;
392     dstFrame->size = sizeof (PAF_InpBufConfig);
394     // .........................................................................
396     if ((pDevExt->syncState == SYNC_NONE) || (dstFrame->arg == PAF_SIO_REQUEST_SYNC)) {
398         Log_info0("DIB: At case: syncState == SYNC_NONE (or PAF_SIO_REQUEST_SYNC)");
400         // pass in external buffer config which used to initialize the internal view
401         status = DIB_FTABLE_reset (device, pBufConfig);
402         if (status)
403             return status;
405         status = DIB_FTABLE_getSync (device, &pDevExt->bufConfig);
406         if (status)
407             return status;
409         // since getSync resets sourceProgram to unknown at entry
410         // sourceProgram will remain unknown if no sync is returned
411         // (i.e. no need to reset it here)
412         if (pDevExt->syncState == SYNC_NONE)
413         {
414             Log_info0("Returning DIBERR_SYNC after DIB_FTABLE_getSync");
415             return DIBERR_SYNC;
416         }
418         // get input info (frameLength/etc)
419         status = DIB_FTABLE_initFrame (device, &pDevExt->bufConfig);
421         if (status)
422         {
423             Log_info1("Returning %d after DIB_FTABLE_initFrame", status);
424             return status;
425         }
427         // request timing frame
428         status = DIB_FTABLE_requestFrame (device, &pDevExt->bufConfig);
429         if (status)
430         {
431             Log_info1("Returning %d after DIB_FTABLE_requestFrame", status);
432             return status;
433         }
434         // update external view of bufConfig. In particular for slave force PCM
435         // this insures that the first decode will be processed with deliverZeros = 1
436         // which is necessary since the first decode of slave input occurs before the
437         // first slave input frame is actually captured.
438         *pBufConfig = pDevExt->bufConfig;
440     } //((pDevExt->syncState == SYNC_NONE) || (dstFrame->arg == PAF_SIO_REQUEST_SYNC))
442     // .........................................................................
444     if (dstFrame->arg == PAF_SIO_REQUEST_NEWFRAME) {
446         Log_info0("DIB: At case = PAF_SIO_REQUEST_NEWFRAME");
448         // wait for enough data to check for sync at expected location
449         status = DIB_FTABLE_waitForData (device, &pDevExt->bufConfig, pDevExt->bufConfig.frameLength);
450         if (status)
451         {
452             Log_info2("DIB_reclaim.%d DIB_FTABLE_waitForData returned %d", __LINE__, status);
453             //TRACE((&TR_MOD, "DIB_reclaim.%d DIB_FTABLE_waitForData returned %d\n", __LINE__, status));
454             return status;
455         }
457         // if PCM, but not forced PCM, then scan for bitstream sync
458         // note that we we using the local view of bufConfig here and we update the
459         // public view afterwards.
460         if (pDevExt->syncState == SYNC_PCM) {
461             float sampleRate = PAF_ASP_sampleRateHzTable[pBufConfig->pBufStatus->sampleRateStatus][PAF_SAMPLERATEHZ_STD];
462             PAF_InpBufConfig *pBufConfig = &pDevExt->bufConfig;
463             Int ibMode = pBufConfig->pBufStatus->mode; // read mode register once
465             // normally no scanning done if sampleRate > 48kHz since bitstream input is highly unlikley.
466             if ((sampleRate <= SCANATSAMPLERATELIMIT) || pBufConfig->pBufStatus->scanAtHighSampleRateMode) {
467                 if (!pBufConfig->deliverZeros) {
468                     pDevExt->pcmTimeout = pBufConfig->lengthofData;
470                     // check zeroRunTrigger if needed
471                     if (ibMode != MODE_NO_ZERORUN) {
472                         if(pDevExt->zeroCount >= 2 * pBufConfig->pBufStatus->zeroRunTrigger) {
473                             // set this flag one block late to allow for
474                             // transmission of all data in frame which contained zeroRunTrigger
475                             pBufConfig->deliverZeros = 1;
476                             pDevExt->pcmTimeout = 2 * pBufConfig->pBufStatus->unknownTimeout;
477                         } // > zeroRunTrigger
478                     } // !MODE_NO_ZERORUN
479                 } // !pBufConfig->deliverZeros
481                 // scan PCM data
482                 status = DIB_FTABLE_syncScan (device, pBufConfig, &pDevExt->pcmTimeout);
483                 if (status) {
484                     pDevExt->sourceProgram = PAF_SOURCE_UNKNOWN;
485                     Log_info2("DIB_reclaim.%d DIB_FTABLE_syncScan returned %d", __LINE__, status);
486                     //TRACE((&TR_MOD, "DIB_reclaim.%d DIB_FTABLE_syncScan returned %d\n", __LINE__, status));
487                     return status;
488                 }
490                 // if scan found something other than PCM, then exit with error
491                 if (pDevExt->syncState != SYNC_PCM)
492                 {
493                     Log_info1("DIB_reclaim.%d error: syncState != SYNC_PCM", __LINE__);
494                     //TRACE((&TR_MOD, "DIB_reclaim.%d error: syncState != SYNC_PCM\n", __LINE__));
495                     return DIBERR_SYNC;
496                 }
498                 // if heeding zeroRunRestart control then return to unknown if necessary
499                 if ((ibMode == MODE_DEFAULT) &&
500                     (pDevExt->zeroCount >= 2*pBufConfig->pBufStatus->zeroRunRestart)) {
501                     // if zeroRunRestart me then reset input to unknown
502                     Log_info1("DIB_reclaim.%d error: zeroRunRestart, setting PAF_SOURCE_UNKNOWN", __LINE__);
503                     //TRACE((&TR_MOD, "DIB_reclaim.%d error: zeroRunRestart, setting PAF_SOURCE_UNKNOWN\n", __LINE__));
504                     pDevExt->sourceProgram = PAF_SOURCE_UNKNOWN;
505                     return DIBERR_SYNC;
506                 }
508                 // since in skeptical state we disallow returning to PCM when end of timeout contains zeros
509                 // note that we need not check the mode here since above logic prevents deliverZeros state.
510                 if (pBufConfig->deliverZeros && (pDevExt->zeroCount >= 2 * pBufConfig->pBufStatus->zeroRunTrigger))
511                 {
512                     //TRACE((&TR_MOD, "DIB_reclaim.%d set pcmTimeout = unknown timeout\n", __LINE__));
513                     pDevExt->pcmTimeout = 2 * pBufConfig->pBufStatus->unknownTimeout;
514                 }
515             } //scanAtHighSampleRate
516         } //SYNC_PCM
518         // clear this flag immediately to play new audio ASAP
519         // this check is OK for forced PCM since pcmTimeout and zeroCount are not
520         // updated
521         if (pDevExt->bufConfig.deliverZeros && !pDevExt->pcmTimeout &&
522             (pDevExt->zeroCount < 2 * pDevExt->bufConfig.pBufStatus->zeroRunTrigger))
523         {
524             pDevExt->bufConfig.deliverZeros = 0;
525         }
527         // update external view of buffer with local view we do this with current 
528         // frame info before the following update to the local view for the next 
529         // frame to be captured. Need to subtract headerSize from lengthofData
530         // since, at least for THD, it is needed by decoders.
531         *pBufConfig = pDevExt->bufConfig;
532         pBufConfig->lengthofData -= pDevExt->headerSize;
533         Log_info4("DIB_reclaim.%d lengthofData = %d; InISRCNT=%d; OutISRCNT=%d", __LINE__, pBufConfig->lengthofData, gIsrInputCnt, gIsrInputCnt);
534         //TRACE((&TR_MOD, "DIB_reclaim.%d lengthofData = %d\n", __LINE__, pBufConfig->lengthofData));
536         // HACK: for DSD the frameLength needs to be the number of samples to generate.
537         if ((pDevExt->sourceSelect >= PAF_SOURCE_DSD1) &&
538             (pDevExt->sourceSelect <= PAF_SOURCE_DSD3))
539             pBufConfig->frameLength /= pBufConfig->stride;
540         Log_info2("DIB_reclaim.%d frameLength = %d", __LINE__, pBufConfig->frameLength);
541         //TRACE((&TR_MOD, "DIB_reclaim.%d frameLength = %d\n", __LINE__, pBufConfig->frameLength));
543         // set external view to point at synch position of the frame guaranteed
544         // to be captured by above waitForData. Need to condition this against PCM since
545         // in that case pSync could point anywhere in the buffer to to syncScan. E.g.
546         // if there was a partial sync then pSync would point at that rather than
547         // at the beginning of the buffer.
548         // TODO: change syncScan to only update pDevExt->pSync when there is an actual sync
549         //       so that we can use this for both PCM and bitstream
550         if (pDevExt->syncState == SYNC_ONGOING) {
551             pBufConfig->pntr = pDevExt->pSync;
552             IncrementPtr (pBufConfig, &pBufConfig->pntr.pVoid, pDevExt->headerSize);
553         } //SYNC_ONGOING
555         // if a bitstream then need to update tail to bitstream sync location
556         // and check for next sync at expected location
557         // quick scan for sync. if decoding IEC but sync is missing then
558         // defer error until the next frame so that we decode all frames
559         // TODO: does this assume decoders have copied the entire input frame
560         //       i.e. it is ok to adjust the input buffer pointers.
561         // if successful then this sets
562         //      pSync = address of PA (for IEC)
563         status = DIB_FTABLE_initFrame (device, &pDevExt->bufConfig);  // DIB_initFrame
564         if (status) {
565             if (pBufConfig->pBufStatus->lastFrameMask & (1 << pDevExt->sourceProgram)) {
566                 pDevExt->deferredError = status;
567                 Log_info1("DIB_reclaim.%d last frame\n", __LINE__);
568                 //TRACE((&TR_MOD, "DIB_reclaim.%d last frame\n", __LINE__));
569                 pBufConfig->pBufStatus->lastFrameFlag = 1;
570                 return 0;
571             }
572             else {
573                 Log_info1("DIB_reclaim.%d setting PAF_SOURCE_UNKNOWN", __LINE__);
574                 //TRACE((&TR_MOD, "DIB_reclaim.%d setting PAF_SOURCE_UNKNOWN\n", __LINE__));
575                 pDevExt->sourceProgram = PAF_SOURCE_UNKNOWN;
576                 return status;
577             }
578         }
580     } //(dstFrame->arg == PAF_SIO_REQUEST_NEWFRAME)
582     // .........................................................................
584     Log_info4("DIB_reclaim.%d exit status = %d, InISRCNT = %d OutISRCNT = %d", __LINE__, status, gIsrInputCnt, gIsrOutputCnt);
585     //TRACE((&TR_MOD, "DIB_reclaim.%d exit status = %d\n", __LINE__, status));
587     return status;
588 } // DIB_reclaim
590 // -----------------------------------------------------------------------------
592 Int DIB_ctrl (DEV2_Handle  device, Uns code, Arg arg)
594     DIB_DeviceExtension   *pDevExt = (DIB_DeviceExtension *)device->object;
595     DEV2_Handle            pChild = (DEV2_Handle)&pDevExt->child;
596     Int status = 0;
599     switch (code) {
601         case PAF_SIO_CONTROL_GET_CHILD_DEVICE:
602             *((Arg *)arg) = (Arg) pChild;
603             break;
605             //,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
607         case PAF_SIO_CONTROL_SET_DECSTATUSADDR:
608             pDevExt->pDecodeStatus = (PAF_DecodeStatus *) arg;
609             break;
611         case PAF_SIO_CONTROL_SET_PCMFRAMELENGTH:
612             pDevExt->pcmFrameLength = (XDAS_Int32) arg;
613             break;
615         case PAF_SIO_CONTROL_SET_SOURCESELECT:
616             pDevExt->sourceSelect = (XDAS_Int8) arg;
617             break;
619         case PAF_SIO_CONTROL_SET_AUTOREQUESTSIZE:
620             pDevExt->autoRequestSize = (XDAS_Int16) arg;
621             break;
623         case PAF_SIO_CONTROL_GET_SOURCEPROGRAM:
624             if (!arg)
625                 return DIBERR_UNSPECIFIED;
626             *((XDAS_Int8 *) arg) = pDevExt->sourceProgram;
627             break;
629         case PAF_SIO_CONTROL_SET_IALGADDR:
630             pDevExt->pSioIalg = (PAF_SIO_IALG_Obj *) arg;
631             break;
633             //,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
635         case PAF_SIO_CONTROL_OPEN:
636             pDevExt->sourceProgram = PAF_SOURCE_UNKNOWN;
637             pDevExt->zeroCount = 0;
638             if (pDevExt->pInpBufStatus)
639                 pDevExt->pInpBufStatus->zeroRun = 0;
640             status = DEV2_ctrl (pChild, code, arg);
641             break;
643         case PAF_SIO_CONTROL_CLOSE:
644             if (pDevExt->pInpBufStatus)
645                 pDevExt->pInpBufStatus->zeroRun = 0;
646             status = DEV2_ctrl (pChild, code, arg);
647             break;
649         // return number of DMA events vs. request size
650         // only update if not in error state (i.e. status = 0)
651         case PAF_SIO_CONTROL_GET_NUM_EVENTS:
652             if (!arg)
653                 return DIBERR_UNSPECIFIED;
654             status = DEV2_ctrl (pChild, code, arg);
655             if (!status)
656                 *((Int *)arg) -= pDevExt->pcmFrameLength;
657             break;
659         // return net samples until next DIB_waitForData() should succeed w/o blocking
660         case PAF_SIO_CONTROL_GET_NUM_REMAINING:
661             if (!arg)
662                 return DIBERR_UNSPECIFIED;
663             status = DEV2_ctrl (pChild, code, arg);
664             *((Int *)arg) -= pDevExt->numSamplesExtra;
665             break;
667         default:
668             status = DEV2_ctrl (pChild, code, arg);
669             break;
670     }
672     return status;
673 } // DIB_ctrl
675 // -----------------------------------------------------------------------------
677 Int DIB_idle (DEV2_Handle device, Bool flush)
679     DIB_DeviceExtension   *pDevExt = (DIB_DeviceExtension *)device->object;
680     Int                    status;
683     while (!Queue_empty (device->todevice))
684         Queue_enqueue (device->fromdevice, Queue_dequeue (device->todevice));
686     while (!Queue_empty (device->fromdevice))
687         Queue_enqueue (Queue_handle(&((SIO2_Handle) device)->framelist), Queue_dequeue (device->fromdevice));
689     status = DIB_FTABLE_reset (device, NULL);
690     if (status)
691         return status;
693     return 0;
694 } // DIB_idle
696 // -----------------------------------------------------------------------------
698 Int DIB_open (DEV2_Handle device, String name)
700     DIB_DeviceExtension   *pDevExt;
701     DEV2_Handle             pChild;
702     DEV2_Device            *entry;
703     DEV2_Frame             *frame;
704     Int                    status, i;
705         Error_Block eb;
707         Error_init(&eb);
709     name = DEV2_match (name, &entry);
710     if (entry == NULL) {
711         Log_info1("DEV2_match failed in DIB_open:", SIO2_ENODEV);
712         return SIO2_ENODEV;
713     }
715     // only one frame interface supported
716     if (device->nbufs != 1)
717         return SYS_EALLOC;
719     if (!(pDevExt = Memory_alloc (device->bufSeg, sizeof(DIB_DeviceExtension), 0, &eb)))
720     {
721         Log_info1("DIB Memory alloc failed in DIB_open:", SYS_EALLOC);
722         return SYS_EALLOC;
723     }
724     pDevExt->pcmFrameLength = 0;
725     pDevExt->sourceSelect  = PAF_SOURCE_NONE;
726     pDevExt->autoRequestSize = DEFAULT_AUTOREQUESTSIZE;
727     pDevExt->pInpBufStatus = NULL;
728     pDevExt->pDecodeStatus = NULL;
729     device->object = (Ptr)pDevExt;
731     pChild = (DEV2_Handle)&pDevExt->child;
732     pChild->fromdevice = Queue_create (NULL, &eb);
733     pChild->todevice = Queue_create (NULL, &eb);
734     if (pChild->fromdevice == NULL || pChild->todevice == NULL) {
735         Log_info1 ("DIB Queue_create failed in DIB_open:", SYS_EALLOC);
736         return SYS_EALLOC;
737     }
739     pChild->bufsize = 0;
740     pChild->nbufs = NUM_CHILD_BUFFERS;
741     pChild->bufSeg = device->bufSeg;
742     pChild->mode = device->mode;
743     pChild->timeout = device->timeout;
744     pChild->align = device->align;
745     pChild->devid = entry->devid;
746     pChild->params = entry->params;
747     pChild->fxns = *(DEV2_Fxns *)(entry->fxns);
748     ((SIO2_Handle)pChild)->model = ((SIO2_Handle)device)->model;
750     //Create frames and put them on the correct device queue.
751     // We only support ISSUERECLAIM mode so size = 0
752     Queue_construct(&((SIO2_Handle)pChild)->framelist, NULL); //Queue_new (&((SIO2_Handle)pChild)->framelist);
753     for (i=0; i < pChild->nbufs; i++) {
754         frame = DEV2_mkframe (0, 0, 0);
755         if (!frame)
756             return SYS_EALLOC;
757         Queue_put (Queue_handle(&((SIO2_Handle)pChild)->framelist), (Queue_Elem *) frame);
758     }
760     // open underlying device
761     status = DEV2_open (pChild, name);
762     if (status)
763         return status;
765     // use dev match to fetch function table pointer for DIB
766     name = DEV2_match ("/DIB", &entry);
767     if (entry == NULL) {
768         Log_info1 ("DEV2_match for DIB in DIB_open:", SIO2_ENODEV);
769         return SIO2_ENODEV;
770     }
771     pDevExt->pFxns = (DIB_Fxns *) entry->fxns;
773     // set IEC frame length table pointer -- change in
774     // subsequent control call (not defined) to add new IEC type
775     pDevExt->pIECFrameLength = (XDAS_UInt16 *) iecFrameLength;
777     status = DIB_FTABLE_reset (device,NULL);
778     if (status)
779         return status;
781     return status;
782 } // DIB_open
784 // -----------------------------------------------------------------------------
785 // Although this is void it is still needed since BIOS calls all DEV inits on
786 // startup.
788 Void DIB_init (Void)
790 } // DIB_init
792 // -----------------------------------------------------------------------------
793 // Notes:
794 //   1. DIB_reset is called prior to this function being called.(see DIB_reclaim)
795 //   2. (1) ==> sizeofBuffer is an integral # of 2byte samples.
796 //   3. (2) ==> if we use a request size which is divisor of sizeofBuffer there
797 //              will be no wrap-around when requesting data for scanning.
798 //   4. (3) ==> we meet the interface requirement for syncScan which has no
799 //              circular arithmetic.
801 Int DIB_getSync (DEV2_Handle device, PAF_InpBufConfig *pBufConfig )
803     DIB_DeviceExtension   *pDevExt = (DIB_DeviceExtension *)device->object;
804     DEV2_Handle             pChild = (DEV2_Handle)&pDevExt->child;
805     int status;
806     Uns timeout,  syncBufSize, syncRequestSize;
807     Int ibMode = pBufConfig->pBufStatus->mode; // read mode register once
808     Int deliverZeros;
810     //..........................................................................
812     // implement local timeout so that we don't get 'stuck' here when input
813     // is all zeros + lock
814     if (pDevExt->syncState == SYNC_NONE) {
815         Uns localTimeout;
816         // latch value before resetting to PAF_SOURCE_UNKNOWN
817         Int sourceProgram = pDevExt->sourceProgram;
819         pDevExt->sourceProgram = PAF_SOURCE_UNKNOWN;
821         // if here then guaranteed to have fresh reset
823         if (pDevExt->sourceSelect == PAF_SOURCE_PCM || pDevExt->sourceSelect == PAF_SOURCE_DSD1 ||
824             pDevExt->sourceSelect == PAF_SOURCE_DSD2 || pDevExt->sourceSelect == PAF_SOURCE_DSD3) {
825             timeout = 0;
827             // no zero run counting in force modes since no scanning
828             pBufConfig->pBufStatus->zeroRun = 0;
829             pDevExt->zeroCount = 0;
830         }
831         else if ((pDevExt->sourceSelect == PAF_SOURCE_PCMAUTO) &&
832                  ((sourceProgram == PAF_SOURCE_UNKNOWN) || (sourceProgram == PAF_SOURCE_PCM))) {
833             // if sourceselect is PCMAUTO then
834             //    if current input is a bistream then scan for normal timeout period
835             //    if current input is unknown or PCM then transition immediately to PCM
836             // this provides for *no* lossed PCM, detection of bitstreams, but some noise
837             // is possible.
838             timeout = 0;
839             pDevExt->zeroCount = 0;
840         }
841         else
842             timeout = 2*pBufConfig->pBufStatus->unknownTimeout;
844         // force request size to be a divisor of sizeofBuffer
845         syncRequestSize = NOMINAL_XFERSIZE;
846         if (pBufConfig->stride > 2)
847             syncRequestSize *= pBufConfig->stride;
848         syncBufSize = pBufConfig->sizeofBuffer / ((int) (pBufConfig->sizeofBuffer/syncRequestSize));
850         if (timeout) {
851             status = DIB_FTABLE_issueChild (device, pBufConfig, syncBufSize, 0);
852             if (status)
853                 return status;
854         }
856         localTimeout = timeout;
857         while ((timeout) && (pDevExt->syncState != SYNC_ONE)) {
859             status = DIB_FTABLE_issueChild (device, pBufConfig, syncBufSize, 0);
860             if (status)
861                 return status;
863 #if 0 // debug
864             // Shows timing of Input Rx SIO reclaim during autodet
865             // ADC B5
866             {
867                 static Uint8 toggleState = 0;
868                 if (toggleState == 0)
869                     GPIOSetOutput(GPIO_PORT_0, GPIO_PIN_99);
870                 else
871                     GPIOClearOutput(GPIO_PORT_0, GPIO_PIN_99);
872                 toggleState = ~(toggleState);
873             }
874 #endif            
876             // get next block of data to scan
877             status = DIB_FTABLE_waitForData (device, pBufConfig, syncBufSize);
878             if (status)
879                 return status;
880             
881             // this function updates the tail pointer
882             status = DIB_FTABLE_syncScan (device, pBufConfig, &timeout);
883             if (status)
884                 return status;
886             // if input is zero, i.e. haven't decremented at all,
887             // then break out and use more logic and
888             if (localTimeout < syncBufSize) {
889                 // Should this be 2 *? MAW
890                 if (timeout == 2*pBufConfig->pBufStatus->unknownTimeout)
891                     break;
892             }
893             else
894             {
895                 Log_info3("DIB: Inside DIB_getSync with syncState != SYNC_ONE. localTimeout = %d, syncBufSize  = %d, timeout = %d", localTimeout,syncBufSize, timeout);
896                 localTimeout -= syncBufSize;
897             }
898         }
900         // if found sync then return to caller who will call 
901         // initFrame to get bitstream info and requestFrame for data
902         if (pDevExt->syncState != SYNC_NONE)
903             return 0;
905     } //pDevExt->syncState == SYNC_NONE
907     //..........................................................................
909     // set default to zero -- we assume decode calls will not be made
910     // before data is available since this must be master input. Will be changed below
911     // as needed
912     deliverZeros = 0;
914     if (pDevExt->syncState == SYNC_AUTO) {
915         timeout = pDevExt->pcmTimeout;
916         deliverZeros = 1;
917     }
919     // if in zero run, and heeding full zeroRun control, then return to unknown if # zeros > trigger/Restart
920     if (ibMode == MODE_DEFAULT) {
921         if ((pDevExt->zeroCount >= 2 * pBufConfig->pBufStatus->zeroRunTrigger) ||
922             (pDevExt->zeroCount >= 2 * pBufConfig->pBufStatus->zeroRunRestart))
923             return DIBERR_SYNC;
924         // since we may have exited prematurely above we check timeout
925         if (timeout)
926             return DIBERR_SYNC;
927     }
928     // if heeding trigger but not restart then enter deliverZeros state of PCM
929     else if (ibMode == MODE_NO_ZERORUNRESTART) {
930         if (pDevExt->zeroCount >= 2 * pBufConfig->pBufStatus->zeroRunTrigger)
931             deliverZeros = 1;
932     }
934     // here if timeout to PCM (includes force PCM)
935     status = DIB_FTABLE_reset (device, pBufConfig);
936     if (status)
937         return status;
939     // hack -- try 32bit then 16bit if necessary
940     pBufConfig->sizeofElement = 4;
941     status = SIO2_ctrl (pChild,(Uns)PAF_SIO_CONTROL_SET_WORDSIZE,pBufConfig->sizeofElement);
942     if(status) {
943         pBufConfig->sizeofElement = 2;
944         status = SIO2_ctrl (pChild, (Uns)PAF_SIO_CONTROL_SET_WORDSIZE,pBufConfig->sizeofElement);
945         if(status)
946             return status;
947     }
949     // Force sizeofBuffer to be integral number of frame sizes. This ensures that the
950     // pcm buffers will not need a circular wrap-around. We prevent this because
951     // syncScan makes this assumption in order to perform an efficient scan.
952     {
953         int sizeofStride = pBufConfig->sizeofElement*pBufConfig->stride*pDevExt->pcmFrameLength;
954         pBufConfig->sizeofBuffer = (pBufConfig->allocation)/sizeofStride*sizeofStride;
955     }
957     if (pDevExt->sourceSelect == PAF_SOURCE_DSD1 || pDevExt->sourceSelect == PAF_SOURCE_DSD2 ||
958         pDevExt->sourceSelect == PAF_SOURCE_DSD3)
959         pDevExt->sourceProgram = pDevExt->sourceSelect;
960     else
961         pDevExt->sourceProgram = PAF_SOURCE_PCM;
963     if (pDevExt->sourceSelect == PAF_SOURCE_PCM || pDevExt->sourceSelect == PAF_SOURCE_DSD1 ||
964         pDevExt->sourceSelect == PAF_SOURCE_DSD2 || pDevExt->sourceSelect == PAF_SOURCE_DSD3) {
965         pDevExt->syncState = SYNC_PCM_FORCED;
966         // set to one -- ensures that PCM decode calls made before data is
967         // available will result in zero output.
968         // (mostly needed for PA15 since, currently, all other frameworks
969         // require a frame of data before the first decode call.
970         deliverZeros = 1;
971     }
972     else
973         pDevExt->syncState = SYNC_PCM;
975     // update config struct
976     pBufConfig->deliverZeros = deliverZeros;
978     //..........................................................................
980     return 0;
981 } // DIB_getSync
983 // -----------------------------------------------------------------------------
985 int gWrapCtr=0;
986 Int DIB_issueChild (DEV2_Handle device, PAF_InpBufConfig  *pBufConfig, int size, int forTotal)
988     DIB_DeviceExtension   *pDevExt = (DIB_DeviceExtension *) device->object;
989     DEV2_Handle             pChild  = (DEV2_Handle) &pDevExt->child;
990     int                    bufEnd  = (int) pBufConfig->base.pVoid + pBufConfig->sizeofBuffer;
991     DEV2_Frame             *dstFrame;
992     int                    futureHead, status;
993     int                    i, sizes[2];
994     Ptr                    endAddr[2];
995    
998     // if seeking for total amount then adjust for difference
999     if (forTotal) 
1000         size -= GetFutureAvail (pBufConfig);
1002     // return success if we needn't make any requests
1003     if (size <= 0)
1004         return 0;
1006     // assume if eight channel then using optimized dMAX routine which requires
1007     // requests which are a mulitple of 8 to operate correctly. If not a proper
1008     // multiple then we increase the requested size as needed. This information
1009     // is communicated to other portions of DIB indirectly through the update
1010     // of the futureHead pointer (here) and head pointer (in reclaim). To these
1011     // other portions it is a don't care as we ensure enough data requested will
1012     // be available at, the now slightly deferred, reclaim point. We assume that
1013     // the buffer is a multiple of 8 and so, by using this single statement, we
1014     // ensure all requests are a mulitple 8 even if they need to be split across
1015     // the buffer wrap point.
1016     if (pBufConfig->stride == 8)
1017         size = (size + 7) & ~0x7;
1019     // convert to bytes
1020     size *= pBufConfig->sizeofElement;
1021     //size *= 4;
1023     // if request crosses circular buffer boundary then split into two requests
1024     futureHead = (int) pBufConfig->futureHead.pVoid + size;
1025     if (futureHead <= bufEnd) {
1026         sizes[0] = size;
1027         sizes[1] = 0;
1029         // If this request happens to be the rest of the buffer, then 
1030         // futureHead must be set to the beginning of the buffer.
1031         if (futureHead != bufEnd)
1032             endAddr[0] = (Ptr) futureHead;
1033         else
1034             endAddr[0] = pBufConfig->base.pVoid;
1035     }
1036     else {
1037         sizes[0] = bufEnd - (int) pBufConfig->futureHead.pVoid;
1038         sizes[1] = futureHead - bufEnd;
1039         endAddr[0] = pBufConfig->base.pVoid;
1040         endAddr[1] = (Ptr) ((int)pBufConfig->base.pVoid + sizes[1]);
1041     }
1043     for (i=0; i < 2; i++) {
1044         if (sizes[i]) {
1045             dstFrame = Queue_get (Queue_handle(&((SIO2_Handle) pChild)->framelist));
1046             if (dstFrame == (DEV2_Frame *)&((SIO2_Handle) pChild)->framelist)
1047                 return DIBERR_UNSPECIFIED;
1048             dstFrame->arg = (Arg) pBufConfig;
1050             dstFrame->addr = pBufConfig->futureHead.pVoid;
1051             dstFrame->size = sizes[i];
1052             Queue_put (pChild->todevice, (Queue_Elem *)dstFrame);
1053             status = DEV2_issue (pChild);
1054             if (status)
1055                 return DIBERR_UNSPECIFIED;
1057             pBufConfig->futureHead.pVoid = endAddr[i];
1059             if (i==1)
1060             {
1061                 gWrapCtr++;
1062                 Log_info4("DIB: Inside DIB_issueChild Wrap Around Point #%d, with Future Head: 0x%x, current addr: 0x%x, current size: %d", gWrapCtr, (xdc_IArg)pBufConfig->futureHead.pVoid, (xdc_IArg)dstFrame->addr, dstFrame->size );
1064             }
1065         }
1066     }
1068     return 0;
1069 } // DIB_issueChild
1071 // -----------------------------------------------------------------------------
1073 Int DIB_reclaimChild (DEV2_Handle device, PAF_InpBufConfig *pBufConfig)
1075     DIB_DeviceExtension    *pDevExt = (DIB_DeviceExtension *)device->object;
1076     DEV2_Handle              pChild = (DEV2_Handle)&pDevExt->child;
1077     DEV2_Frame              *srcFrame;
1078     int                     status, bufEnd;
1080     //Log_info3("DIB_reclaimChild.%d: Inside DEV2_reclaim(pChild) pChild = 0x%x DEV2_reclaim = 0x%x", __LINE__, pChild, &pChild->fxns.reclaim);
1081     //TRACE((&TR_MOD, "DIB_reclaimChild.%d: calling DEV2_reclaim(pChild) pChild = 0x%x DEV2_reclaim = 0x%x", __LINE__, pChild, &pChild->fxns.reclaim));
1082     status = DEV2_reclaim (pChild);
1083     if (status)
1084     {
1085         Log_info2("DIB_reclaimChild.%d DEV2_reclaim() returned (%d) DIBERR_UNSPECIFIED", __LINE__, status);
1086         //TRACE((&TR_MOD, "DIB_reclaimChild.%d DEV2_reclaim() returned (%d) DIBERR_UNSPECIFIED \n", __LINE__, status));
1087         return DIBERR_UNSPECIFIED;
1088     }
1090     //Log_info1("DIB_reclaimChild.%d calling Queue_get()", __LINE__);
1091     //TRACE((&TR_MOD, "DIB_reclaimChild.%d calling Queue_get()\n", __LINE__));
1092     srcFrame = Queue_get (pChild->fromdevice);
1093     //Log_info2("DIB_reclaimChild.%d calling Queue_put(), srcFrame = 0x%x", __LINE__, srcFrame);
1094     //TRACE((&TR_MOD, "DIB_reclaimChild.%d calling Queue_put(), srcFrame = 0x%x\n", __LINE__, srcFrame));
1095     Queue_put (Queue_handle(&((SIO2_Handle) pChild)->framelist), (Queue_Elem *)srcFrame);
1097     // Only for non-fill requests do we update ptrs
1098     if (srcFrame->addr != NULL) {
1099         //Log_info2("DIB_reclaimChild.%d update pointers with srcFrame->size = %d", __LINE__, srcFrame->size);
1100         //TRACE((&TR_MOD, "DIB_reclaimChild.%d update pointers\n", __LINE__));
1101         pBufConfig->head.pVoid = (Ptr) ((int)srcFrame->addr + srcFrame->size);
1103         // wrap, if necessary
1104         bufEnd = (int) pBufConfig->base.pVoid + pBufConfig->sizeofBuffer;
1105         if( (int) pBufConfig->head.pVoid >= bufEnd )
1106         {
1107             Log_info1("DIB_reclaimChild.%d wrap pointer", __LINE__);
1108             //TRACE((&TR_MOD, "DIB_reclaimChild.%d wrap pointer\n", __LINE__));
1109             pBufConfig->head.pVoid = (Ptr) ((int) pBufConfig->base.pVoid + (int) pBufConfig->head.pVoid - bufEnd);
1110         }
1111     }
1113     Log_info2("DIB_reclaimChild.%d exit with status = %d", __LINE__, status);
1114     //TRACE((&TR_MOD, "DIB_reclaimChild.%d exit with status = %d\n", __LINE__, status));
1116     return status;
1117 } // DIB_reclaimChild
1119 // -----------------------------------------------------------------------------
1120 // This function uses the local definition of frameLength and lengthofData in
1121 // pDevExt to request the next frame of data.
1123 Int DIB_requestFrame (DEV2_Handle device, PAF_InpBufConfig *pBufConfig)
1125     DIB_DeviceExtension    *pDevExt = (DIB_DeviceExtension *)device->object;
1126     int status = 0;
1129     // if in steady state then update tail pointer to indicate we are done, i.e. no
1130     // longer own, the last frame of data.
1131     if (pDevExt->running > 1)
1132         IncrementPtr (pBufConfig, &pBufConfig->pntr.pVoid, pBufConfig->lengthofData);
1134     switch (pDevExt->syncState) {
1135         case SYNC_PCM:
1136         case SYNC_PCM_FORCED:
1137                     
1138             if (pDevExt->sourceSelect == PAF_SOURCE_DSD1)
1139                 pDevExt->frameLength = 256;
1140             else if (pDevExt->sourceSelect == PAF_SOURCE_DSD2)
1141                 pDevExt->frameLength = 128;
1142             else if (pDevExt->sourceSelect == PAF_SOURCE_DSD3)
1143                 pDevExt->frameLength = 64;
1144             else
1145                 pDevExt->frameLength = pDevExt->pcmFrameLength;
1147             pDevExt->lengthofData = pBufConfig->stride*pDevExt->frameLength;
1148             pDevExt->frameLength  = pDevExt->lengthofData;        
1150             // note that the following issueChild
1151             // doesn't *fetch* the data which will next be consumed,
1152             // but rather *replenishes* what's about to be consumed
1153             status = DIB_FTABLE_issueChild (device, pBufConfig, pDevExt->lengthofData, 0);
1154             break;
1156         case SYNC_ONE:
1157             // for the first issue we need to set the tail pointer to the bitstream sync
1158             pBufConfig->pntr = pDevExt->pSync;
1159             IncrementPtr (pBufConfig, &pBufConfig->pntr.pVoid, pDevExt->headerSize);
1160             status = DIB_FTABLE_issueChild (device, pBufConfig, pDevExt->frameLength, 1);
1162             // HD codecs need extra time due to several factors
1163             //   time between first info call and starting output is non-negligible
1164             //   peak decoder MIPs
1165             //   reset time for decoders/ASPs
1166             if ((pDevExt->sourceProgram == PAF_SOURCE_DDP)   ||
1167                 (pDevExt->sourceProgram == PAF_SOURCE_DTSHD) ||
1168                 (pDevExt->sourceProgram == PAF_SOURCE_THD)   ||
1169                 (pDevExt->sourceProgram == PAF_SOURCE_DXP))
1170                 status = DIB_FTABLE_issueChild (device, pBufConfig, pDevExt->lengthofData, 0);
1172             pDevExt->syncState = SYNC_ONGOING;
1173             break;
1175         case SYNC_ONGOING:
1176             status = DIB_FTABLE_issueChild (device, pBufConfig, pDevExt->lengthofData, 0);
1177             break;
1179     } //switch
1181     // update bufConfig with info for use in next reclaim call
1182     // the interface to DIB is based on a single frame. So the amount
1183     // of data requested in this issue is assumed to be what is wanted in the next
1184     // reclaim.
1185     pBufConfig->frameLength  = pDevExt->frameLength;
1186     pBufConfig->lengthofData = pDevExt->lengthofData;
1187     // enable to inspect input buffer.
1188     // if (pDevExt->lengthofData > 512)
1189     //     asm( " SWBP 0" );  // breakpoint
1192     if (pDevExt->running < 3)
1193         pDevExt->running++;
1195     // Goal is to align timing so synchronized with forthcoming
1196     // "DIB_waitForData (... pDevExt->lengthofData);"
1197     // in DIB_reclaim(), servicing PAF_SIO_REQUEST_NEWFRAME, for PAF_SOURCE_PCM/DSD?.
1198     // ** need to revise above DSD handling so it works w/ this calc. **
1199     {
1200         int futureAvail = GetFutureAvail (pBufConfig);
1201         // GetFutureAvail() returns 0 if full buffer requested or if no requests outstanding
1202         // -- 0 (empty) can't be right interpretation here, on account of foregoing issueChild()
1203         if( ! futureAvail)
1204             futureAvail = pBufConfig->sizeofBuffer / pBufConfig->sizeofElement; // total words in buffer
1205         pDevExt->numSamplesExtra = (XDAS_Int16) (futureAvail - pDevExt->frameLength);
1206     }
1208     return status;
1209 } // DIB_requestFrame
1211 // -----------------------------------------------------------------------------
1213 Int DIB_reset (DEV2_Handle device, PAF_InpBufConfig *pBufConfig)
1215     DIB_DeviceExtension    *pDevExt = (DIB_DeviceExtension *)device->object;
1216     DEV2_Handle              pChild = (DEV2_Handle)&pDevExt->child;
1217     int status, numChan;
1220     //?? Do we need a shutdown to handle queue problems?
1221     // or are there no problems since we use one frame
1222     status = DEV2_idle (pChild, 1);
1223     if(status)
1224         return status;
1226     if (pBufConfig) {
1227         int sizeofStride;
1228         pBufConfig->pntr       = pBufConfig->base;
1229         pBufConfig->head       = pBufConfig->base;
1230         pBufConfig->futureHead = pBufConfig->base;
1232         pBufConfig->lengthofData = 0;
1234         //devices must? support 2byte words
1235         pBufConfig->sizeofElement = 2;
1236         status = SIO2_ctrl (pChild, (Uns)PAF_SIO_CONTROL_SET_WORDSIZE,pBufConfig->sizeofElement);
1237         if(status)
1238             return status;
1240         status = DEV2_ctrl (pChild, PAF_SIO_CONTROL_GET_NUMCHANNELS, (Arg) &numChan);
1241         if(status)
1242             return status;
1243         pBufConfig->stride = numChan;
1245         // compute and use *effective buffer size*
1246         sizeofStride = pBufConfig->sizeofElement*pBufConfig->stride;
1247         pBufConfig->sizeofBuffer = (pBufConfig->allocation)/sizeofStride*sizeofStride;  //GJ: Debug - Account for EDMA padding
1249         //hack -- save status context for use in close
1250         pDevExt->pInpBufStatus = pBufConfig->pBufStatus;
1251         pBufConfig->pBufStatus->lastFrameFlag = 0;
1253         pDevExt->bufConfig = *pBufConfig;
1254         pDevExt->pSync = pBufConfig->base;
1255     }
1257     pDevExt->syncState = SYNC_NONE;
1258     pDevExt->scanState = SCANNED_NONE;
1259     pDevExt->pcmTimeout = 0;
1260     pDevExt->deferredError = 0;
1262     pDevExt->numSamplesSinceDTS = 0;
1263     pDevExt->numSamplesExtra = 0;
1265     pDevExt->headerSize = 0;
1266     pDevExt->running = 0;
1268     return 0;
1269 } // DIB_reset
1271 // -----------------------------------------------------------------------------
1272 // Notes:
1273 //   1. The amount of data to be scanned will not result in a buffer wrap-around
1274 //   2. (1) is currently met from the two locations that call this function
1275 //          a. DIB_getSync
1276 //          b. DIB_reclaim (for PCM)
1277 //   3. We require that pTimeout != NULL since we dereference to make a const
1279 Int DIB_syncScan (DEV2_Handle device, PAF_InpBufConfig *pBufConfig, XDAS_UInt32 *pTimeout)
1281     DIB_DeviceExtension   * restrict pDevExt = (DIB_DeviceExtension *)device->object;
1282     MdInt * restrict pTail, * restrict pShadowTail, * restrict pSync;
1283     MdInt *pLocalTail, pc;
1284     XDAS_Int8   scanState;
1285     XDAS_UInt32 zeroCount;
1286     int stride, numLeft, i, datId;
1287     int status, foundDTS = 0;
1288     Uns scanCount, pageSize;
1289     PAF_SIO_IALG_Obj    *pObj = pDevExt->pSioIalg;
1290     PAF_SIO_IALG_Config *pAlgConfig = &pObj->config;
1291     const int timeoutChanged = (*pTimeout != 2 * pBufConfig->pBufStatus->unknownTimeout);
1292     MdInt DTSHDSubType;
1294     // .........................................................................
1296     // works for both SYNC_NONE and SYNC_PCM
1297     numLeft = min (*pTimeout, GetNumAvail(pBufConfig));
1299     pTail = pBufConfig->pntr.pMdInt;
1300     pShadowTail = pBufConfig->pntr.pMdInt;
1302     // if scratch buffer present then assume it is needed for paging
1303     pageSize = numLeft*pBufConfig->sizeofElement;
1305     Log_info3("DIB: Entered DIB_syncScan with pTail = 0x%x & numLeft = %d, timeout = %d", (xdc_IArg)pTail, numLeft, *pTimeout);
1308     if ((pAlgConfig->numRec > 1) && pAlgConfig->pMemRec[1].base && (pAlgConfig->pMemRec[1].size >= pageSize)) {
1309         pTail = pAlgConfig->pMemRec[1].base;
1310         datId = DAT_copy ((void *) pShadowTail, (void *) pTail, pageSize);
1311         DAT_wait (datId);
1312     }
1314     if (pBufConfig->sizeofElement == 4) {
1315         Log_info0("DIB: SyncScan - Inside pBufConfig->sizeofElement == 4");
1316         stride = 2;
1317         pTail += 1; // point at MSB
1318         pShadowTail += 1;
1319     }
1320     else
1321         stride = 1;
1323     // .........................................................................
1325     // scan until out of available data or a sync found
1326     scanCount = 0;
1327     zeroCount = pDevExt->zeroCount;
1328     scanState = pDevExt->scanState;
1329     pSync     = pDevExt->pSync.pMdInt;
1331     Log_info4("DIB: Entered DIB_syncScan with zeroCount = %d & scanState = %d, stride = %d, pSync = 0x%x", zeroCount, scanState, stride, (xdc_IArg)pSync);
1333     // scan until out of available data or a sync found
1334     for (i=0; i < numLeft; i++) {
1335         MdInt tail = pTail[i*stride];
1337         // assumes SCANNED_NONE = 0
1338         if (!scanState) {
1339             if (tail == IEC_PA) {
1340                 // since above code handles ongoing sync we are
1341                 //  safe to check for extended sync here. i.e.
1342                 //  two zeros before PA.
1343                 if (zeroCount >= 2) {
1344                     scanState = SCANNED_IEC_PA;
1345                     pSync = &pShadowTail[i*stride];
1346                 }
1347             }
1348             else if (tail == DTS14_SYNC_A) {
1349                 scanState = SCANNED_DTS14_SYNC_A;
1350                 pSync = &pShadowTail[i*stride];
1351             }
1352             else if (tail == DTS16_SYNC_A) {
1353                 scanState = SCANNED_DTS16_SYNC_A;
1354                 pSync = &pShadowTail[i*stride];
1355             }
1357             // limit count to prevent wrap around
1358             zeroCount = min (zeroCount+1,INT_MAX - 1);
1359             if (tail != 0x0000)
1360                 zeroCount = 0;
1362             // don't start counting until we get the first non-zero
1363             // sample while UNKNOWN. Note we don't have to worry
1364             // about the other scanCount increments since these
1365             // only occur after the first non-zero sample.
1366             //
1367             // so don't count unless
1368             //    . we are already started counting (in this call) ||
1369             //    . we started counting in an earlier scanForSync (timeout has changed) ||
1370             //    . the last sample was non-zero
1371             if (scanCount || (tail != 0x0000) || timeoutChanged)
1372             {
1373                 //Log_info3("DIB: DIB_syncScan scanCount = %d tail = %d timeoutChanged = %d", scanCount, tail, timeoutChanged);
1374                 scanCount += 1;
1375             }
1378             continue;
1379         }
1381         // ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
1383         switch (scanState) {
1385             case SCANNED_DTS16_SYNC_A:
1386                 if (tail == DTS16_SYNC_B) {
1387                     scanState = SCANNED_DTS16_SYNC_B;
1388                     scanCount += 1;
1389                 }
1390                 else
1391                     scanState = SCANNED_NONE;
1392                 break;
1394                 // wait for header data to get payload size via
1395                 // nblks/fsize
1396             case SCANNED_DTS16_SYNC_B:
1397                 // use extended sync
1399                 if ((short)(tail & 0xFC00) == DTS16_SYNC_C) {
1400                     scanState = SCANNED_DTS16_SYNC_C;
1401                     scanCount += 1;
1402                 }
1403                 else
1404                     scanState = SCANNED_NONE;
1405                 break;
1407                 // `````````````````````````````````````````````````````````````````````````
1408                 // check for 2nd word of DTS-14 sync
1409             case SCANNED_DTS14_SYNC_A:
1410                 if (tail == DTS14_SYNC_B) {
1411                     scanState = SCANNED_DTS14_SYNC_B;
1412                     scanCount += 1;
1413                 }
1414                 else
1415                     scanState = SCANNED_NONE;
1416                 break;
1418                 // check for 3rd word of DTS-14 sync
1419             case SCANNED_DTS14_SYNC_B:
1420                 // if here then looking for extended 38 bit sync
1421                 if ((short)(tail & 0xFFF0) == DTS14_SYNC_C) {
1422                     scanState = SCANNED_DTS14_SYNC_C;
1423                     scanCount += 1;
1424                 }
1425                 else
1426                     scanState = SCANNED_NONE;
1427                 break;
1429                 // wait for header data to get payload size via
1430                 //   nblks/fsize
1431             case SCANNED_DTS14_SYNC_C:
1432                 scanState = SCANNED_DTS14_SYNC_D;
1433                 scanCount += 1;
1434                 break;
1436                 // `````````````````````````````````````````````````````````````````````````
1437                 // if here then all of header is buffered
1438             case SCANNED_DTS16_SYNC_C:
1439             case SCANNED_DTS14_SYNC_D:
1440                 // update sync to point at beginning of DTS header as syncScanDTS uses this info
1441                 pDevExt->scanState    = scanState;
1442                 pDevExt->pSync.pMdInt = pSync;
1443                 status = DIB_FTABLE_syncScanDTS (device, pBufConfig, pTimeout, (XDAS_UInt16 *) &pShadowTail[i*stride]);
1444                 scanState = pDevExt->scanState;
1445                 if (status)
1446                     return status;
1447                 foundDTS = 1;
1448                 if (pDevExt->syncState == SYNC_ONE)
1449                     goto syncScanExit;
1450                 break;
1452                 // `````````````````````````````````````````````````````````````````````````
1454                 // note that the round about detection of IEC only
1455                 // happens for the first sync so the extra states are OK.
1456             case SCANNED_IEC_PA:
1457                 if (tail == IEC_PB) {
1458                     scanState = SCANNED_IEC_PB;
1459                     scanCount += 1;
1460                     Log_info0("DIB: SyncScan Inside case - SCANNED_IEC_PA - if path");
1461                 }
1462                 else
1463                 {
1464                     Log_info0("DIB: SyncScan Inside case - SCANNED_IEC_PA - else path");
1465                     scanState = SCANNED_NONE;
1466                 }
1467                 break;
1469             case SCANNED_IEC_PB:
1470                 // Update scanCount here since, at this point, we are confident that
1471                 // this is a proper IEC stream. Regardless if we ignore it our not.
1472                 // Therefore we want to properly signal that this data has been scanned.
1473                 scanCount += 1;
1475                 // check for IEC pause packets at this time and if required ignore them.
1476                 // By construction we are guaranteed to have tail=PC at this time.
1477                 if ((pBufConfig->pBufStatus->mode == MODE_NO_ZERORUNRESTART) ||
1478                     (pBufConfig->pBufStatus->mode == MODE_NO_ZERORUN)) {
1479                     MdInt pc = tail & 0x1F;
1481                     if ((pc == 0) || (pc == 3)) {
1482                         scanState = SCANNED_NONE;
1483                         break;
1484                     }
1485                 }
1487                 scanState = SCANNED_IEC_PC;
1488                 break;
1490             case SCANNED_IEC_PC:
1491                 pLocalTail = pSync;
1492                 IncrementPtr (pBufConfig, (Ptr *)  &pLocalTail, 2);
1493                 pc = *pLocalTail & 0x1F;
1494                 pDevExt->headerSize = IEC_HEADER_SIZE;
1496                 Log_info0("DIB: Sync Scan - Inside case: SCANNED_IEC_PC");
1497                 // Handle DTSHD subtype (LBR)
1498                 if (pc == 0x11) {
1499                     pDevExt->headerSize +=6;
1500                     DTSHDSubType = (*pLocalTail & 0x700)>>8;
1501                 }
1502                 // DDP or THD
1503                 if (pc == 21 || pc ==22) {
1504                     TRACE((&TR_MOD, "Dolby: useIECSubType is 0x%x.\n", pBufConfig->pBufStatus->useIECSubType));
1505                     if (pBufConfig->pBufStatus->useIECSubType == 1) {
1506                         unsigned char IECSubType = *pLocalTail & 0x60;
1507                         TRACE((&TR_MOD, "Dolby: IECSubType is 0x%x.\n", IECSubType));
1508                         if (IECSubType != 0) {
1509                             pDevExt->sourceProgram = PAF_SOURCE_UNKNOWN;
1510                             pDevExt->frameLength = 0;
1511                         }
1512                     }
1513                 }
1514                 // don't know how to support other types
1515                 if (pc > 22)
1516                 {
1517                     Log_info1("DIB:  Unknown IEC type 0x%x encountered.\n", pc);
1518                     return DIBERR_SYNC;
1519                 }
1521                 pDevExt->syncState = SYNC_ONE;
1522                 pBufConfig->pntr.pMdInt = pSync;
1523                 pDevExt->sourceProgram = iecPafSource[pc];
1525                 Log_info2("source is %d.  pc is %d.", iecPafSource[pc], pc);
1526                 //TRACE((&TR_MOD, "source is %d.  pc is %d.\n", iecPafSource[pc], pc));
1527 #if 0 //No need to differentiate LBR subtype from DTSHD as DXP source program as LBR is handled inside DTSX decoder like other subtypes.
1528                 if (pc == 0x11 && DTSHDSubType == 3 && (PAF_ASP_sampleRateHzTable[pBufConfig->pBufStatus->sampleRateStatus][PAF_SAMPLERATEHZ_STD] <=48000.0))
1529                     pDevExt->sourceProgram = PAF_SOURCE_DXP;    // LBR is 23
1530 #endif             
1531                 pDevExt->frameLength = pDevExt->pIECFrameLength[pc];
1532                 pDevExt->lengthofData = pDevExt->frameLength;
1533                 if (pc == 1)
1534                     pDevExt->frameLength = 4288;
1535                 else if (pc == 0x11) {
1536                     pDevExt->frameLength = (pDevExt->pIECFrameLength[pc] << DTSHDSubType);
1537                     pDevExt->lengthofData = pDevExt->frameLength;
1538                 }
1540                 goto syncScanExit;
1542         } // switch
1543     } // for
1545     // .............................................................................
1547 syncScanExit:
1548     Log_info4("DIB inside syncScanExit.  pTimeout = %d, scanCount = %d, zeroCount = %d, numLeft = %d", *pTimeout,scanCount, zeroCount, numLeft );
1549     pDevExt->zeroCount    = zeroCount;
1550     pDevExt->scanState    = scanState;
1551     pDevExt->pSync.pMdInt = pSync;
1553     if (pDevExt->zeroCount >= 2 * pBufConfig->pBufStatus->zeroRunTrigger)
1554         pBufConfig->pBufStatus->zeroRun = 1;
1555     else
1556         pBufConfig->pBufStatus->zeroRun = 0;
1558     // If detected an initial DTS sync in a previous buffer then add the
1559     // number of samples in this buffer to the tally.
1560     // TODO: should we add numLeft instead of lengthofData?
1561     if (!foundDTS && pDevExt->numSamplesSinceDTS)
1562         pDevExt->numSamplesSinceDTS += pBufConfig->lengthofData;
1564     if (*pTimeout > scanCount)
1565         *pTimeout -= scanCount;
1566     else {
1567         *pTimeout = 0;
1568         return 0;
1569     }
1571     // This flushes the current scanned buffer if a sync is not found
1572     // Note that this code is not executed when *pTimeout = 0. 
1573     // TODO: should this be moved elsewhere. Like in requestFrame?
1574     //       seems like this should be done in request frame for continuous modes
1575     //       and in getSync for traditional modes.
1576     //       What does it mean that this is not executed when we have timed out to PCM
1577     if (pDevExt->syncState == SYNC_NONE || pDevExt->syncState == SYNC_AUTO) {
1578         IncrementPtr (pBufConfig, (Ptr *) &pBufConfig->pntr.pMdInt, numLeft);
1579         return 0;
1580     }
1582     return 0;
1583 } // DIB_syncScan
1585 // -----------------------------------------------------------------------------
1586 // Assumes scanState is SCANNED_DTS16_SYNC_C or SCANNED_DTS14_SYNC_D
1588 Int DIB_syncScanDTS (DEV2_Handle device, PAF_InpBufConfig *pBufConfig, XDAS_UInt32 *pTimeout, XDAS_UInt16 *pHeaderEnd)
1590     DIB_DeviceExtension  *pDevExt = (DIB_DeviceExtension *)device->object;
1591     Int sourceProgram = (pDevExt->scanState == SCANNED_DTS14_SYNC_D) ? PAF_SOURCE_DTS14  : PAF_SOURCE_DTS16;
1592     float sampleRate = PAF_ASP_sampleRateHzTable[pBufConfig->pBufStatus->sampleRateStatus][PAF_SAMPLERATEHZ_STD];
1593     MdInt *pLocalTail, pc, pd;
1594     int nblks;
1597     // compute repetition rate as predicted by DTS header
1598     pLocalTail = pDevExt->pSync.pMdInt;
1599     IncrementPtr (pBufConfig, (Ptr *) &pLocalTail, 2);
1600     pc = *pLocalTail;
1601     if (pDevExt->scanState == SCANNED_DTS16_SYNC_C)
1602         nblks = (pc & 0x01FC) >> 2;
1603     else {
1604         IncrementPtr (pBufConfig, (Ptr *) &pLocalTail, 1);
1605         pd = *pLocalTail;
1606         nblks = (pc & 0x7) << 4;
1607         nblks |= (pd & 0x3C00) >> 10;
1608     }
1610     // if samplerate > 44.1k and DTS16 bit CD then report as DTS-DVD
1611     // this is a work around to the possibility that DTS-DVD is being
1612     // sent but, due to the variance in input recording, we may have
1613     // missed the IEC header. This is predicated on the enable register
1614     if (pBufConfig->pBufStatus->reportDTS16AsDTSForLargeSampleRate &&
1615         (sampleRate > 44100) && (sourceProgram == PAF_SOURCE_DTS16))
1616         sourceProgram = PAF_SOURCE_DTS;
1618     // point at LSB, if neceesary, so that space calculation is correct
1619     if (pBufConfig->sizeofElement == 4)
1620         pHeaderEnd -= 1;
1622     // If in PCM mode then require double sync, at an appropriate spacing,
1623     // in order to determine DTS validity.
1624     if (pDevExt->syncState == SYNC_PCM) {
1625         int diff;
1627         // If we have started counting, i.e. found a previous sync,
1628         // then compute sync spacing.
1629         if (pDevExt->numSamplesSinceDTS) {
1630             // determine distance since last sync
1631             //    pHeaderEnd, which points at the end of the DTS header, is guaranteed
1632             //    to be in the active buffer. Whereas the pointer to the beginning of the header (pSync)
1633             //    may have occured in the previous buffer.
1634             diff = ((int) pHeaderEnd - (int) pBufConfig->pntr.pVoid);
1635             if (diff < 0)
1636                 diff += pBufConfig->sizeofBuffer;
1637             diff /= pBufConfig->sizeofElement;
1638             diff += pDevExt->numSamplesSinceDTS;
1640             // if spacing incorrect then reset sample count to
1641             // force next conditional to be true.
1642             if (diff != (nblks+1)*32*2)
1643                 pDevExt->numSamplesSinceDTS = 0;
1644         }
1646         // If this is the 1st sync detected or if this is the second sync
1647         // but the spacing between DTS syncs did not match that predicted by
1648         // NBLKS, then this is not DTS data. Therefore the previous DTS sync
1649         // word was not valid and so it is safe to reset the count based on
1650         // this secondary sync word. This latter sync may or may not be valid;
1651         // we don't know yet. In both cases init sync spacing count, reset
1652         // scan state, and continue. Note that there is a positive, albeit
1653         // quite small, probability of falsing in a pathological case where
1654         // the PCM data, interpreted as a DTS header and used to compute NBLKS,
1655         // actually matches the fake DTS syncs in the PCM file.
1656         if (!pDevExt->numSamplesSinceDTS) {
1657             diff = (int) pBufConfig->head.pVoid - (int) pHeaderEnd;
1658             if (diff <= 0)
1659                 diff += pBufConfig->sizeofBuffer;
1660             diff /= pBufConfig->sizeofElement;
1661             pDevExt->numSamplesSinceDTS = diff;
1662             pDevExt->scanState = SCANNED_NONE;
1663             return 0;
1664         }
1665     } //SYNC_PCM
1667     pDevExt->lengthofData = (nblks+1)*32*2;
1668     if (pDevExt->scanState == SCANNED_DTS16_SYNC_C)
1669         pDevExt->frameLength = pDevExt->lengthofData + 4;
1670     else
1671         pDevExt->frameLength = pDevExt->lengthofData + 6;
1673     pDevExt->syncState = SYNC_ONE;
1674     pBufConfig->pntr = pDevExt->pSync;
1675     pDevExt->sourceProgram = sourceProgram;
1677     return 0;
1678 } //DIB_syncScanDTS
1680 // -----------------------------------------------------------------------------
1681 // This function is responsible for verifying bitstream sync (if applicable) and
1682 // configuring the sizes of the next frame of data.
1684 Int DIB_initFrame (DEV2_Handle device, PAF_InpBufConfig *pBufConfig)
1686     DIB_DeviceExtension  * restrict pDevExt = (DIB_DeviceExtension *) device->object;
1687     MdInt * restrict pTail;
1688     MdInt pa, pb, pc;
1689     unsigned char DTSHDSubType;
1690     PAF_UnionPointer     ac3SearchPtr;
1693     // MID 810
1694     // TODO: is this needed anymore? can we combine above and this?
1695     // I don't think this is needed since pSync is guaranteed to be
1696     // valid under all cases where this function is called.
1697     if (!(pDevExt->scanState == SCANNED_DTS14_SYNC_D ||
1698           pDevExt->scanState == SCANNED_DTS16_SYNC_C ||
1699           pDevExt->scanState == SCANNED_IEC_PC ))
1700         return 0;
1702     // minimum possible distance from current IEC sync to next is 1856 words
1703     // capture this here before we update pSync following
1704     ac3SearchPtr = pDevExt->pSync; 
1706     // for steady state compute expected sync location
1707     if (pDevExt->syncState == SYNC_ONGOING) 
1708         IncrementPtr (pBufConfig, &pDevExt->pSync.pVoid, pBufConfig->lengthofData);
1710     pTail = pDevExt->pSync.pMdInt;
1711     pa = *pTail;
1712     IncrementPtr (pBufConfig, (Ptr *) &pTail, 1);
1713     pb = *pTail;
1714     IncrementPtr (pBufConfig, (Ptr *) &pTail, 1);
1715     pc = *pTail;
1716     IncrementPtr (pBufConfig, (Ptr *) &pTail, 1);
1718     switch (pDevExt->scanState) {
1719         // ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
1721         case SCANNED_DTS14_SYNC_D:
1722             // check sync (extended sync checked above for 1st sync)
1723             if ((pa != DTS14_SYNC_A) || (pb != DTS14_SYNC_B) || ((pc & 0xFC00) != (DTS14_SYNC_C & 0xFC00)))
1724                 return DIBERR_SYNC;
1725             break;
1727             // ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
1729         case SCANNED_DTS16_SYNC_C:
1730             // check sync (extended sync checked above for 1st sync)
1731             if ((pa != DTS16_SYNC_A) || (pb != DTS16_SYNC_B))
1732                 return DIBERR_SYNC;
1733             break;
1735             // ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
1737         case SCANNED_IEC_PC:
1738             // check for sync
1739             //    special handling for AC3 variable bit rate (VBR)
1740             //       start looking for sync at max payload sync location and
1741             //       scan forward. Note that getSync() has waited for
1742             //       sufficient data to arrive so that we can determine reliably
1743             //       the presence or absence of a correct sync.
1745             if ((pa != IEC_PA) || (pb != IEC_PB)) {
1746                 PAF_SIO_IALG_Obj    *pObj = pDevExt->pSioIalg;
1747                 PAF_SIO_IALG_Config *pAlgConfig = &pObj->config;
1748                 int scan1, scan2, searchIdx, datId;
1749                 const int bufEnd = (int) pBufConfig->base.pVoid + pBufConfig->sizeofBuffer;
1752                 // only extend IEC search in the case of AC3
1753                 if (pDevExt->sourceProgram != PAF_SOURCE_AC3)
1754                     return DIBERR_SYNC;
1756                 // move search ptr to earliest possible location of next sync
1757                 IncrementPtr (pBufConfig, &ac3SearchPtr.pVoid, 1856);
1759                 // compute number of samples between earliest possible sync location
1760                 // (ac3SearchPtr) and latest possible sync location (head)
1761                 scan1 = (int) pBufConfig->head.pVoid - (int) ac3SearchPtr.pVoid;
1762                 if (scan1 < 0) {
1763                     // here if search will wrap around so split search into two
1764                     // halves to accomodate circular buffer
1765                     scan1 = bufEnd - (int) ac3SearchPtr.pVoid;
1766                     scan2 = (int) pBufConfig->head.pVoid - (int) pBufConfig->base.pVoid;
1767                 }
1768                 else
1769                     scan2 = 0;
1771                 // page if necessary (assume so if second memRec present)
1772                 if (pAlgConfig->numRec > 1) {
1773                     // if invalid buffer or if page buffer not big enough for either split then error
1774                     if (!pAlgConfig->pMemRec[1].base ||
1775                         (pAlgConfig->pMemRec[1].size < max(scan1,scan2)))
1776                         return DIBERR_UNSPECIFIED;
1778                     pTail = (MdInt *) pAlgConfig->pMemRec[1].base;
1779                     datId = DAT_copy (ac3SearchPtr.pVoid, (void *) pTail, scan1);
1780                     DAT_wait (datId);
1781                 }
1782                 else
1783                     pTail = ac3SearchPtr.pMdInt;
1785                 // convert to number of words
1786                 scan1 /= pBufConfig->sizeofElement;
1788                 // if non-zero must be IEC header, otherwise sync error
1789                 // update pointer after check so that it remains
1790                 // pointed at first non-zero word when breaking
1791                 searchIdx = 0;
1792                 while (scan1--) {
1793                     if (*pTail != 0) {
1794                         // force skip of any possible split scan since we found non-zero word
1795                         scan2 = 0;
1796                         break;
1797                     }
1798                     *pTail++;
1799                     searchIdx++;
1800                 }
1802                 // perform second half of circular buffer search if necessary
1803                 if (scan2) {
1804                     // page if necessary, note no need to check valid buffer
1805                     // or space since this is ensured in first scan
1806                     if (pAlgConfig->numRec > 1) {
1807                         pTail = (MdInt *) pAlgConfig->pMemRec[1].base;
1808                         datId = DAT_copy (pBufConfig->base.pVoid, (void *) pTail, scan2);
1809                         DAT_wait (datId);
1810                     }
1811                     else
1812                         pTail = pBufConfig->base.pMdInt;
1814                     // convert to number of words
1815                     scan2 /= pBufConfig->sizeofElement;
1817                     while (scan2--) {
1818                         if (*pTail != 0)
1819                             break;
1820                         *pTail++;
1821                         searchIdx++;
1822                     }
1823                 }
1825                 // if using paging buffer then translate search pointer back into circular buffer
1826                 if (pAlgConfig->numRec > 1) {
1827                     pTail = ac3SearchPtr.pMdInt;
1828                     IncrementPtr (pBufConfig, (Ptr *) &pTail, searchIdx);
1829                 }
1831                 // update sync in expection of success, if it is not a sync then no
1832                 // harm since it will be ignored then reset
1833                 pDevExt->pSync.pMdInt = pTail;
1835                 // above search only scans for the first non-zero word.
1836                 // here is common check to make sure that non-zero data is an IEC sync.
1837                 pa = *pTail;
1838                 IncrementPtr (pBufConfig, (Ptr *) &pTail, 1);
1839                 pb = *pTail;
1840                 IncrementPtr (pBufConfig, (Ptr *) &pTail, 1);
1841                 pc = *pTail;
1842                 IncrementPtr (pBufConfig, (Ptr *) &pTail, 1);
1843                 if ((pa != IEC_PA) || (pb != IEC_PB))
1844                     return DIBERR_SYNC;
1845             }
1847             // compute possible DTSHD sub type before masking pc
1848             DTSHDSubType = (pc & 0x700) >> 8;
1850             // mask pc to get data type only
1851             pc = pc & 0x1F;
1853             // don't know how to support other types
1854             // this also ensures that the below array access is bounded
1855             if (pc > 22)
1856                 return DIBERR_SYNC;
1858             // continuing frame must be same as current type otherwise
1859             // we return error to force reset of decode and input
1860             // classification state machines
1861             if (pDevExt->sourceProgram != iecPafSource[pc]) {
1862                 if (DTSHDSubType == 3 &&
1863                     (PAF_ASP_sampleRateHzTable[pBufConfig->pBufStatus->sampleRateStatus][PAF_SAMPLERATEHZ_STD] <= 48000.0))  {
1864                     if (pDevExt->sourceProgram != PAF_SOURCE_DXP)
1865                         return DIBERR_SYNC;
1866                 }
1867                 else
1868                     return DIBERR_SYNC;
1869             }
1870             break;
1872             // ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
1873     } //switch
1875     return 0;
1876 } // DIB_initFrame
1878 // -----------------------------------------------------------------------------
1880 Int DIB_waitForData (DEV2_Handle device, PAF_InpBufConfig *pBufConfig, XDAS_UInt32 count )
1882     DIB_DeviceExtension  *pDevExt = (DIB_DeviceExtension *) device->object;
1883     DEV2_Handle            pChild = (DEV2_Handle) &pDevExt->child;
1884     Int status, lock;
1886     Log_info2("DIB_waitForData.%d count = %d", __LINE__, count);
1887     //TRACE((&TR_MOD, "DIB_waitForData.%d count = %d\n", __LINE__, count));
1889     while (GetNumAvail(pBufConfig) < count) {
1890         PAF_SIO_InputStatus inputStatus;
1892         // query underlying device for lock status & check lock override register
1893         // dont wait without lock
1894         status = SIO2_ctrl (pChild, (Uns)PAF_SIO_CONTROL_GET_INPUT_STATUS, (Arg) &inputStatus);
1895         if (status)
1896         {
1897             Log_info2("DIB_waitForData.%d SIO2_ctrl() returned %d", __LINE__, status);
1898             //TRACE((&TR_MOD, "DIB_waitForData.%d SIO2_ctrl() returned %d\n", __LINE__, status));
1899             return status;
1900         }
1901         lock = inputStatus.lock;
1902 #ifndef IGNORE_LOCK_OVERRIDE
1903         if ((pBufConfig->pBufStatus->lockOverride & (XDAS_Int8)0x80) == 0)
1904         {
1905             Log_info1("DIB_waitForData.%d lock = lockOverride\n", __LINE__);
1906             //TRACE((&TR_MOD, "DIB_waitForData.%d lock = lockOverride\n", __LINE__));
1907             lock = pBufConfig->pBufStatus->lockOverride;
1908         }
1909 #endif
1910         if (!lock)
1911         {
1912             Log_info1("DIB_waitForData.%d no lock, return DIBERR_SYNC\n", __LINE__);
1913             //TRACE((&TR_MOD, "DIB_waitForData.%d no lock, return DIBERR_SYNC\n", __LINE__));
1914             return DIBERR_SYNC;
1915         }
1916         // check that decoding still requested -- allows for status
1917         // register to be updated via IOS to cancel autoProcessing
1918         if (pDevExt->pDecodeStatus) {
1919             if (pDevExt->pDecodeStatus->sourceSelect == PAF_SOURCE_NONE)
1920             {
1921                 Log_info1("DIB_waitForData.%d sourceSelect is NONE, return DIBERR_SYNC", __LINE__);
1922                 //TRACE((&TR_MOD, "DIB_waitForData.%d sourceSelect is NONE, return DIBERR_SYNC\n", __LINE__));
1923                 return DIBERR_SYNC;
1924             }
1925         }
1927         Log_info1("DIB_waitForData.%d calling DIB_FTABLE_reclaimChild()", __LINE__);
1928         //TRACE((&TR_MOD, "DIB_waitForData.%d calling DIB_FTABLE_reclaimChild()\n", __LINE__));
1929         status = DIB_FTABLE_reclaimChild (device, pBufConfig);
1930         if(status)
1931         {
1932             Log_info2("DIB_waitForData.%d DIB_FTABLE_reclaimChild() returned %d", __LINE__, status);
1933             //TRACE((&TR_MOD, "DIB_waitForData.%d DIB_FTABLE_reclaimChild() returned %d\n", __LINE__, status));
1934             return status;
1935         }
1936     }
1938     return 0;
1939 } // DIB_waitForData
1941 // -----------------------------------------------------------------------------
1942 #ifdef IEC_ENCODE
1944 // FS9 only supports PCM input so return error if not PCM.
1946 Int DIB_requestFrame_957 (DEV2_Handle device, PAF_InpBufConfig *pBufConfig)
1948     DIB_DeviceExtension    *pDevExt = (DIB_DeviceExtension *) device->object;
1949     int i, head, tail, avail, status;
1952     if (pDevExt->sourceProgram != PAF_SOURCE_PCM)
1953         return DIBERR_SYNC;
1955     // if in steady state then update tail pointer to indicate we are done, i.e. no
1956     // longer own, the last frame of data. 
1957     if (pDevExt->running > 1)
1958         IncrementPtr (pBufConfig, &pBufConfig->pntr.pVoid, pBufConfig->lengthofData);
1960     pDevExt->lengthofData = pBufConfig->stride*pDevExt->pcmFrameLength;
1961     pDevExt->frameLength  = pDevExt->lengthofData;        
1963     // note that due to MID 1037 it is required to check the return status after this call
1964     status = DIB_FTABLE_issueChild (device, pBufConfig, pDevExt->lengthofData, 0);
1965     if (status)
1966         return status;
1968     // add extra input delay to account for peak encoder mips
1969     for (i=0; i < 4; i++) {
1970         head = (int) pBufConfig->futureHead.pVoid;
1971         tail = (int) pBufConfig->pntr.pVoid;
1972         // compute how much data we have including outstanding requests
1973         if (head >= tail)
1974             avail = head - tail;
1975         else
1976             avail = head - tail + pBufConfig->sizeofBuffer;
1978         // convert to words
1979         avail /= pBufConfig->sizeofElement;
1980         if (avail < 4*pBufConfig->lengthofData) {
1981             status = DIB_FTABLE_issueChild (device, pBufConfig, pBufConfig->lengthofData, 0);
1982             if (status)
1983                 return status;
1984         }
1985     }
1987     pBufConfig->frameLength  = pDevExt->frameLength;
1988     pBufConfig->lengthofData = pDevExt->lengthofData;
1990     if (pDevExt->running < 3)
1991         pDevExt->running++;
1993     return 0;
1994 } // DIB_requestFrame_957
1996 #endif /* IEC_ENCODE */
1998 // -----------------------------------------------------------------------------
2000 #ifdef DSD_OVER_SPDIF
2002 Int DIB_requestFrame_patch (DEV2_Handle device, PAF_InpBufConfig *pBufConfig )
2004     DIB_DeviceExtension    *pDevExt = (DIB_DeviceExtension *)device->object;
2005     int status;
2007     status = DIB_requestFrame (device, pBufConfig);
2008     // For testing DSD over SPDIF i.e. 1 pin vs actual over 6 pin
2009     pDevExt->numSamplesExtra += pDevExt->lengthofData;
2010     pDevExt->lengthofData *=6;
2011     pDevExt->numSamplesExtra -= pDevExt->lengthofData;
2013     return status;
2014 } // DIB_requestFrame
2016 Int DIB_getSync_patch (DEV2_Handle device, PAF_InpBufConfig *pBufConfig )
2018     DIB_DeviceExtension   *pDevExt = (DIB_DeviceExtension *)device->object;
2019     DEV2_Handle             pChild = (DEV2_Handle)&pDevExt->child;
2020     int status;
2022     status=DIB_getSync (device, pBufConfig );
2023     if(status)
2024         return status;
2026     pBufConfig->sizeofElement = 2;
2027     status = SIO2_ctrl (pChild,(Uns)PAF_SIO_CONTROL_SET_WORDSIZE,pBufConfig->sizeofElement);
2028     if (status)
2029         return status;
2031     // compute and use *effective buffer size*
2032     {
2033         int sizeofStride = pBufConfig->sizeofElement*pBufConfig->stride;
2034         pBufConfig->sizeofBuffer = pBufConfig->allocation/sizeofStride*sizeofStride;
2035     }
2036     //..........................................................................
2038     return 0;
2039 } // DIB_getSync_patch
2041 #endif /* DSD_OVER_SPDIF */
2043 // -----------------------------------------------------------------------------