Ejemplo n.º 1
0
/******************************************************************************
 * gst_tiaudenc1_codec_stop
 *     Release codec engine resources
 *****************************************************************************/
static gboolean gst_tiaudenc1_codec_stop (GstTIAudenc1  *audenc1)
{
    if (audenc1->circBuf) {
        GstTICircBuffer *circBuf;

        GST_LOG("freeing cicrular input buffer\n");

        circBuf                = audenc1->circBuf;
        audenc1->circBuf       = NULL;
        gst_ticircbuffer_unref(circBuf);
    }

    if (audenc1->hOutBufTab) {
        GST_LOG("freeing output buffers\n");
        gst_tidmaibuftab_unref(audenc1->hOutBufTab);
        audenc1->hOutBufTab = NULL;
    }

    if (audenc1->hAe) {
        GST_LOG("closing audio encoder\n");
        Aenc1_delete(audenc1->hAe);
        audenc1->hAe = NULL;
    }

    if (audenc1->hEngine) {
        GST_LOG("closing codec engine\n");
        Engine_close(audenc1->hEngine);
        audenc1->hEngine = NULL;
    }

    return TRUE;
}
Ejemplo n.º 2
0
DvevmStRetCode
dvtb_ceClose(DvevmStEngineInfo *ce)
{
	DVTBASSERT(ce != NULL);
	DVTBASSERT(ce->hdl != NULL);

	Engine_close(ce->hdl);
	return DVEVM_ST_SUCCESS;
}
Ejemplo n.º 3
0
/*
 *  ======== ceapp_exit ========
 */
void ceapp_exit()
{
    /* teardown the codecs and the engine */
    if (decHandle != NULL) {
        SPHDEC1_delete(decHandle);
        traceDump(ceHandle);
    }
    if (ceHandle != NULL) {
        Engine_close(ceHandle);
    }
}
Ejemplo n.º 4
0
DvevmStRetCode
dvtb_ceDeInit(Engine_Handle *hdl)
{
	if (hdl == NULL)
	{
		SYS_ERROR("Invalid Engine Handle\n");
		return DVEVM_ST_FAIL;
	}

	Engine_close((*hdl));
	hdl = NULL;
	return DVEVM_ST_SUCCESS;
}
Ejemplo n.º 5
0
int codecEngineClose(CodecEngine* _ce)
{
  if (_ce == NULL)
    return EINVAL;

  if (_ce->m_handle == NULL)
    return EALREADY;

  Engine_close(_ce->m_handle);
  _ce->m_handle = NULL;

  return 0;
}
Ejemplo n.º 6
0
/*
 *  ======== ceapp_exit ========
 */
void ceapp_exit()
{
    /* teardown the codecs and the engine */
    if (encHandle != NULL) {
        VIDENC_delete(encHandle);
    }
    if (decHandle != NULL) {
        VIDDEC_delete(decHandle);
    }
    TraceUtil_stop();  /* close tracing thread */
    if (ceHandle != NULL) {
        Engine_close(ceHandle);
    }

    /* clean up Codec Engine */
    CERuntime_exit();
}
Ejemplo n.º 7
0
static void
engine_close (GstDucatiVidDec * self)
{
  if (self->engine) {
    Engine_close (self->engine);
    self->engine = NULL;
  }

  if (self->params) {
    dce_free (self->params);
    self->params = NULL;
  }

  if (self->dynParams) {
    dce_free (self->dynParams);
    self->dynParams = NULL;
  }

  if (self->status) {
    dce_free (self->status);
    self->status = NULL;
  }

  if (self->inBufs) {
    dce_free (self->inBufs);
    self->inBufs = NULL;
  }

  if (self->outBufs) {
    dce_free (self->outBufs);
    self->outBufs = NULL;
  }

  if (self->inArgs) {
    dce_free (self->inArgs);
    self->inArgs = NULL;
  }

  if (self->outArgs) {
    dce_free (self->outArgs);
    self->outArgs = NULL;
  }
}
Ejemplo n.º 8
0
/******************************************************************************
 * speechThrFxn
 ******************************************************************************/
Void *speechThrFxn(Void *arg)
{
    SpeechEnv              *envp                = (SpeechEnv *) arg;
    SPHDEC1_Params          defaultParams       = Sdec1_Params_DEFAULT;
    SPHDEC1_DynamicParams   defaultDynParams    = Sdec1_DynamicParams_DEFAULT;
    Void                   *status              = THREAD_SUCCESS;
    Sound_Attrs             sAttrs              = Sound_Attrs_MONO_DEFAULT;
    Loader_Attrs            lAttrs              = Loader_Attrs_DEFAULT;
    Buffer_Attrs            bAttrs              = Buffer_Attrs_DEFAULT;
    Sdec1_Handle            hSd1                = NULL;
    Sound_Handle            hSound              = NULL;
    Loader_Handle           hLoader             = NULL;
    Engine_Handle           hEngine             = NULL;
    Buffer_Handle           hOutBuf             = NULL;
    SPHDEC1_Params         *params;
    SPHDEC1_DynamicParams  *dynParams;
    Buffer_Handle           hInBuf;

    /* Open the codec engine */
    hEngine = Engine_open(envp->engineName, NULL, NULL);

    if (hEngine == NULL) {
        ERR("Failed to open codec engine %s\n", envp->engineName);
        cleanup(THREAD_FAILURE);
    }

    /* Create the sound device */
    sAttrs.sampleRate = 8000;
    sAttrs.mode = Sound_Mode_OUTPUT;
    sAttrs.leftGain  = 127;
    sAttrs.rightGain = 127;
    sAttrs.bufSize   = 128;
    hSound = Sound_create(&sAttrs);

    if (hSound == NULL) {
        ERR("Failed to create audio device\n");
        cleanup(THREAD_FAILURE);
    }

    /* Set the sample rate for the user interface */
    gblSetSamplingFrequency(sAttrs.sampleRate);

    /* Use supplied params if any, otherwise use defaults */
    params = envp->params ? envp->params : &defaultParams;
    dynParams = envp->dynParams ? envp->dynParams : &defaultDynParams;

    /* Create the speech decoder */
    hSd1 = Sdec1_create(hEngine, envp->speechDecoder, params, dynParams);

    if (hSd1 == NULL) {
        ERR("Failed to create speech decoder: %s\n", envp->speechDecoder);
        cleanup(THREAD_FAILURE);
    }

    /*
     * Make the output buffer size twice the size of what the codec needs
     * as the codec needs mono and the Sound module converts the decoded
     * mono samples to stereo before writing to the device driver.
     */
    hOutBuf = Buffer_create(OUTBUFSIZE, &bAttrs);

    if (hOutBuf == NULL) {
        ERR("Failed to allocate output buffer\n");
        cleanup(THREAD_FAILURE);
    }

    /* How much encoded data to feed the codec each process call */
    lAttrs.readSize = INBUFSIZE;

    /* Make the total ring buffer larger */
    lAttrs.readBufSize = lAttrs.readSize * 512;

    /* Create the file loader for reading encoded data */
    hLoader = Loader_create(envp->speechFile, &lAttrs);

    if (hLoader == NULL) {
        ERR("Failed to create loader\n");
        cleanup(THREAD_FAILURE);
    }

    /* Signal that initialization is done and wait for other threads */
    Rendezvous_meet(envp->hRendezvousInit);

    /* Prime the file loader */
    Loader_prime(hLoader, &hInBuf);

    while (!gblGetQuit()) {
        /* Pause processing? */
        Pause_test(envp->hPauseProcess);

        /* Decode the audio buffer */
        if (Sdec1_process(hSd1, hInBuf, hOutBuf) < 0) {
            ERR("Failed to decode audio buffer\n");
            cleanup(THREAD_FAILURE);
        }

        /* Increment statistics for user interface */
        gblIncSoundBytesProcessed(Buffer_getNumBytesUsed(hInBuf));

        /*
         * Force the output buffer size since we are forcing the size of the
         * output buffer allocated as opposed to asking the codec for a size.
         */
        Buffer_setNumBytesUsed(hOutBuf, OUTBUFSIZE);

        /* Write the decoded samples to the sound device */
        if (Sound_write(hSound, hOutBuf) < 0) {
            ERR("Failed to write audio buffer\n");
            cleanup(THREAD_FAILURE);
        }

        /* Load a new frame from the file system */
        if (Loader_getFrame(hLoader, hInBuf) < 0) {
            ERR("Failed to read a frame of encoded data\n");
            cleanup(THREAD_FAILURE);
        }

        /* Check if the clip has ended */
        if (Buffer_getUserPtr(hInBuf) == NULL) {
            /* Wait for the video clip to finish, if applicable */
            Rendezvous_meet(envp->hRendezvousLoop);

            /* If we are to loop the clip, start over */
            if (envp->loop) {
                /* Recreate the speech codec */
                Sdec1_delete(hSd1);
                hSd1 = Sdec1_create(hEngine, envp->speechDecoder,
                                    params, dynParams);

                if (hSd1 == NULL) {
                    ERR("Failed to create speech decoder: %s\n",
                        envp->speechDecoder);
                    cleanup(THREAD_FAILURE);
                }

                /* Re-prime the file loader */
                Loader_prime(hLoader, &hInBuf);
            }
            else {
                printf("End of clip reached, exiting..\n");
                cleanup(THREAD_SUCCESS);
            }
        }
    }

cleanup:
    /* Make sure the other threads aren't waiting for us */
    Rendezvous_force(envp->hRendezvousInit);
    Rendezvous_force(envp->hRendezvousLoop);
    Pause_off(envp->hPauseProcess);

    /* Meet up with other threads before cleaning up */
    Rendezvous_meet(envp->hRendezvousCleanup);

    /* Clean up the thread before exiting */
    if (hLoader) {
        Loader_delete(hLoader);
    }

    if (hSd1) {
        Sdec1_delete(hSd1);
    }

    if (hSound) {
        Sound_delete(hSound);
    }

    if (hOutBuf) {
        Buffer_delete(hOutBuf);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    return status;
}
Ejemplo n.º 9
0
/*
 *  ======== smain ========
 */
Int smain(String progName, String procId, String engineName,
          String inFile, String outFile)
{
    Engine_Handle ce = NULL;
    Engine_Attrs attrs;
    VIDDEC2_Handle dec = NULL;
    VIDENC1_Handle enc = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    Memory_AllocParams allocParams;

    createInFileIfMissing(inFile);

    Log_print4(Diags_USER1, "[+1] App-> Application started, procId %s "
               "engineName %s input-file %s output-file %s.",
               (IArg)procId, (IArg)engineName, (IArg)inFile, (IArg)outFile);

    /* allocate input, encoded, and output buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    encodedBuf = (XDAS_Int8 *)Memory_alloc(EFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);

    if ((inBuf == NULL) || (encodedBuf == NULL) || (outBuf == NULL) ||
            (versionBuf == NULL)) {

        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* Initialize attrs fields to default values, and set the procId */
    Engine_initAttrs(&attrs);
    attrs.procId = procId;

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, &attrs, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video decoder on the engine */
    dec = VIDDEC2_create(ce, decoderName, NULL);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize video encoder on the engine */
    enc = VIDENC1_create(ce, encoderName, NULL);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
    /* teardown the codecs */
    if (enc) {
        VIDENC1_delete(enc);
    }
    if (dec) {
        VIDDEC2_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (encodedBuf) {
        Memory_free(encodedBuf, EFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

    Log_print0(Diags_USER1, "[+1] app done.");
    return (0);
}
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    SCALE_Handle codec = NULL;
    SCALE_Params params;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Memory_AllocParams allocParams;

    unsigned char color_table_temp[1024]={0}; 

   //opencv var
    IplImage * frame;
    IplImage * gray_frame = NULL;
    IplImage * BinaryImage =NULL;
    CvCapture *cap=cvCreateCameraCapture(0);
    cvSetCaptureProperty(cap,CV_CAP_PROP_FRAME_WIDTH,320);
    cvSetCaptureProperty(cap,CV_CAP_PROP_FRAME_HEIGHT,240);
    cvSetCaptureProperty(cap,CV_CAP_PROP_FPS,30);



   /*YC added the bmp struct*/
#pragma pack(1)                       //採用1byte為單位對齊(需要讀檔頭)  
    static struct BMP_file_header {   //Total 54 bytes
           unsigned char Identifier[2];                     
           unsigned long  File_Size;            
           unsigned long  Reserved;          
           unsigned long  Bitmap_Data_Offset;  
           unsigned long   Bitmap_Header_Size;   
           unsigned long   Width;
           unsigned long   Height;       
           unsigned short  Planes;        
           unsigned short  Bits_Per_Pixel;      
           unsigned long   Compression;      
           unsigned long   Bitmap_Data_Size;  
           unsigned long   H_Resolution;        
           unsigned long   V_Resolution;         
           unsigned long   Used_Colors;           
           unsigned long   Important_Colors;  
    } BMP_header;  
    #pragma pack()

   static struct BMP_file_header *header_temp; 

    if (argc <= 1) {
        inFile = "./test2_8bit_gray.bmp";
        outFile = "./test2_8bit_sobel.bmp";
        createInFileIfMissing(inFile);
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    printf("App-> Application started.\n");

    /* allocate input, encoded, and output buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = Memory_DEFAULTALIGNMENT;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    

    if ((inBuf == NULL) || (outBuf == NULL)) {
        goto end;
    }



    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }


    //copy the Bmp_header
    header_temp=&BMP_header;                                                                    
    fread(header_temp,54,sizeof(unsigned char),in);                        
    fwrite(header_temp,54,sizeof(unsigned char),out);
 
    //copy the color table BGRA total 256*4=1024 bytes                                                                       
    fread(color_table_temp,1024,sizeof(unsigned char),in);
    fwrite(color_table_temp,1024,sizeof(unsigned char),out);  





   //capture video's frame
    frame = cvQueryFrame(cap);
   


    /* initialize scale factor */
    params.size = sizeof(SCALE_Params);
    params.initialScaleFactor = APP_SCALEFACTOR;

    /* allocate and initialize scale algo on the engine */
    codec = SCALE_create(ce, scaleName, &params);
    if (codec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", scaleName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    scale(codec, in, out);




end:
    /* teardown the codec */
    if (codec) {
        SCALE_delete(codec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }

    printf("app done.\n");
    return (0);
}
Ejemplo n.º 11
0
Archivo: appMain.c Proyecto: sv99/DVSDK
/******************************************************************************
 * appMain
 ******************************************************************************/
Int appMain(Args * args)
{
    VIDENC1_Params         params    = Venc1_Params_DEFAULT;
    VIDENC1_DynamicParams  dynParams = Venc1_DynamicParams_DEFAULT;
    BufferGfx_Attrs        gfxAttrs  = BufferGfx_Attrs_DEFAULT;
    Buffer_Attrs           bAttrs    = Buffer_Attrs_DEFAULT;
    Time_Attrs             tAttrs    = Time_Attrs_DEFAULT;
    Venc1_Handle           hVe1      = NULL;
    FILE                  *outFile   = NULL;
    FILE                  *reconFile = NULL;
    FILE                  *inFile    = NULL;
    Engine_Handle          hEngine   = NULL;
    Time_Handle            hTime     = NULL;
    Bool                   flushed   = FALSE;
    Bool                   mustExit  = FALSE;
    BufTab_Handle          hBufTab   = NULL;
    Buffer_Handle          hOutBuf   = NULL;
    Buffer_Handle          hFreeBuf  = NULL;
    Buffer_Handle          hInBuf    = NULL;
    Buffer_Handle          hReconBuf = NULL;
    Int                    numFrame  = 0;
    Int                    flushCntr = 1;
    Int                    bufIdx;
    Int                    inBufSize, outBufSize;
    Cpu_Device             device;
    Int                    numBufs;
    ColorSpace_Type        colorSpace;
    UInt32                 time;
    Int                    ret = Dmai_EOK;

    printf("Starting application...\n");

    /* Initialize the codec engine run time */
    CERuntime_init();

    /* Initialize DMAI */
    Dmai_init();

    /* Determine which device the application is running on */
    if (Cpu_getDevice(NULL, &device) < 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to determine target board\n");
        goto cleanup;
    }

    if (args->benchmark) {
        hTime = Time_create(&tAttrs);

        if (hTime == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to create Time object\n");
            goto cleanup;
        }
    }

    /* Open the input file with raw yuv data */
    inFile = fopen(args->inFile, "rb");

    if (inFile == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to open input file %s\n", args->inFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
    if (setvbuf(inFile, vbufferIn, _IOFBF, sizeof(vbufferIn)) != 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to setvbuf on input file descriptor\n");
        goto cleanup;
    }

    /* Open the output file where to put encoded data */
    outFile = fopen(args->outFile, "wb");

    if (outFile == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to open output file %s\n", args->outFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
    if (setvbuf(outFile, vbufferOut, _IOFBF, sizeof(vbufferOut)) != 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to setvbuf on output file descriptor\n");
        goto cleanup;
    }

    /* Open the output file where to put reconstructed frames */
    if (args->writeReconFrames) {
        reconFile = fopen(args->reconFile, "wb");

        if (reconFile == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to open output file %s\n", args->reconFile);
            goto cleanup;
        }

        /* Using a larger vbuf to enhance performance of file i/o */
        if (setvbuf(reconFile, vbufferRecon, _IOFBF,
                    sizeof(vbufferRecon)) != 0) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to setvbuf on output file descriptor\n");
            goto cleanup;
        }
    }

    /* Open the codec engine */
    hEngine = Engine_open(args->engineName, NULL, NULL);

    if (hEngine == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to open codec engine: %s\n", args->engineName);
        goto cleanup;
    }

    /* Set up codec parameters depending on bit rate */
    if (args->bitRate < 0) {
        /* Variable bit rate */
        params.rateControlPreset = IVIDEO_NONE;

        /*
         * If variable bit rate use a bogus bit rate value (> 0)
         * since it will be ignored.
         */
        params.maxBitRate        = 2000000;
    }
    else {
        /* Constant bit rate */
        params.rateControlPreset = IVIDEO_LOW_DELAY;
        params.maxBitRate        = args->bitRate;
    }

    /* Set up codec parameters depending on device */
    switch (device) {
    case Cpu_Device_DM6467:
        params.inputChromaFormat = XDM_YUV_420SP;
        params.reconChromaFormat = XDM_CHROMA_NA;
        break;
    case Cpu_Device_DM355:
        params.inputChromaFormat = XDM_YUV_422ILE;
        params.reconChromaFormat = XDM_YUV_420P;
        break;
    case Cpu_Device_DM365:
    case Cpu_Device_DM368:
        params.inputChromaFormat = XDM_YUV_420SP;
        params.reconChromaFormat = XDM_YUV_420SP;
        break;
    case Cpu_Device_DM3730:
        params.rateControlPreset = IVIDEO_STORAGE;
        params.inputChromaFormat = XDM_YUV_422ILE;
        break;
    default:
        params.inputChromaFormat = XDM_YUV_422ILE;
        break;
    }

    params.maxWidth              = args->width;
    params.maxHeight             = args->height;

    /* Workaround for SDOCM00068944: h264fhdvenc fails
       to create codec when params.dataEndianness is
       set as XDM_BYTE */
    if(device == Cpu_Device_DM6467) {
        if (!strcmp(args->codecName, "h264fhdvenc")) {
            params.dataEndianness        = XDM_LE_32;
        }
    }

    params.maxInterFrameInterval = 1;
    dynParams.targetBitRate      = params.maxBitRate;
    dynParams.inputWidth         = params.maxWidth;
    dynParams.inputHeight        = params.maxHeight;

    /* Create the video encoder */
    hVe1 = Venc1_create(hEngine, args->codecName, &params, &dynParams);

    if (hVe1 == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create video encoder: %s\n", args->codecName);
        goto cleanup;
    }

    /* Ask the codec how much input data it needs */
    inBufSize = Venc1_getInBufSize(hVe1);

    /* Ask the codec how much space it needs for output data */
    outBufSize = Venc1_getOutBufSize(hVe1);

    /* Which color space to use in the graphics buffers depends on the device */
    colorSpace = ((device == Cpu_Device_DM6467)||
                  (device == Cpu_Device_DM365) ||
                  (device == Cpu_Device_DM368)) ? ColorSpace_YUV420PSEMI :
                 ColorSpace_UYVY;

    /* Align buffers to cache line boundary */
    gfxAttrs.bAttrs.memParams.align = bAttrs.memParams.align = BUFSIZEALIGN;

    /* Use cached buffers if requested */
    if (args->cache) {
        gfxAttrs.bAttrs.memParams.flags = bAttrs.memParams.flags
                                          = Memory_CACHED;
    }

    gfxAttrs.dim.width      = args->width;
    gfxAttrs.dim.height     = args->height;
    if ((device == Cpu_Device_DM6467) || (device == Cpu_Device_DM365)
            || (device == Cpu_Device_DM368)) {
        gfxAttrs.dim.height = Dmai_roundUp(gfxAttrs.dim.height, CODECHEIGHTALIGN);
    }
    gfxAttrs.dim.lineLength = BufferGfx_calcLineLength(args->width, colorSpace);
    gfxAttrs.colorSpace     = colorSpace;

    if (inBufSize < 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to calculate buffer attributes\n");
        goto cleanup;
    }

    /* Number of input buffers required */
    if(params.maxInterFrameInterval>1) {
        /* B frame support */
        numBufs = params.maxInterFrameInterval;
    }
    else {
        numBufs = 1;
    }

    /* Create a table of input buffers of the size requested by the codec */
    hBufTab =
        BufTab_create(numBufs, Dmai_roundUp(inBufSize, BUFSIZEALIGN),
                      BufferGfx_getBufferAttrs(&gfxAttrs));

    if (hBufTab == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to allocate contiguous buffers\n");
        goto cleanup;
    }

    /* Set input buffer table */
    Venc1_setBufTab(hVe1, hBufTab);

    /* Create the reconstructed frame buffer for raw yuv data */
    if (args->writeReconFrames) {
        hReconBuf =
            Buffer_create(Dmai_roundUp(inBufSize, BUFSIZEALIGN),
                          BufferGfx_getBufferAttrs(&gfxAttrs));

        if (hReconBuf == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to allocate contiguous buffer\n");
            goto cleanup;
        }
    }

    /* Create the output buffer for encoded video data */
    hOutBuf = Buffer_create(Dmai_roundUp(outBufSize, BUFSIZEALIGN), &bAttrs);

    if (hOutBuf == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create contiguous buffer\n");
        goto cleanup;
    }

    while (1) {

        /* Get a buffer for input */
        hInBuf = BufTab_getFreeBuf(hBufTab);

        if (hInBuf == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to get a free contiguous buffer from BufTab\n");
            BufTab_print(hBufTab);
            goto cleanup;
        }

        if (args->benchmark) {
            if (Time_reset(hTime) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to reset timer\n");
                goto cleanup;
            }
        }

        /* Read a yuv input frame */
        printf("\n Frame %d: ", numFrame);
        if ((device == Cpu_Device_DM6467)||
                (device == Cpu_Device_DM365) ||
                (device == Cpu_Device_DM368)) {
            if(args->sp) {
                if (readFrame420SP(hInBuf, inFile, args->height) < 0) {
                    ret = Dmai_EFAIL;
                    goto cleanup;
                }
            } else {
                if (readFrame420P(hInBuf, inFile, args->height) < 0) {
                    ret = Dmai_EFAIL;
                    goto cleanup;
                }
            }
        }
        else {
            if (readFrameUYVY(hInBuf, inFile) < 0) {
                ret = Dmai_EFAIL;
                mustExit = TRUE;
            }
        }

        if (++numFrame == args->numFrames||mustExit == TRUE) {
            if(!(params.maxInterFrameInterval>1)) {
                /* No B-frame support */
                printf("... exiting \n");
                goto cleanup;
            }

            /*
             * When encoding a stream with B-frames, ending the processing
             * requires to free the buffer held by the encoder. This is done by
             * flushing the encoder and performing a last process() call
             * with a dummy input buffer.
             */
            printf("\n... exiting with flush (B-frame stream) \n");
            flushCntr = params.maxInterFrameInterval-1;
            flushed = TRUE;
            Venc1_flush(hVe1);
        }

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer delta\n");
                goto cleanup;
            }

            printf("Read time: %uus\n", (Uns)time);
        }

        /*
         * Following flushing loop will iterate more than one time only
         * when the encoder completes processing by flushing the frames
         * held by the encoder. All flushed frames will be encoded as P
         * or I frames.
         */

        for(bufIdx = 0; bufIdx < flushCntr; bufIdx++) {

            if (args->cache) {
                /*
                *  To meet xDAIS DMA Rule 7, when input buffers are cached, we
                *  must writeback the cache into physical memory.  Also, per DMA
                *  Rule 7, we must invalidate the output buffer from
                *  cache before providing it to any xDAIS algorithm.
                */
                Memory_cacheWbInv(Buffer_getUserPtr(hInBuf),
                                  Buffer_getSize(hInBuf));

                /* Per DMA Rule 7, our output buffer cache lines must be cleaned */
                Memory_cacheInv(Buffer_getUserPtr(hOutBuf),
                                Buffer_getSize(hOutBuf));

                if (args->benchmark) {
                    if (Time_delta(hTime, &time) < 0) {
                        ret = Dmai_EFAIL;
                        fprintf(stderr,"Failed to get timer delta\n");
                        goto cleanup;
                    }

                    printf("Pre-process cache maintenance: %uus \n", (Uns) time);
                }
            }

            /* Make sure the whole buffer is used for input */
            BufferGfx_resetDimensions(hInBuf);

            /* Encode the video buffer */
            if (Venc1_process(hVe1, hInBuf, hOutBuf) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to encode video buffer\n");
                goto cleanup;
            }

            /* if encoder generated output content, free released buffer */
            if (Buffer_getNumBytesUsed(hOutBuf)>0) {
                /* Get free buffer */
                hFreeBuf = Venc1_getFreeBuf(hVe1);
                /* Free buffer */
                BufTab_freeBuf(hFreeBuf);
            }
            /* if encoder did not generate output content */
            else {
                /* if non B frame sequence */
                /* encoder skipped frame probably exceeding target bitrate */
                if (params.maxInterFrameInterval<=1) {
                    /* free buffer */
                    printf(" Encoder generated 0 size frame\n");
                    BufTab_freeBuf(hInBuf);
                }
            }

            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    ret = Dmai_EFAIL;
                    fprintf(stderr,"Failed to get encode time\n");
                    goto cleanup;
                }

                printf("[%d] Encode: %uus\n", numFrame, (Uns)time);
            }

            if (args->cache) {
                /* Writeback the outBuf. */
                Memory_cacheWb(Buffer_getUserPtr(hOutBuf),
                               Buffer_getSize(hOutBuf));

                if (args->benchmark) {
                    if (Time_delta(hTime, &time) < 0) {
                        ret = Dmai_EFAIL;
                        fprintf(stderr,"Failed to get timer delta\n");
                        goto cleanup;
                    }

                    printf("Post-process cache write back: %uus \n", (Uns) time);
                }
            }

            /* Write the encoded frame to the file system */
            if (Buffer_getNumBytesUsed(hOutBuf)) {
                if (fwrite(Buffer_getUserPtr(hOutBuf),
                           Buffer_getNumBytesUsed(hOutBuf), 1, outFile) != 1) {
                    ret = Dmai_EFAIL;
                    fprintf(stderr,"Failed to write encoded video data to file\n");
                    goto cleanup;
                }
            }

            /* Write the reconstructed frame to the file system */
            if (args->writeReconFrames) {
                processReconData(Venc1_getReconBufs(hVe1), hInBuf, hReconBuf);

                if (Buffer_getNumBytesUsed(hReconBuf)) {
                    if (fwrite(Buffer_getUserPtr(hReconBuf),
                               Buffer_getNumBytesUsed(hReconBuf), 1, reconFile) != 1) {
                        ret = Dmai_EFAIL;
                        fprintf(stderr,"Failed to write reconstructed frame to file\n");
                        goto cleanup;
                    }
                }
            }

            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    ret = Dmai_EFAIL;
                    printf("Failed to get timer delta\n");
                    goto cleanup;
                }

                printf("File write time: %uus\n", (Uns)time);

                if (Time_total(hTime, &time) < 0) {
                    ret = Dmai_EFAIL;
                    fprintf(stderr,"Failed to get timer total\n");
                    goto cleanup;
                }

                printf("Total: %uus\n", (Uns)time);
            }
        }

        /* If the codec flushing completed, exit main thread */
        if (flushed) {
            /* Free dummy input buffer used for flushing process() calls */
            printf("freeing dummy input buffer ... \n");
            BufTab_freeBuf(hInBuf);
            break;
        }
    }

cleanup:
    /* Clean up the application */
    if (hOutBuf) {
        Buffer_delete(hOutBuf);
    }

    if (hReconBuf) {
        Buffer_delete(hReconBuf);
    }

    if (hVe1) {
        Venc1_delete(hVe1);
    }

    if (hBufTab) {
        BufTab_delete(hBufTab);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    if (inFile) {
        fclose(inFile);
    }

    if (outFile) {
        fclose(outFile);
    }

    if (reconFile) {
        fclose(reconFile);
    }

    if (hTime) {
        Time_delete(hTime);
    }

    printf("End of application.\n");

    if (ret == Dmai_EFAIL)
        return 1;
    else
        return 0;
}
Ejemplo n.º 12
0
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    SPHDEC1_Handle dec = NULL;
    SPHENC1_Handle enc = NULL;
    SPHDEC1_Params decParams;
    SPHENC1_Params encParams;

    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;

    if (argc <= 1) {
        inFile = "../in.dat";
        outFile = "../out.dat";
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate input, encoded, and output buffers */
    inBuf = (XDAS_Int8 *)Memory_contigAlloc(IFRAMESIZE, BUFALIGN);
    encodedBuf = (XDAS_Int8 *)Memory_contigAlloc(EFRAMESIZE, BUFALIGN);
    outBuf = (XDAS_Int8 *)Memory_contigAlloc(OFRAMESIZE, BUFALIGN);
    versionBuf = (XDAS_Int8 *)Memory_contigAlloc(MAXVERSIONSIZE, BUFALIGN);

    if ((inBuf == NULL) || (encodedBuf == NULL) || (outBuf == NULL) ||
        (versionBuf == NULL)) {

        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize decoder in the engine */
    decParams.size = sizeof(decParams);
    decParams.compandingLaw = ISPEECH1_PCM_COMPAND_ULAW;
    /* no other create params are meaningful for PCM decoders */

    dec = SPHDEC1_create(ce, decoderName, &decParams);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize encoder in the engine */
    encParams.size = sizeof(encParams);
    encParams.frameSize = IFRAMESIZE;
    encParams.compandingLaw = ISPEECH1_PCM_COMPAND_ULAW;
    /* no other create params are meaningful for PCM encoders */

    enc = SPHENC1_create(ce, encoderName, &encParams);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
    /* teardown the codecs */
    if (enc) {
        SPHENC1_delete(enc);
    }
    if (dec) {
        SPHDEC1_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_contigFree(inBuf, IFRAMESIZE);
    }
    if (encodedBuf) {
        Memory_contigFree(encodedBuf, EFRAMESIZE);
    }
    if (outBuf) {
        Memory_contigFree(outBuf, OFRAMESIZE);
    }
    if (versionBuf) {
        Memory_contigFree(versionBuf, MAXVERSIONSIZE);
    }

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
Ejemplo n.º 13
0
Archivo: ce.c Proyecto: guyz/dsp
static void ce_close(void)
{
    codecModule->close();
    if (ce)         Engine_close(ce);               ce     = NULL;
    CERuntime_exit();
}
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    IMGDEC1_Handle dec = NULL;
    IMGENC1_Handle enc = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Memory_AllocParams allocParams;

    if (argc <= 1) {
        inFile = "./in.dat";
        outFile = "./out.dat";
        createInFileIfMissing(inFile);
    }
    else if (argc >= 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    if ((argc == 4) && (argv[3][0] == '1')) {
        appPause = 1;
    }


    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    encodedBuf = (XDAS_Int8 *)Memory_alloc(EFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);

    if ((inBuf == NULL) || (encodedBuf == NULL) || (outBuf == NULL) ||
        (versionBuf == NULL)) {

        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video decoder on the engine */
    dec = IMGDEC1_create(ce, decoderName, NULL);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize video encoder on the engine */
    enc = IMGENC1_create(ce, encoderName, NULL);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

#ifdef USE_POWER_MANAGEMENT
    /* open local power manager */
    if (Global_usePowerManagement) {
       LPM_Status  lpmStat = LPM_SOK;
       lpmStat = LPM_open("/dev/lpm0", &lpmHandle);

       if (lpmStat != LPM_SOK) {
            fprintf(stderr, "%s: error: LPM_open() failed\n", progName);
            goto end;
       }
    }
#endif

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
#ifdef USE_POWER_MANAGEMENT
    /* close local power manager */
    if (lpmHandle != NULL) {
       LPM_close(lpmHandle);
    }
#endif

    /* teardown the codecs */
    if (enc) {
        IMGENC1_delete(enc);
    }
    if (dec) {
        IMGDEC1_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (encodedBuf) {
        Memory_free(encodedBuf, EFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
Ejemplo n.º 15
0
/******************************************************************************
 * main
 ******************************************************************************/
Int appMain(Args * args)
{
    Buffer_Attrs            bAttrs      = Buffer_Attrs_DEFAULT;
    Loader_Attrs            lAttrs      = Loader_Attrs_DEFAULT;
    AUDDEC1_Params          params      = Adec1_Params_DEFAULT;
    AUDDEC1_DynamicParams   dynParams   = Adec1_DynamicParams_DEFAULT;
    Time_Attrs              tAttrs      = Time_Attrs_DEFAULT;
    Adec1_Handle            hAd1        = NULL;
    Loader_Handle           hLoader     = NULL;
    Engine_Handle           hEngine     = NULL;
    Buffer_Handle           hOutBuf     = NULL;
    Time_Handle             hTime       = NULL;
    Buffer_Handle           hInBuf      = NULL;
    FILE                   *outFile     = NULL;
    Int                     numFrame    = 0;
    UInt32                  time;
    Int                     ret         = Dmai_EOK;
    Cpu_Device              device;

    printf("Starting application...\n");
        
    if (args->benchmark) {
        hTime = Time_create(&tAttrs);

        if (hTime == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr, "Failed to create Time object\n");
            goto cleanup;
        }
    }

    /* Initialize the codec engine run time */
    CERuntime_init();

    /* Initialize DMAI */
    Dmai_init();

    /* Determine which device the application is running on */
    if (Cpu_getDevice(NULL, &device) < 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr, "Failed to determine target board\n");
        goto cleanup;
    }

    /* Open the output file */
    outFile = fopen(args->outFile, "wb");

    if (outFile == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create output file %s\n", args->outFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
    if (setvbuf(outFile, vbuffer, _IOFBF, sizeof(vbuffer)) != 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr, "Failed to setvbuf on file descriptor\n");
        goto cleanup;
    }

    /* Open the codec engine */
    hEngine = Engine_open(args->engineName, NULL, NULL);

    if (hEngine == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr, "Failed to open codec engine %s\n", args->engineName);
        goto cleanup;
    }

    if (device == Cpu_Device_DM365 || device == Cpu_Device_OMAP3530 ||
        device == Cpu_Device_DM368 || device == Cpu_Device_DM3730) {
        params.dataEndianness = XDM_LE_16;
    }


    /* Create the AUDDEC1 based audio decoder */
    hAd1 = Adec1_create(hEngine, args->codecName, &params, &dynParams);

    if (hAd1 == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr, "Failed to create audio decoder\n");
        goto cleanup;
    }

    /* Align buffers to cache line boundary */    
    bAttrs.memParams.align = lAttrs.mParams.align = BUFSIZEALIGN; 
    
    /* Use cached buffers if requested */    
    if (args->cache) {
        bAttrs.memParams.flags = lAttrs.mParams.flags = Memory_CACHED;
    } 
    
    /* Ask the codec how much input data it needs */
    lAttrs.readSize = Adec1_getInBufSize(hAd1);

    /* Make the total ring buffer larger */
    lAttrs.readBufSize = Dmai_roundUp(lAttrs.readSize * 10, BUFSIZEALIGN);

    /* Increase the stdio buffer size for loader for better RTDX performance */
    lAttrs.vBufSize = VBUFSIZE;

    /* Create the file loader */
    hLoader = Loader_create(args->inFile, &lAttrs);

    if (hLoader == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr, "Failed to create loader\n");
        goto cleanup;
    }

    /* Create an output buffer for decoded data */
    hOutBuf = Buffer_create(
        Dmai_roundUp(Adec1_getOutBufSize(hAd1), BUFSIZEALIGN), &bAttrs);

    if (hOutBuf == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr, "Failed to create contiguous buffers\n");
        goto cleanup;
    }

    /* Prime the file loader */
    Loader_prime(hLoader, &hInBuf);

    while (numFrame++ < args->numFrames) {
        if (args->benchmark) {
            if (Time_reset(hTime) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr, "Failed to reset timer\n");
                goto cleanup;
            }
        }

        if (args->cache) {
            /*
             *  To meet xDAIS DMA Rule 7, when input buffers are cached, we
             *  must writeback the cache into physical memory.  Also, per DMA
             *  Rule 7, we must invalidate the output buffer from
             *  cache before providing it to any xDAIS algorithm.
             */
            Memory_cacheWbInv(Buffer_getUserPtr(hInBuf),Buffer_getSize(hInBuf));

            /* Per DMA Rule 7, our output buffer cache lines must be cleaned */
            Memory_cacheInv(Buffer_getUserPtr(hOutBuf),Buffer_getSize(hOutBuf));

            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    ret = Dmai_EFAIL;
                    fprintf(stderr,"Failed to get timer delta\n");
                    goto cleanup;
                }

                printf("Pre-process cache maintenance: %uus ", (Uns) time);
            }
        }

        /* Decode the audio buffer */
        ret = Adec1_process(hAd1, hInBuf, hOutBuf);

        if ((ret == Dmai_EFAIL)||
            (ret == Dmai_EBITERROR && Buffer_getNumBytesUsed(hInBuf) == 0)) {
            ret = Dmai_EFAIL;
            fprintf(stderr, "Failed to decode audio buffer\n");
            goto cleanup;
        }

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr, "Failed to get timer delta\n");
                goto cleanup;
            }

            printf("Decode: %uus ", (Uns) time);
        }

        if (args->cache) {
            /* Writeback the outBuf. */
            Memory_cacheWb(Buffer_getUserPtr(hOutBuf), Buffer_getSize(hOutBuf));

            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    ret = Dmai_EFAIL;
                    fprintf(stderr, "Failed to get timer delta\n");
                    goto cleanup;
                }

                printf("Post-process cache write back: %uus ", (Uns) time);
            }
        }

        /* Load a new frame from the file system */
        Loader_getFrame(hLoader, hInBuf);

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer delta\n");
                goto cleanup;
            }

            printf("Loader: %uus\n", (Uns) time);
        }

        if (Buffer_getNumBytesUsed(hOutBuf)) {
            if (numFrame >= args->startFrame) {
                printf("Frame %d: ", numFrame);
                if (writeFrame(hOutBuf, outFile) < 0) {
                    ret = Dmai_EFAIL;
                    goto cleanup;
                }
            }
        }

        if (Buffer_getUserPtr(hInBuf) == NULL) {
            printf("Loader returned null, clip finished\n");
            break;
        }

        if (args->benchmark) {
            if (Time_total(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer total\n");
                goto cleanup;
            }

            printf("Total: %uus\n", (unsigned int)time);
        }
    }

cleanup:
    /* Clean up the application */
    if (hLoader) {
        Loader_delete(hLoader);
    }

    if (hAd1) {
        Adec1_delete(hAd1);
    }

    if (hOutBuf) {
        Buffer_delete(hOutBuf);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    if (hTime) {
        Time_delete(hTime);
    }

    if (outFile) {
        fclose(outFile);
    }

    printf("End of application.\n");

    if (ret == Dmai_EFAIL)
        return 1;
    else
        return 0;
}
Ejemplo n.º 16
0
/******************************************************************************
 * appMain
 ******************************************************************************/
Void appMain(Args * args)
{
    VIDENC_Params           params      = Venc_Params_DEFAULT;
    VIDENC_DynamicParams    dynParams   = Venc_DynamicParams_DEFAULT;
    BufferGfx_Attrs         gfxAttrs    = BufferGfx_Attrs_DEFAULT;
    Buffer_Attrs            bAttrs      = Buffer_Attrs_DEFAULT;
    Time_Attrs              tAttrs      = Time_Attrs_DEFAULT;
    Venc_Handle             hVe         = NULL;
    FILE                   *outFile     = NULL;
    FILE                   *inFile      = NULL;
    Engine_Handle           hEngine     = NULL;
    Time_Handle             hTime       = NULL;
    Int                     numFrame    = 0;
    Buffer_Handle           hOutBuf     = NULL;
    Buffer_Handle           hInBuf      = NULL;
    ColorSpace_Type         colorSpace;
    UInt32                  time;

    printf("Starting application...\n");
    
    /* Initialize the codec engine run time */
    CERuntime_init();
    
    /* Initialize DMAI */
    Dmai_init();
    
    if (args->benchmark) {
        hTime = Time_create(&tAttrs);

        if (hTime == NULL) {
            printf("Failed to create Time object\n");
            goto cleanup;
        }
    }

    /* Open input file */
    inFile = fopen(args->inFile, "rb");
    
    if (inFile == NULL) {
        printf("Failed to open input file %s\n", args->inFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
    if (setvbuf(inFile, vbufferIn, _IOFBF, sizeof(vbufferIn)) != 0) {
        printf("Failed to setvbuf on input file descriptor\n");
        goto cleanup;   
    }   

    
    /* Open output file */
    outFile = fopen(args->outFile, "wb");

    if (outFile == NULL) {
        printf("Failed to open output file %s\n", args->outFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
    if (setvbuf(outFile, vbufferOut, _IOFBF, sizeof(vbufferOut)) != 0) {
        printf("Failed to setvbuf on output file descriptor\n");
        goto cleanup;   
    }
    
    /* Open the codec engine */
    hEngine = Engine_open(args->engineName, NULL, NULL);

    if (hEngine == NULL) {
        printf("Failed to open codec engine: %s\n", args->engineName);
        goto cleanup;
    }

    params.maxWidth = args->width;
    params.maxHeight = args->height;

    /* Set up codec parameters depending on bit rate */
    if (args->bitRate < 0) {
        /* Variable bit rate */
        params.rateControlPreset = IVIDEO_NONE;

        /*
         * If variable bit rate use a bogus bit rate value (> 0)
         * since it will be ignored.
         */
        params.maxBitRate        = 2000000;
    }
    else {
        /* Constant bit rate */
        params.rateControlPreset = IVIDEO_LOW_DELAY;
        params.maxBitRate        = args->bitRate;
    }

    params.inputChromaFormat = XDM_YUV_422ILE;

    dynParams.targetBitRate = params.maxBitRate;
    dynParams.inputWidth = params.maxWidth;
    dynParams.inputHeight = params.maxHeight;
    
    /* Create the video encoder */
    hVe = Venc_create(hEngine, args->codecName, &params, &dynParams);

    if (hVe == NULL) {
        printf("Failed to create video encoder: %s\n", args->codecName);
        goto cleanup;
    }

    /* Only the UYVY colorspace is supported in this application */
    colorSpace = ColorSpace_UYVY;

    /* Align buffers to cache line boundary */    
    gfxAttrs.bAttrs.memParams.align = bAttrs.memParams.align = BUFSIZEALIGN; 
    
    /* Use cached buffers if requested */    
    if (args->cache) {
        gfxAttrs.bAttrs.memParams.flags = bAttrs.memParams.flags 
            = Memory_CACHED;
    } 
    
    /* Calculate the buffer attributes */
    gfxAttrs.dim.width = args->width;
    gfxAttrs.dim.height = args->height;
    gfxAttrs.dim.lineLength = BufferGfx_calcLineLength(args->width, colorSpace);
    gfxAttrs.colorSpace = colorSpace;

    /* Create input buffer */
    hInBuf = Buffer_create(Dmai_roundUp(Venc_getInBufSize(hVe), BUFSIZEALIGN),
                           BufferGfx_getBufferAttrs(&gfxAttrs));

    if (hInBuf == NULL) {
        printf("Failed to allocate contiguous buffer\n");
        goto cleanup;
    }

    /* Create output buffer */
    hOutBuf = Buffer_create(Dmai_roundUp(Venc_getOutBufSize(hVe), BUFSIZEALIGN),
        &bAttrs);

    if (hOutBuf == NULL) {
        printf("Failed to create contiguous buffer\n");
        goto cleanup;
    }

    while (numFrame++ < args->numFrames) {
        /* Read a yuv input frame */
        printf("Frame %d: ", numFrame);
        if (readFrameUYVY(hInBuf, inFile) < 0) {
            goto cleanup;        
        }
        
        if (args->benchmark) {
            if (Time_reset(hTime) < 0) {
                printf("Failed to reset timer\n");
                goto cleanup;
            }
        }

        if (args->cache) {
            /*  
             *  To meet xDAIS DMA Rule 7, when input buffers are cached, we 
             *  must writeback the cache into physical memory.  Also, per DMA 
             *  Rule 7, we must invalidate the output buffer from
             *  cache before providing it to any xDAIS algorithm.
             */
            Memory_cacheWbInv(Buffer_getUserPtr(hInBuf), Buffer_getSize(hInBuf));
    
            /* Per DMA Rule 7, our output buffer cache lines must be cleaned */
            Memory_cacheInv(Buffer_getUserPtr(hOutBuf), Buffer_getSize(hOutBuf));
    
            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    printf("Failed to get timer delta\n");
                    goto cleanup;
                }
    
                printf("Pre-process cache maintenance: %uus \n", (Uns) time);
            }
        }

        /* Encode the video buffer */
        if (Venc_process(hVe, hInBuf, hOutBuf) < 0) {
            printf("Failed to encode video buffer\n");
            goto cleanup;
        }

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                printf("Failed to get encode time\n");
                goto cleanup;
            }

            printf("[%d] Encode: %uus\n", numFrame, (Uns)time);
        }

        if (args->cache) {
            /* Writeback the outBuf. */
            Memory_cacheWb(Buffer_getUserPtr(hOutBuf), Buffer_getSize(hOutBuf));
    
            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    printf("Failed to get timer delta\n");
                    goto cleanup;
                }
    
                printf("Post-process cache write back: %uus \n", (Uns) time);
            }
        }
        
        /* Write the encoded frame to the file system */
        if (Buffer_getNumBytesUsed(hOutBuf)) {
            if (fwrite(Buffer_getUserPtr(hOutBuf),
                       Buffer_getNumBytesUsed(hOutBuf), 1, outFile) != 1) {
                printf("Failed to write encoded video data to file\n");
                goto cleanup;
            }
        }
        
        if (args->benchmark) {
            if (Time_total(hTime, &time) < 0) {
                printf("Failed to get timer total\n");
                goto cleanup;
            }

            printf("Total: %uus\n", (unsigned int)time);
        }
    }

cleanup:
    /* Clean up the application */
    if (hOutBuf) {
        Buffer_delete(hOutBuf);
    }

    if (hInBuf) {
        Buffer_delete(hInBuf);
    }

    if (hVe) {
        Venc_delete(hVe);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    if (inFile) {
        fclose(inFile);
    }
   
    if (outFile) {
        fclose(outFile);
    }

    if (hTime) {
        Time_delete(hTime);
    }

    printf("End of application.\n");
    
    return;
}
Ejemplo n.º 17
0
/*
 *  ======== smain ========
 */
Int smain(String progName, String procId, String engineName,
          String inFile, String outFile)
{
    Engine_Handle ce = NULL;
    Engine_Attrs attrs;
    UNIVERSAL_Handle hUniversal = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    Memory_AllocParams allocParams;
    XDAS_Int8 *inBuf;
    XDAS_Int8 *outBuf;
    XDAS_Int8 *versionBuf;   /* acquire optional version from codecs */

    /* create the input file if it doesn't already exist */
    createInFileIfMissing(inFile);

    Log_print4(Diags_USER1, "[+1] App-> Application started, procId %s "
               "engineName %s input-file %s output-file %s.",
               (IArg)procId, (IArg)engineName, (IArg)inFile, (IArg)outFile);

    /*
     * Allocate buffers.
     * Note that the .flags field (cache) is ignored on BIOS-based systems.
     */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);

    if ((inBuf == NULL) || (outBuf == NULL) || (versionBuf == NULL)) {
        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* Initialize attrs fields to default values, and set the procId */
    Engine_initAttrs(&attrs);
    attrs.procId = procId;

    /* Open the Engine */
    if ((ce = Engine_open(engineName, &attrs, NULL)) == NULL) {
        printf("App-> ERROR: can't open engine %s\n", engineName);
        goto end;
    }

    /* allocate and initialize universal alg on the engine */
    hUniversal = UNIVERSAL_create(ce, universalName, NULL);
    if (hUniversal == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", universalName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    processLoop(hUniversal, in, out, inBuf, outBuf, versionBuf);

end:
    /* teardown the codec */
    if (hUniversal) {
        UNIVERSAL_delete(hUniversal);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

    Log_print0(Diags_USER1, "[+1] app done.");
    return (0);
}
Ejemplo n.º 18
0
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    AUDDEC1_Handle dec = NULL;
    AUDENC1_Handle enc = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Int i;

    if (argc <= 1) {
        inFile = "../in.dat";
        outFile = "../out.dat";
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate input, encoded, output, and version buffers */
    for (i = 0; i < NBUFFERS; i++) {
        inBuf[i] = (XDAS_Int8 *)Memory_contigAlloc(IFRAMESIZE, BUFALIGN);
        encodedBuf[i] = (XDAS_Int8 *)Memory_contigAlloc(EFRAMESIZE, BUFALIGN);
        outBuf[i] = (XDAS_Int8 *)Memory_contigAlloc(OFRAMESIZE, BUFALIGN);
#if USE_ANCDATA
        ancBuf[i] = (XDAS_Int8 *)Memory_contigAlloc(ENCANCBUFSIZE, BUFALIGN);
        if (ancBuf[i] == NULL) {
            goto end;
        }
#endif

        if ((inBuf[i] == NULL) || (encodedBuf[i] == NULL) ||
            (outBuf[i] == NULL)) {

            goto end;
        }
    }
    /* we need one more encoded buffer than the others */
    encodedBuf[NBUFFERS] = (XDAS_Int8 *)Memory_contigAlloc(EFRAMESIZE,
                                        BUFALIGN);
    if (encodedBuf[NBUFFERS] == NULL) {
        goto end;
    }

    versionBuf = (XDAS_Int8 *)Memory_contigAlloc(MAXVERSIONSIZE, BUFALIGN);
    if (versionBuf == NULL) {
        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video decoder on the engine */
    dec = AUDDEC1_create(ce, decoderName, NULL);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize video encoder on the engine */
    enc = AUDENC1_create(ce, encoderName, NULL);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
    /* teardown the codecs */
    if (enc) {
        AUDENC1_delete(enc);
    }
    if (dec) {
        AUDDEC1_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    for (i = 0; i < NBUFFERS; i++) {
        if (inBuf[i]) {
            Memory_contigFree(inBuf[i], IFRAMESIZE);
        }
        if (encodedBuf[i]) {
            Memory_contigFree(encodedBuf[i], EFRAMESIZE);
        }
        if (outBuf[i]) {
            Memory_contigFree(outBuf[i], OFRAMESIZE);
        }
#if USE_ANCDATA
        if (ancBuf[i]) {
            Memory_contigFree(ancBuf[i], ENCANCBUFSIZE);
        }
#endif
    }
    if (encodedBuf[NBUFFERS]) {
        Memory_contigFree(encodedBuf[NBUFFERS], EFRAMESIZE);
    }
    if (versionBuf) {
        Memory_contigFree(versionBuf, MAXVERSIONSIZE);
    }

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
Ejemplo n.º 19
0
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Char newTraceMask[MAXTRACESTRING];
    Server_Handle server = NULL;
    Bool finished = FALSE;
    Uns mode = PULLTRACE;
    Server_Status status;
    Int traceToken;
    String mask;
    Uns rate;

    /* interpret PULLTRACE mode args */
    if (argc == 3) {
        rate = atoi(argv[1]);
        mask = argv[2];
    }

    /* else, if no args, set mode to TRACEUTIL */
    else if (argc == 1) {
        mode = TRACEUTIL;
    }
    /* else, show usage */
    else {
        fprintf(stderr, usage, argv[0]);
        goto done;
    }

    /* reset, load, and start DSP Engine */
    if ((engine = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "Error: can't open engine %s!\n", engineName);
        goto done;
    }

    /* setup file descriptor mask for checking for user key input */
    FD_ZERO(&fdMask);
    FD_SET(STDIN_FILENO, &fdMask);

    /* if standard output mode... */
    if (mode == PULLTRACE) {

        printf("Trace polling rate: %d msec\n", rate);
        rate *= 1000;
        printf("DSP trace mask: %s\n", mask);

        /* get server handle */
        server = Engine_getServer(engine);
        if (server == NULL) {
            fprintf(stderr, "Error: can't get server handle!\n");
            goto closeEngine;
        }

        /* connect for server trace data */
        status = Server_connectTrace(server, &traceToken);
        if (status == Server_EINUSE) {
            fprintf(stderr,
                "Error: server trace already in use by another process!\n");
            goto closeEngine;
        }
        else if (status != Server_EOK) {
            fprintf(stderr, "Error: server connect failed, status = 0x%x!\n",
                status);
            goto closeEngine;
        }

        /* server trace mask */
        status = Server_setTrace(server, mask);
        if (status != (Int) Engine_EOK) {
            fprintf(stderr, "Error: unable to set trace mask, status = 0x%x!\n",
                status);
            goto closeEngine;
        }

        printf("Hit <Enter> to exit, or, new trace mask and then <Enter>...\n");

        while (finished == FALSE) {

            dumpTrace(server);

            usleep(rate);

            if (checkInput(newTraceMask) == TRUE) {
                if (strlen(newTraceMask) == 0) {
                    finished = TRUE;
                }
                else {
                    printf("setting new trace mask: %s\n", newTraceMask);
                    status = Server_setTrace(server, newTraceMask);
                    if (status != (Int) Engine_EOK) {
                        fprintf(stderr,
                           "Error updating trace mask, status = 0x%x!\n",
                           status);
                    }
                }
            }
        };

        /* discconnect from server trace data */
        status = Server_disconnectTrace(server, traceToken);
        if (status != Server_EOK) {
            fprintf(stderr,
              "Error: unable to disconnect from server trace, status = 0x%x!\n",
                status);
        }
    }

    /* else, startup TraceUtil to retrieve trace/LOG data and write to files */
    else {

        TraceUtil_start(engineName);

        printf("Started TraceUtil thread\nHit <Enter> to exit...\n");

        getchar();

        TraceUtil_stop();
    }

    printf("Done.\n");

closeEngine:

    /* close the engine */
    if (engine) {
        Engine_close(engine);
    }

done:
    return (0);
}
Ejemplo n.º 20
0
void
dvtb_sphEncCapture(DvevmStThreadInfo *T)
{
  DvevmStRetCode retval=DVEVM_ST_FAIL;
  int nBytes=DVEVM_ST_FAIL;
  char *buff=NULL;
  int bytesToCapture=0, count=0;
  char tempBuff[SPHENC_FRAME_SIZE*4];

  SYS_DEBUG("Speech [capture][encode] called with %s option\n", (T->useAlgorithm)?"USE DSP":"NO DSP");
  SYS_DEBUG("Number of seconds to [capture][encode] : %d\n", T->g.senc.seconds);

  if ( !T->targetFp )
  {
    SYS_ERROR("Target file cannot be opened. It is a mandatory parameter\n");
    dvtb_freeThr(T);
    dvtb_threadExit();
  }

  // [Capture][Encode] scenario
  do
  {
    SYS_OUT("Speech [capture][encode] started for %d seconds\n", T->g.senc.seconds);

    if (T->useAlgorithm)
    {
      T->g.aud.sampleRate = 8000;
      T->g.senc.inBuf.size = SPHENC_FRAME_SIZE * 2;
      T->g.senc.outBuf.size = SPHENC_FRAME_SIZE;
      if (DVEVM_ST_FAIL == dvtb_ceInit(T->g.eng.name, &T->g.senc.ceHdl))
      {
        SYS_ERROR("Unable to initialize Codec Engine <%s>\n", T->g.eng.name);
        break;
      }
      else if (DVEVM_ST_FAIL == dvtb_sphEncInit(&T->g.senc))
      {
        SYS_ERROR("Unable to initialize Speech Encoder <%s>\n", T->g.senc.sencName);
        break;
      }
      else
        SYS_OUT("Speech Encoder <%s> initialized\n", T->g.senc.sencName);
    }
    else
    {
      T->g.senc.inBuf.size = SPHENC_FRAME_SIZE*4*2;
      T->g.senc.inBuf.start = (char *)malloc(T->g.senc.inBuf.size);
    }

    if (!T->sourceFp)
    {
      T->g.aud.mode = DVEVM_ST_CAPTURE;
      retval = dvtb_audioSetup(&T->g.aud);
      if (DVEVM_ST_FAIL == retval)
      {
        SYS_ERROR("Unable to initialize Audio device <%s> for capture\n", T->g.aud.device);
        break;
      }
      else
      {
        SYS_DEBUG("Audio Device <%s> initialized for capture\n", T->g.aud.device);
        bytesToCapture = (T->g.senc.seconds)*(AUD_FRAME_SIZE(T->g.aud.sampleRate, T->g.aud.numChannels, T->g.aud.sampleSize));
      }
    }
    while (1)
    {
      buff = tempBuff;

      if (T->sourceFp)
      {
        nBytes = fread(buff, 1, SPHENC_FRAME_SIZE*4, T->sourceFp);
        if (0==nBytes || feof(T->sourceFp))
        {
          SYS_DEBUG("End of file reached. Exiting ...\n");
          break;
	}
      }
      else
      {
        nBytes = dvtb_audioIn(&T->g.aud, buff, SPHENC_FRAME_SIZE*4);
        if (DVEVM_ST_FAIL == nBytes || count >= bytesToCapture)
          break;

        count += SPHENC_FRAME_SIZE*4;
      }

      if (T->useAlgorithm)
      {
        stereoToMono( (short *)buff, (short *)T->g.senc.inBuf.start, SPHENC_FRAME_SIZE);
        buff = T->g.senc.inBuf.start;

        memset(T->g.senc.outBuf.start, 0, T->g.senc.outBuf.size);
        if (DVEVM_ST_FAIL == dvtb_sphEncEncode(&T->g.senc))
        {
          SYS_ERROR("Unable to encode the input buffer\n");
          break;
        }
        buff = T->g.senc.outBuf.start;
        fwrite(buff, 1, T->g.senc.outBuf.size, T->targetFp);
      }
      else
      {
      //  stereoToMono( (short *)buff, (short *)T->g.senc.inBuf.start, SPHENC_FRAME_SIZE);
      //  buff = T->g.senc.inBuf.start;
          fwrite(buff, 1, SPHENC_FRAME_SIZE*4, T->targetFp);
      }

    }
  } while (DVEVM_ST_FALSE); // Dummy loop

  SYS_OUT("Speech [capture][encode] completed\n");

  if (!T->sourceFp)
    dvtb_audioClose(&T->g.aud);

  if (T->useAlgorithm)
  {
    dvtb_sphEncClose(&T->g.senc);
    SYS_OUT("Speech Encoder <%s> closed\n", T->g.senc.sencName);

    Engine_close(T->g.senc.ceHdl);
    SYS_OUT("Engine <%s> closed\n", T->g.eng.name);
  }
  else
    free(T->g.senc.inBuf.start);

  if (T->sourceFp)
  {
    fclose(T->sourceFp);
    T->sourceFp = NULL;
  }

  if (T->targetFp)
  {
    fclose(T->targetFp);
    T->targetFp = NULL;
  }

  SYS_OUT("Speech Capture thread exiting\n");

  dvtb_freeThr(T);
  dvtb_threadExit();
}
Ejemplo n.º 21
0
/*
 * ======== traceThrFxn ========
 */
static void *traceThrFxn(void *arg)
{
    String engineName = (String) arg;
    Server_Status status;
    FILE *f;
    IArg key;

    /* determine DSP line prefix: "[DSP] " if local and DSP trace end up at the same
     * file, otherwise ""
     */
    char *dspPrefix = (dsp0TraceFilePtr == localTraceFilePtr) ? "[DSP] " : "";

    DBG("Trace thread started\n");

    hEngine = Engine_open(engineName, NULL, NULL);

    if (hEngine == NULL) {
        ERR("Failed to open codec engine \"%s\"\n", engineName);
        threadCreateFailed = TRUE;
        return ((void *) -1);
    }

    /* for multi-process situations, make sure can acquire server trace */
    if (Global_useLinkArbiter) {

        /* get server handle */
        hServer = Engine_getServer(hEngine);

        /* cleanup and abort if can't get server handle */
        if (hServer == NULL) {
            Engine_close(hEngine);
            ERR("Failed to get server handle\n");
            threadCreateFailed = TRUE;
            return ((void *) -1);
        }

        /* request server trace token */
        status = Server_connectTrace(hServer, &traceToken);

        /* cleanup and abort if trace could not acquire trace token */
        if (status != Server_EOK) {
            Engine_close(hEngine);
            ERR("Failed to connect for server trace\n");
            threadCreateFailed = TRUE;
            return ((void *) -1);
        }
    }

    /* else: if single-process, don't need to explictly connect for trace */

    Engine_setTrace(hEngine, dsp0mask);

    /* create the pipe thread now */
    if (cmdPipeFile != NULL && cmdPipeFile[0] != '\0') {
        if (pthread_create(&pipeThread, NULL, pipeThrFxn, NULL)) {
            ERR("Failed to create pipe thread\n");
        } else {
            /* run the thread just created so it can immediately execute
             * pending cmdPipe trace commands -- in case there are any
             */
            while (pipeThreadCreated == FALSE) {
                sched_yield();
            }
        }
    }

    /* TODO: remove? will LogClient_connect be inside CE? */
    /*
     * Note, call LogClient_connect() before releasing the main thread to
     * avoid context switching away _during_ the connect() call - which could
     * result in a skewed timesynch log.
     */
    if (dsp0BiosFilePtr != NULL) {
//        LogClient_connect();
    }

    /* Release the spinning main thread to run */
    traceThreadCreated = TRUE;

    while (!quit) {

        if (refresh > 0) {

            DBG("Writing DSP logs\n");

            key = Gate_enterModule();

            Engine_fwriteTrace(hEngine, dspPrefix, dsp0TraceFilePtr);

            if (dsp0BiosFilePtr != NULL) {
//                LogClient_fwriteLogs(dsp0BiosFilePtr);
            }

            Gate_leaveModule(key);

            DBG("Sleeping for %d us\n", refresh);
            usleep(refresh);
        } else {
            DBG("Sleeping for %d us\n", SLEEPWHENNOREFRESH);
            usleep( SLEEPWHENNOREFRESH );
        }
    }

    if (refresh > 0) {

        DBG("Trace thread exiting, writing final DSP logs\n");

        /* try to collect anything that remained one more time */
        key = Gate_enterModule();

        Engine_fwriteTrace(hEngine, dspPrefix, dsp0TraceFilePtr);

        if (dsp0BiosFilePtr != NULL) {
//            LogClient_fwriteLogs(dsp0BiosFilePtr);
        }

        Gate_leaveModule(key);
    }

    if (dsp0BiosFilePtr != NULL) {
//        LogClient_disconnect();
    }

    /* for multi-process situations, release trace token back to RMS */
    if (Global_useLinkArbiter) {
        Server_disconnectTrace(hServer, traceToken);
    }

    Engine_close(hEngine);

    DBG("Quitting trace thread\n");

    /* and killing our offspring. */
    if (pipeThread != NULL) {
        DBG("Telling pipe thread to quit\n");
        f = fopen(cmdPipeFile, "w");
        if (f != NULL) {
            fputs(TRACECMD_QUIT, f);
            fclose(f);
            DBG("Wrote quit command, waiting for the pipe thread to join\n");
            if (pthread_join(pipeThread, NULL)) {
                ERR("Failed to join pipe thread\n");
            }
            DBG("Pipe thread joined.\n");
        }
    }

    return ((void *) 1);
}
Ejemplo n.º 22
0
/******************************************************************************
 * appMain
 ******************************************************************************/
Void appMain(Args * args)
{
    Buffer_Attrs            bAttrs      = Buffer_Attrs_DEFAULT;
    Time_Attrs              tAttrs      = Time_Attrs_DEFAULT;
    SPHENC1_Params          params      = Senc1_Params_DEFAULT;
    SPHENC1_DynamicParams   dynParams   = Senc1_DynamicParams_DEFAULT;
    Senc1_Handle            hSe1        = NULL;
    Engine_Handle           hEngine     = NULL;
    Buffer_Handle           hOutBuf     = NULL;
    Buffer_Handle           hInBuf      = NULL;
    Time_Handle             hTime       = NULL;
    FILE                   *inFile      = NULL;
    FILE                   *outFile     = NULL;
    Int                     numFrame    = 0;
    Int32                   bytesRead;
    UInt32                  time;

   printf("Starting application...\n");

   if (args->benchmark) {
        hTime = Time_create(&tAttrs);

        if (hTime == NULL) {
            printf("Failed to create Time object\n");
            goto cleanup;
        }
    }

    /* Initialize the codec engine run time */
    CERuntime_init();

    /* Initialize DMAI */
    Dmai_init();

    /* Open the output file */
    outFile = fopen(args->outFile, "wb");

    if (outFile == NULL) {
        printf("Failed to create output file %s\n", args->outFile);
        goto cleanup;
    }

    /* Open the input file */
    inFile = fopen(args->inFile, "rb");

    if (inFile == NULL) {
        printf("Failed to open input file %s\n", args->inFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
        if (setvbuf(outFile, vbuffer, _IOFBF, sizeof(vbuffer)) != 0) {
            printf("Failed to setvbuf on file descriptor\n");
            goto cleanup;
    }

    /* Open the codec engine */
    hEngine = Engine_open(args->engineName, NULL, NULL);

    if (hEngine == NULL) {
        printf("Failed to open codec engine %s\n", args->engineName);
        goto cleanup;
    }
    
    params.compandingLaw = args->compandingLaw;

    /* Create the SPHENC1 based speech encoder */
    hSe1 = Senc1_create(hEngine, args->codecName, &params, &dynParams);

    if (hSe1 == NULL) {
        printf("Failed to create %s\n", args->codecName);
        goto cleanup;
    }

    /* Align buffers to cache line boundary */    
    bAttrs.memParams.align = BUFSIZEALIGN; 
    
    /* Use cached buffers if requested */  
    if (args->cache) {
        bAttrs.memParams.flags = Memory_CACHED;
    } 
    
    /* Create an output buffer for encoded data */
    hOutBuf = Buffer_create(
        Dmai_roundUp(Senc1_getOutBufSize(hSe1), BUFSIZEALIGN), &bAttrs); 

    if (hOutBuf == NULL) {
        printf("Failed to create contiguous buffer\n");
        goto cleanup;
    }

    /* Create an input buffer for input data */
    hInBuf = Buffer_create(Dmai_roundUp(Senc1_getInBufSize(hSe1), BUFSIZEALIGN),
                           &bAttrs);

    if (hInBuf == NULL) {
        printf("Failed to create contiguous buffer\n");
        goto cleanup;
    }

    while (numFrame++ < args->numFrames) {
        printf("Frame %d: ", numFrame);
        if (args->benchmark) {
            if (Time_reset(hTime) < 0) {
                printf("Failed to reset timer\n");
                goto cleanup;
            }
        }

        /* Read raw PCM data from input file */
        bytesRead = fread(Buffer_getUserPtr(hInBuf), 1,
                          Senc1_getInBufSize(hSe1), inFile);

        if (bytesRead < Senc1_getInBufSize(hSe1)) {
            if (ferror(inFile)) {
                printf("Failed to read data from input file\n");
                goto cleanup;
            }
             printf("Failed to read full frame %ld bytes, read %ld bytes\n",
                                    Senc1_getInBufSize(hSe1),bytesRead);
             goto cleanup;
        }

        Buffer_setNumBytesUsed(hInBuf, bytesRead);

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                printf("Failed to get timer delta\n");
                goto cleanup;
            }
            printf("Read: %uus ", (Uns) time);
        }

        if (args->cache) {
            /*
             *  To meet xDAIS DMA Rule 7, when input buffers are cached, we
             *  must writeback the cache into physical memory.  Also, per DMA
             *  Rule 7, we must invalidate the output buffer from
             *  cache before providing it to any xDAIS algorithm.
             */
            Memory_cacheWbInv(Buffer_getUserPtr(hInBuf),
                              Buffer_getSize(hInBuf));

            /* Per DMA Rule 7, our output buffer cache lines must be cleaned */
            Memory_cacheInv(Buffer_getUserPtr(hOutBuf),
                            Buffer_getSize(hOutBuf));

            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    printf("Failed to get timer delta\n");
                    goto cleanup;
                }
                printf("Pre-process cache maintenance: %uus ", (Uns) time);
            }
        }

        /* Encode the speech buffer */
        if (Senc1_process(hSe1, hInBuf, hOutBuf) < 0) {
            printf("Failed to encode speech buffer\n");
            goto cleanup;
        }

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                printf("Failed to get timer delta\n");
                goto cleanup;
            }
            printf("Encode: %uus ", (Uns) time);
        }

        if (args->cache) {
            /* Writeback the outBuf. */
            Memory_cacheWb(Buffer_getUserPtr(hOutBuf), Buffer_getSize(hOutBuf));

            if (args->benchmark) {
                if (Time_delta(hTime, &time) < 0) {
                    printf("Failed to get timer delta\n");
                    goto cleanup;
                }
                printf("Post-process cache write back: %uus ", (Uns) time);
            }
        }

        printf("Write encoded speech data to output file \n");

        /* Write the encoded frame to the file system */
        if (Buffer_getNumBytesUsed(hOutBuf)) {
            if (fwrite(Buffer_getUserPtr(hOutBuf),
                       Buffer_getNumBytesUsed(hOutBuf), 1, outFile) != 1) {
                printf("Failed to write encoded speech data to file\n");
                goto cleanup;
            }
        }

        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                printf("Failed to get timer delta\n");
                goto cleanup;
            }
            printf("Write: %uus ", (Uns) time);

            if (Time_total(hTime, &time) < 0) {
                printf("Failed to get timer total\n");
                goto cleanup;
            }

            printf("Total: %uus\n", (unsigned int)time);
        }
    }
cleanup:
    /* Clean up the application */
    if (hSe1) {
        Senc1_delete(hSe1);
    }

    if (hInBuf) {
        Buffer_delete(hInBuf);
    }

    if (hOutBuf) {
        Buffer_delete(hOutBuf);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    if (hTime) {
        Time_delete(hTime);
    }

    if (inFile) {
        fclose(inFile);
    }

    if (outFile) {
        fclose(outFile);
    }

    printf("End of application.\n");

    return;
}
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    AUDDEC1_Handle dec = NULL;
    AUDENC1_Handle enc = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Memory_AllocParams allocParams;

    if (argc <= 1) {
        inFile = "./in.dat";
        outFile = "./out.dat";
        createInFileIfMissing(inFile);
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    encodedBuf = (XDAS_Int8 *)Memory_alloc(EFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);

#if USE_ANCDATA
    ancBuf = (XDAS_Int8 *)Memory_alloc(ENCANCBUFSIZE, &allocParams);
    if (ancBuf == NULL) {
        goto end;
    }
#endif

    if ((inBuf == NULL) || (encodedBuf == NULL) || (outBuf == NULL) ||
        (versionBuf == NULL)) {

        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video decoder on the engine */
    dec = AUDDEC1_create(ce, decoderName, NULL);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize video encoder on the engine */
    enc = AUDENC1_create(ce, encoderName, NULL);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
    /* teardown the codecs */
    if (enc) {
        AUDENC1_delete(enc);
    }
    if (dec) {
        AUDDEC1_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (encodedBuf) {
        Memory_free(encodedBuf, EFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

#if USE_ANCDATA
    if (ancBuf) {
        Memory_free(ancBuf, ENCANCBUFSIZE, &allocParams);
    }
#endif

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
Ejemplo n.º 24
0
/******************************************************************************
 * appMain
 ******************************************************************************/
Int appMain(Args * args)
{
    IMGDEC1_Params          params       = Idec1_Params_DEFAULT;
    IMGDEC1_DynamicParams   dynParams    = Idec1_DynamicParams_DEFAULT;
    Buffer_Attrs            bAttrs       = Buffer_Attrs_DEFAULT;
    BufferGfx_Attrs         gfxAttrs     = BufferGfx_Attrs_DEFAULT;
    Time_Attrs              tAttrs       = Time_Attrs_DEFAULT;   
    Idec1_Handle            hId          = NULL;
    Engine_Handle           hEngine      = NULL;
    Time_Handle             hTime        = NULL;
    Buffer_Handle           hInBuf       = NULL;
    Buffer_Handle           hOutBuf      = NULL;
    FILE                   *outFile      = NULL;
    FILE                   *inFile       = NULL;
    Int                     numBytes     = 0;
    Int                     ret          = Dmai_EOK;
    Cpu_Device              device;
    UInt32                  time;

    printf("Starting application...\n");
     
    if (args->benchmark) {
        hTime = Time_create(&tAttrs);

        if (hTime == NULL) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to create Time object\n");
            goto cleanup;
        }
    }

    /* Initialize the codec engine run time */
    CERuntime_init();

    /* Initialize DMAI */
    Dmai_init();

    /* Determine which device the application is running on */
    if (Cpu_getDevice(NULL, &device) < 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to determine target board\n");
        goto cleanup;
    }

    /* Open input file */
    inFile = fopen(args->inFile, "rb");

    if (inFile == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to open file %s\n", args->inFile);
        goto cleanup;
    }
    
    /* Open output file */
    outFile = fopen(args->outFile, "wb");
    
    if (outFile == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create output file %s\n", args->outFile);
        goto cleanup;
    }

    /* Using a larger vbuf to enhance performance of file i/o */
    if (setvbuf(outFile, vbuffer, _IOFBF, sizeof(vbuffer)) != 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to setvbuf on file descriptor\n");
        goto cleanup;   
    }
    
    /* Open the codec engine */
    hEngine = Engine_open(args->engineName, NULL, NULL);

    if (hEngine == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to open codec engine %s\n", args->engineName);
        goto cleanup;
    }

    /*
     * Set output color format to UYVY or Planar output.
     * Here XDM_DEFUALT sets the output planar format to
     * the planar fromat of the encoded image.
     *           
     */
    switch (args->oColorSpace) {
        case ColorSpace_UYVY:
            params.forceChromaFormat = XDM_YUV_422ILE;
            break;
        case ColorSpace_NOTSET:
            params.forceChromaFormat = XDM_CHROMAFORMAT_DEFAULT;
            break;
        case ColorSpace_YUV444P:
            params.forceChromaFormat = XDM_YUV_444P;
            break;
        case ColorSpace_YUV422P:
            params.forceChromaFormat = XDM_YUV_422P;
            break;
        case ColorSpace_YUV420P:
            params.forceChromaFormat = XDM_YUV_420P;
            break;
        case ColorSpace_YUV420PSEMI:
            params.forceChromaFormat = XDM_YUV_420SP;
            break;
        case ColorSpace_GRAY:
            params.forceChromaFormat = ColorSpace_GRAY;
            break;
        default:
            ret = Dmai_EFAIL;
            fprintf(stderr,"Unsupported output color space %d.\n", args->oColorSpace);
            goto cleanup;
    }

    if ((device == Cpu_Device_DM365) || (device == Cpu_Device_DM368)) {
        params.maxHeight = VideoStd_720P_HEIGHT;
        params.maxWidth  = VideoStd_720P_WIDTH;
    }

    if (device == Cpu_Device_DM6467) {
        params.maxHeight = VideoStd_720P_HEIGHT;
        params.maxWidth  = VideoStd_720P_WIDTH;
    }

    /* Create the image decoder */
    hId = Idec1_create(hEngine, args->codecName, &params, &dynParams);

    if (hId == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create image decoder: %s\n", args->codecName);
        goto cleanup;
    }

    /* Align buffers to cache line boundary */    
    gfxAttrs.bAttrs.memParams.align = bAttrs.memParams.align = BUFSIZEALIGN; 
    
    /* Use cached buffers if requested */    
    if (args->cache) {
        gfxAttrs.bAttrs.memParams.flags = bAttrs.memParams.flags 
            = Memory_CACHED;
    } 
    
    gfxAttrs.colorSpace     = args->oColorSpace;
    gfxAttrs.dim.width      = params.maxWidth;
    gfxAttrs.dim.height     = params.maxHeight;
    gfxAttrs.dim.lineLength = BufferGfx_calcLineLength(params.maxWidth,
                                                       gfxAttrs.colorSpace);
    
    /* Create an output buffer for decoded data */
    hOutBuf = Buffer_create(
        Dmai_roundUp(Idec1_getOutBufSize(hId), BUFSIZEALIGN), 
        BufferGfx_getBufferAttrs(&gfxAttrs));

    if (hOutBuf == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create contiguous buffers\n");
        goto cleanup;
    }

    /* Create an input buffer for encoded data */
    hInBuf = Buffer_create(Dmai_roundUp(Idec1_getInBufSize(hId), BUFSIZEALIGN), 
        &bAttrs);

    if (hInBuf == NULL) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to create contiguous buffers\n");
        goto cleanup;
    }
   
    /* Read encoded image data */
    numBytes = fread(Buffer_getUserPtr(hInBuf), 1,
                     Idec1_getInBufSize(hId), inFile);
                     
    Buffer_setNumBytesUsed(hInBuf, numBytes);

    if (args->benchmark) {
        if (Time_reset(hTime) < 0) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to reset timer\n");
            goto cleanup;
        }
    }

    if (args->cache) {
        /*  
         *  To meet xDAIS DMA Rule 7, when input buffers are cached, we 
         *  must writeback the cache into physical memory.  Also, per DMA 
         *  Rule 7, we must invalidate the output buffer from
         *  cache before providing it to any xDAIS algorithm.
         */
        Memory_cacheWbInv(Buffer_getUserPtr(hInBuf), Buffer_getSize(hInBuf));
        /* Per DMA Rule 7, our output buffer cache lines must be cleaned */
        Memory_cacheInv(Buffer_getUserPtr(hOutBuf), Buffer_getSize(hOutBuf));
        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer delta\n");
                goto cleanup;
            }
    
            printf("Pre-process cache maintenance: %uus \n", (Uns) time);
        }
    }

    printf("Decoding image...\n");
        
    /* Decode the image frame */
    ret = Idec1_process(hId, hInBuf, hOutBuf);
    
    if (ret < 0) {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Failed to decode image buffer\n");
        goto cleanup;
    }
    
    if (args->benchmark) {
        if (Time_delta(hTime, &time) < 0) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to get timer delta\n");
            goto cleanup;
        }
    
        printf("Frame - Decode: %uus \n", (unsigned int)time);
    }
    
    if (args->cache) {
        /* Writeback the outBuf. */
        Memory_cacheWb(Buffer_getUserPtr(hOutBuf), Buffer_getSize(hOutBuf));
    
        if (args->benchmark) {
            if (Time_delta(hTime, &time) < 0) {
                ret = Dmai_EFAIL;
                fprintf(stderr,"Failed to get timer delta\n");
                goto cleanup;
            }
    
            printf("Post-process cache write back: %uus ", (Uns) time);
        }
    }

    /* Write decoded image to a file */
   if (BufferGfx_getColorSpace(hOutBuf) == ColorSpace_UYVY){
        if (writeFrameUYVY(hOutBuf, outFile) < 0) {
           ret = Dmai_EFAIL;
           fprintf(stderr,"Failed to write image to file\n");
           goto cleanup; 
       }
    } else if (BufferGfx_getColorSpace(hOutBuf) == ColorSpace_YUV420PSEMI) {
        if (writeFrameSemiPlanar(hOutBuf, outFile) < 0) {
           ret = Dmai_EFAIL;
           fprintf(stderr,"Failed to write image to file\n");
           goto cleanup; 
       }
    }
    else if (BufferGfx_getColorSpace(hOutBuf) == ColorSpace_YUV420P
             || ColorSpace_YUV422P || ColorSpace_YUV444P || ColorSpace_GRAY){
        /* For XDM_GRAY ignoring the color planes */
        if (args->oColorSpace == ColorSpace_GRAY){
            BufferGfx_setColorSpace (hOutBuf, ColorSpace_GRAY); 
        }        
        if (writeFramePlanar(hOutBuf, outFile) < 0) {
           ret = Dmai_EFAIL;
           fprintf(stderr,"Failed to write image to file\n");
           goto cleanup; 
       }
    }
    else {
        ret = Dmai_EFAIL;
        fprintf(stderr,"Invalid output colorspace.\n");
        goto cleanup;     
    }

    if (args->benchmark) {
        if (Time_total(hTime, &time) < 0) {
            ret = Dmai_EFAIL;
            fprintf(stderr,"Failed to get timer total\n");
            goto cleanup;
        }
    
        printf("Total: %uus\n", (unsigned int)time);
    }
       
cleanup:
    /* Clean up the application */
    if (hId) {
        Idec1_delete(hId);
    }
    
    if (hInBuf) {
        Buffer_delete(hInBuf);
    }

    if (hOutBuf) {
        Buffer_delete(hOutBuf);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    if (hTime) {
        Time_delete(hTime);
    }

    if (inFile) {
        fclose(inFile);
    }
 
    if (outFile) {
        fclose(outFile);
    }
    
    printf("End of application.\n");

    if (ret == Dmai_EFAIL) 
        return 1;
    else    
        return 0;
}