Chinaunix首页 | 论坛 | 博客
  • 博客访问: 51905
  • 博文数量: 50
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-30 20:59
文章分类

全部博文(50)

文章存档

2015年(9)

2014年(41)

我的朋友

分类: Android平台

2014-07-25 14:12:54

Android Camera OMX方式数据流分析

在上一篇文章中,对preview过程做了一些简单的分析,其实没有很深入的分析,这篇文章就要在上一篇文章的基础之上深入分析数据到底是怎么传递的,其一,图像是怎样显示的,其二,图像是怎样保存的,这里只针对OMX这种方式进行分析,其实V4L2方式只是在CameraAdapter这里的实现不一样,其他层的调用基本是一致的,理解了OMX方法数据的流向,V4L2方式就没有什么问题

现在开始步入正题了
首先我们必须明确的是camera的图像是需要buffer存储的,那么这块内存是在哪里分配的呢
android camera的操作过程相信大家都比较熟悉,即使不是android 的camera,其他camera也都是一样的,只要打开camera,就自动进入preview模式,然后你点某个button拍了一张照片,或者点了某个button录了一段视频,这是camera的最主要功能,那么应该只有两种可能吧,就是一开始camera被调用的时候内存就申请了,另一种就是打开camera后,开始preview前申请内存,但肯定是不能再preview之后的,很容易理解啊,就像睡觉时先眯起眼睛在睡着的,而不是先睡着再眯起眼睛,嘻嘻
不知道的可以大体看一下frameworks的app,你可以发现好像是没有申请什么内存的方法出现,当然我没有那么细心的去看,那是因为我是认为是通过上面的第二种可能申请内存的,现在就开始看看
camera 打开后,一切都初始化ok,然后就真正的开始干活了,那就是调用startPreview了,开始preview啊,这从app一路高歌,知道走到hal层才去申请这个空间,让我不禁感慨app层就是爽,一声令下,底层你怎么去实现我不管,我只要结果,多有范儿,底层就用足了力气实现去了
再说细一点,这个内存的申请是在hal层startPreview的cameraPreviewInitialization方法中实现的,先贴出代码,待会分析
  1. status_t CameraHal::allocPreviewBufs(int width, int height, const char* previewFormat, unsigned int buffercount, unsigned int &max_queueable)
  2. {
  3.     status_t ret = NO_ERROR;

  4.     LOG_FUNCTION_NAME;

  5.     if(mDisplayAdapter.get() == NULL)
  6.     {
  7.         // Memory allocation of preview buffers is now placed in gralloc
  8.         // CameraHal should not allocate preview buffers without DisplayAdapter
  9.         return NO_MEMORY;
  10.     }

  11.     if(!mPreviewBuffers)
  12.     {
  13.         mPreviewLength = 0;
  14.         mPreviewBuffers = mDisplayAdapter->allocateBufferList(width, height,
  15.                                                                     previewFormat,
  16.                                                                     mPreviewLength,
  17.                                                                     buffercount);
  18.         if (NULL == mPreviewBuffers ) {
  19.             CAMHAL_LOGEA("Couldn't allocate preview buffers");
  20.             return NO_MEMORY;
  21.         }

  22.         mPreviewOffsets = (uint32_t *) mDisplayAdapter->getOffsets();
  23.         if ( NULL == mPreviewOffsets ) {
  24.             CAMHAL_LOGEA("Buffer mapping failed");
  25.             return BAD_VALUE;
  26.         }
  27.         //指定bufferProvider
  28.         mBufProvider = (BufferProvider*) mDisplayAdapter.get();
  29.         //获取mac_queueable
  30.         ret = mDisplayAdapter->maxQueueableBuffers(max_queueable);
  31.         if (ret != NO_ERROR) {
  32.             return ret;
  33.         }
  34.     }

  35.     LOG_FUNCTION_NAME_EXIT;

  36.     return ret;
  37. }
这个方法传入了几个参数,前几个参数是在这个方法之前都可以得到的,方法没什么难的,很容易理解
width:显示的宽
height:显示的高
previewFrame:显示的frame
buffercount:buffer的个数
max_queueable:这个参数以引用方式调用,重点是他是要往外带东西的,嘻嘻
上面的代码在开始分析之前,先大体看一下,也许你可以猜到,这里申请的mPreviewBuffer到底是用来干什么的,他是一个CameraFrame类型,底层获取到的数据最后都会打包成CameraFrame类型在往app层转交,或者直接通过overlay方式显示出来
在这之后还申请了一块memory,其实我不是很理解具体有什么意义,先看看吧
  1. status_t CameraHal::allocPreviewDataBufs(size_t size, size_t bufferCount)
  2. {
  3.     status_t ret = NO_ERROR;
  4.     int bytes;

  5.     LOG_FUNCTION_NAME;

  6.     bytes = size;

  7.     if ( NO_ERROR == ret )
  8.         {
  9.         if( NULL != mPreviewDataBuffers )
  10.             {
  11.             ret = freePreviewDataBufs();
  12.             }
  13.         }

  14.     if ( NO_ERROR == ret )
  15.         {
  16.         bytes = ((bytes+4095)/4096)*4096;
  17.         mPreviewDataBuffers = mMemoryManager->allocateBufferList(0, 0, NULL, bytes, bufferCount);

  18.         CAMHAL_LOGDB("Size of Preview data buffer = %d", bytes);
  19.         if( NULL == mPreviewDataBuffers )
  20.             {
  21.             CAMHAL_LOGEA("Couldn't allocate image buffers using memory manager");
  22.             ret = -NO_MEMORY;
  23.             }
  24.         else
  25.             {
  26.             bytes = size;
  27.             }
  28.         }

  29.     if ( NO_ERROR == ret )
  30.         {
  31.         mPreviewDataFd = mMemoryManager->getFd();
  32.         mPreviewDataLength = bytes;
  33.         mPreviewDataOffsets = mMemoryManager->getOffsets();
  34.         }
  35.     else
  36.         {
  37.         mPreviewDataFd = -1;
  38.         mPreviewDataLength = 0;
  39.         mPreviewDataOffsets = NULL;
  40.         }

  41.     LOG_FUNCTION_NAME_EXIT;

  42.     return ret;
  43. }
这里是通过mMemoryManager申请的一块内存区域,这里先知道这个内存区mPreviewDataBuffers
这里首先对mPreviewDataBuffers这块内存相关的属性信息打包到BuffersDescriptor这个结构中,然后调用
mCameraAdapter->sendCommand(CameraAdapter::CAMERA_USE_BUFFERS_PREVIEW_DATA, ( int ) &desc);
我们看看OMXCameraAdapter是怎样对应实现的吧
  1. case CameraAdapter::CAMERA_USE_BUFFERS_PREVIEW_DATA:
  2.                     CAMHAL_LOGDA("Use buffers for preview data");
  3.                     desc = ( BuffersDescriptor * ) value1;

  4.                     if ( NULL == desc )
  5.                         {
  6.                         CAMHAL_LOGEA("Invalid preview data buffers!");
  7.                         return -EINVAL;
  8.                         }

  9.                     if ( ret == NO_ERROR )
  10.                         {
  11.                         ret = setState(operation);
  12.                         }

  13.                     if ( ret == NO_ERROR )
  14.                         {
  15.                         Mutex::Autolock lock(mPreviewDataBufferLock);
  16.                         mPreviewDataBuffers = desc->mBuffers;
  17.                         mPreviewDataBuffersLength = desc->mLength;
  18.                         mPreviewDataBuffersAvailable.clear();
  19.                         for ( uint32_t i = 0 ; i < desc->mMaxQueueable ; i++ )
  20.                             {
  21.                             mPreviewDataBuffersAvailable.add(&mPreviewDataBuffers[i], 0);
  22.                             }
  23.                         // initial ref count for undeqeueued buffers is 1 since buffer provider
  24.                         // is still holding on to it
  25.                         for ( uint32_t i = desc->mMaxQueueable ; i < desc->mCount ; i++ )
  26.                             {
  27.                             mPreviewDataBuffersAvailable.add(&mPreviewDataBuffers[i], 1);
  28.                             }
  29.                         }

  30.                     if ( NULL != desc )
  31.                         {
  32.                         ret = useBuffers(CameraAdapter::CAMERA_MEASUREMENT,
  33.                                          desc->mBuffers,
  34.                                          desc->mCount,
  35.                                          desc->mLength,
  36.                                          desc->mMaxQueueable);
  37.                         }

  38.                     if ( ret == NO_ERROR )
  39.                         {
  40.                         ret = commitState();
  41.                         }
  42.                     else
  43.                         {
  44.                         ret |= rollbackState();
  45.                         }

  46.                     break;
这里先不做过多说明,之后遇到了再说,最终他会调用到OMXCameraAdapter的UseBuffersPreviewData方法,看看他的实现
  1. status_t OMXCameraAdapter::UseBuffersPreviewData(CameraBuffer * bufArr, int num)
  2. {
  3.     status_t ret = NO_ERROR;
  4.     OMX_ERRORTYPE eError = OMX_ErrorNone;
  5.     OMXCameraPortParameters * measurementData = NULL;
  6.     Mutex::Autolock lock( mPreviewDataBufferLock);

  7.     LOG_FUNCTION_NAME;

  8.     if ( mComponentState != OMX_StateLoaded )
  9.         {
  10.         CAMHAL_LOGEA("Calling UseBuffersPreviewData() when not in LOADED state");
  11.         return BAD_VALUE;
  12.         }

  13.     if ( NULL == bufArr )
  14.         {
  15.         CAMHAL_LOGEA("NULL pointer passed for buffArr");
  16.         return BAD_VALUE;
  17.         }

  18.     if ( 0 != mUsePreviewDataSem.Count() )
  19.         {
  20.         CAMHAL_LOGEB("Error mUsePreviewDataSem semaphore count %d", mUsePreviewDataSem.Count());
  21.         LOG_FUNCTION_NAME_EXIT;
  22.         return NO_INIT;
  23.         }

  24.     if ( NO_ERROR == ret )
  25.         {
  26.         这里只是把num这个参数保存到measurementPortIndex对应的参数mNumBufs
  27.         measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
  28.         measurementData->mNumBufs = num ;
  29.         }

  30.     if ( NO_ERROR == ret )
  31.         {
  32.          ///Register for port enable event on measurement port
  33.         ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
  34.                                       OMX_EventCmdComplete,
  35.                                       OMX_CommandPortEnable,
  36.                                       mCameraAdapterParameters.mMeasurementPortIndex,
  37.                                       mUsePreviewDataSem);

  38.         if ( ret == NO_ERROR )
  39.             {
  40.             CAMHAL_LOGDB("Registering for event %d", ret);
  41.             }
  42.         else
  43.             {
  44.             CAMHAL_LOGEB("Error in registering for event %d", ret);
  45.             goto EXIT;
  46.             }
  47.         }

  48.     if ( NO_ERROR == ret )
  49.         {
  50.          //Enable MEASUREMENT Port
  51.          eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
  52.                                       OMX_CommandPortEnable,
  53.                                       mCameraAdapterParameters.mMeasurementPortIndex,
  54.                                       NULL);

  55.             if ( eError == OMX_ErrorNone )
  56.                 {
  57.                 CAMHAL_LOGDB("OMX_SendCommand(OMX_CommandPortEnable) -0x%x", eError);
  58.                 }
  59.             else
  60.                 {
  61.                 CAMHAL_LOGEB("OMX_SendCommand(OMX_CommandPortEnable) -0x%x", eError);
  62.                 goto EXIT;
  63.                 }
  64.         }

  65.     if ( NO_ERROR == ret )
  66.         {
  67.         ret = mUsePreviewDataSem.WaitTimeout(OMX_CMD_TIMEOUT);

  68.         //If somethiing bad happened while we wait
  69.         if (mComponentState == OMX_StateInvalid)
  70.           {
  71.             CAMHAL_LOGEA("Invalid State after measurement port enable Exitting!!!");
  72.             goto EXIT;
  73.           }

  74.         if ( NO_ERROR == ret )
  75.             {
  76.             CAMHAL_LOGDA("Port enable event arrived on measurement port");
  77.             }
  78.         else
  79.             {
  80.             ret |= RemoveEvent(mCameraAdapterParameters.mHandleComp,
  81.                                OMX_EventCmdComplete,
  82.                                OMX_CommandPortEnable,
  83.                                mCameraAdapterParameters.mMeasurementPortIndex,
  84.                                NULL);
  85.             CAMHAL_LOGEA("Timeout expoired during port enable on measurement port");
  86.             goto EXIT;
  87.             }

  88.         CAMHAL_LOGDA("Port enable event arrived on measurement port");
  89.         }

  90.     LOG_FUNCTION_NAME_EXIT;

  91.     return ret;
  92. EXIT:
  93.     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
  94.     performCleanupAfterError();
  95.     LOG_FUNCTION_NAME_EXIT;
  96.     return (ret | ErrorUtils::omxToAndroidError(eError));
  97. }
接下来首先对mPreviewBuffers这块内存相关的属性信息打包到BuffersDescriptor这个结构中,然后调用
ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_USE_BUFFERS_PREVIEW, ( int ) &desc);
看看他的具体实现吧
  1. case CameraAdapter::CAMERA_USE_BUFFERS_PREVIEW:
  2.                 CAMHAL_LOGDA("Use buffers for preview");
  3.                 desc = ( BuffersDescriptor * ) value1;

  4.                 if ( NULL == desc )
  5.                     {
  6.                     CAMHAL_LOGEA("Invalid preview buffers!");
  7.                     return -EINVAL;
  8.                     }

  9.                 if ( ret == NO_ERROR )
  10.                     {
  11.                     ret = setState(operation);
  12.                     }

  13.                 if ( ret == NO_ERROR )
  14.                     {
  15.                     Mutex::Autolock lock(mPreviewBufferLock);
  16.                     mPreviewBuffers = desc->mBuffers;
  17.                     mPreviewBuffersLength = desc->mLength;
  18.                     mPreviewBuffersAvailable.clear();
  19.                     mSnapshotBuffersAvailable.clear();
  20.                     for ( uint32_t i = 0 ; i < desc->mMaxQueueable ; i++ )
  21.                         {
  22.                         mPreviewBuffersAvailable.add(&mPreviewBuffers[i], 0);
  23.                         }
  24.                     // initial ref count for undeqeueued buffers is 1 since buffer provider
  25.                     // is still holding on to it
  26.                     for ( uint32_t i = desc->mMaxQueueable ; i < desc->mCount ; i++ )
  27.                         {
  28.                         mPreviewBuffersAvailable.add(&mPreviewBuffers[i], 1);
  29.                         }
  30.                     }

  31.                 if ( NULL != desc )
  32.                     {
  33.                     ret = useBuffers(CameraAdapter::CAMERA_PREVIEW,
  34.                                      desc->mBuffers,
  35.                                      desc->mCount,
  36.                                      desc->mLength,
  37.                                      desc->mMaxQueueable);
  38.                     }

  39.                 if ( ret == NO_ERROR )
  40.                     {
  41.                     ret = commitState();
  42.                     }
  43.                 else
  44.                     {
  45.                     ret |= rollbackState();
  46.                     }

  47.                 break;
到这里大家看到了这个过程跟上面的调用时那么的相似,接下来也看看他在OMXCameraAdapter的实现方法UseBuffersPreview
  1. status_t OMXCameraAdapter::UseBuffersPreview(CameraBuffer * bufArr, int num)
  2. {
  3.     status_t ret = NO_ERROR;
  4.     OMX_ERRORTYPE eError = OMX_ErrorNone;
  5.     int tmpHeight, tmpWidth;

  6.     LOG_FUNCTION_NAME;

  7.     if(!bufArr)
  8.         {
  9.         CAMHAL_LOGEA("NULL pointer passed for buffArr");
  10.         LOG_FUNCTION_NAME_EXIT;
  11.         return BAD_VALUE;
  12.         }

  13.     OMXCameraPortParameters * mPreviewData = NULL;
  14.     OMXCameraPortParameters *measurementData = NULL;
  15.     这里暂时将mPreviewData和measurementData这两个指针分别指向preview port和measurement port的port params结构,方便之后对这两个port的设置
  16.     mPreviewData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
  17.     measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
  18.     mPreviewData->mNumBufs = num ;

  19.     if ( 0 != mUsePreviewSem.Count() )
  20.         {
  21.         CAMHAL_LOGEB("Error mUsePreviewSem semaphore count %d", mUsePreviewSem.Count());
  22.         LOG_FUNCTION_NAME_EXIT;
  23.         return NO_INIT;
  24.         }

  25.     if(mPreviewData->mNumBufs != num)
  26.         {
  27.         CAMHAL_LOGEA("Current number of buffers doesnt equal new num of buffers passed!");
  28.         LOG_FUNCTION_NAME_EXIT;
  29.         return BAD_VALUE;
  30.         }

  31.     mStateSwitchLock.lock();

  32.     这里两个横线之中的内容,其实我没有很理解这些东西是干什么用的,不影响我们接着往下看,暂不深入追究
  33.     if ( mComponentState == OMX_StateLoaded ) {

  34.         if (mPendingPreviewSettings & SetLDC) {
  35.             mPendingPreviewSettings &= ~SetLDC;
  36.             ret = setLDC(mIPP);
  37.             if ( NO_ERROR != ret ) {
  38.                 CAMHAL_LOGEB("setLDC() failed %d", ret);
  39.             }
  40.         }

  41.         if (mPendingPreviewSettings & SetNSF) {
  42.             mPendingPreviewSettings &= ~SetNSF;
  43.             ret = setNSF(mIPP);
  44.             if ( NO_ERROR != ret ) {
  45.                 CAMHAL_LOGEB("setNSF() failed %d", ret);
  46.             }
  47.         }

  48.         if (mPendingPreviewSettings & SetCapMode) {
  49.             mPendingPreviewSettings &= ~SetCapMode;
  50.             ret = setCaptureMode(mCapMode);
  51.             if ( NO_ERROR != ret ) {
  52.                 CAMHAL_LOGEB("setCaptureMode() failed %d", ret);
  53.             }
  54.         }

  55.         if(mCapMode == OMXCameraAdapter::VIDEO_MODE) {

  56.             if (mPendingPreviewSettings & SetVNF) {
  57.                 mPendingPreviewSettings &= ~SetVNF;
  58.                 ret = enableVideoNoiseFilter(mVnfEnabled);
  59.                 if ( NO_ERROR != ret){
  60.                     CAMHAL_LOGEB("Error configuring VNF %x", ret);
  61.                 }
  62.             }

  63.             if (mPendingPreviewSettings & SetVSTAB) {
  64.                 mPendingPreviewSettings &= ~SetVSTAB;
  65.                 ret = enableVideoStabilization(mVstabEnabled);
  66.                 if ( NO_ERROR != ret) {
  67.                     CAMHAL_LOGEB("Error configuring VSTAB %x", ret);
  68.                 }
  69.             }

  70.         }
  71.     }

  72.     ret = setSensorOrientation(mSensorOrientation);
  73.     if ( NO_ERROR != ret )
  74.         {
  75.         CAMHAL_LOGEB("Error configuring Sensor Orientation %x", ret);
  76.         mSensorOrientation = 0;
  77.         }


  78.     if ( mComponentState == OMX_StateLoaded )
  79.         {
  80.         ///Register for IDLE state switch event
  81.         ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
  82.                                OMX_EventCmdComplete,
  83.                                OMX_CommandStateSet,
  84.                                OMX_StateIdle,
  85.                                mUsePreviewSem);

  86.         if(ret!=NO_ERROR)
  87.             {
  88.             CAMHAL_LOGEB("Error in registering for event %d", ret);
  89.             goto EXIT;
  90.             }

  91.         ///Once we get the buffers, move component state to idle state and pass the buffers to OMX comp using UseBuffer
  92.         eError = OMX_SendCommand (mCameraAdapterParameters.mHandleComp ,
  93.                                   OMX_CommandStateSet,
  94.                                   OMX_StateIdle,
  95.                                   NULL);

  96.         CAMHAL_LOGDB("OMX_SendCommand(OMX_CommandStateSet) 0x%x", eError);

  97.         GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);

  98.         mComponentState = OMX_StateIdle;
  99.         }
  100.     else
  101.         {
  102.             ///Register for Preview port ENABLE event
  103.             ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
  104.                                    OMX_EventCmdComplete,
  105.                                    OMX_CommandPortEnable,
  106.                                    mCameraAdapterParameters.mPrevPortIndex,
  107.                                    mUsePreviewSem);

  108.             if ( NO_ERROR != ret )
  109.                 {
  110.                 CAMHAL_LOGEB("Error in registering for event %d", ret);
  111.                 goto EXIT;
  112.                 }

  113.             ///Enable Preview Port
  114.             eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
  115.                                      OMX_CommandPortEnable,
  116.                                      mCameraAdapterParameters.mPrevPortIndex,
  117.                                      NULL);
  118.         }


  119.     ///Configure DOMX to use either gralloc handles or vptrs
  120.     OMX_TI_PARAMUSENATIVEBUFFER domxUseGrallocHandles;
  121.     OMX_INIT_STRUCT_PTR (&domxUseGrallocHandles, OMX_TI_PARAMUSENATIVEBUFFER);

  122.     domxUseGrallocHandles.nPortIndex = mCameraAdapterParameters.mPrevPortIndex;
  123.     domxUseGrallocHandles.bEnable = OMX_TRUE;

  124.     eError = OMX_SetParameter(mCameraAdapterParameters.mHandleComp, (OMX_INDEXTYPE)OMX_TI_IndexUseNativeBuffers, &domxUseGrallocHandles);
  125.     if(eError!=OMX_ErrorNone)
  126.         {
  127.         CAMHAL_LOGEB("OMX_SetParameter - %x", eError);
  128.         }
  129.     GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);

  130.     OMX_BUFFERHEADERTYPE *pBufferHdr;
  131.     for(int index=0;index<num;index++) {
  132.         OMX_U8 *ptr;

  133.         ptr = (OMX_U8 *)camera_buffer_get_omx_ptr (&bufArr[index]);
  134.         eError = OMX_UseBuffer( mCameraAdapterParameters.mHandleComp,
  135.                                 &pBufferHdr,
  136.                                 mCameraAdapterParameters.mPrevPortIndex,
  137.                                 0,
  138.                                 mPreviewData->mBufSize,
  139.                                 ptr);
  140.         if(eError!=OMX_ErrorNone)
  141.             {
  142.             CAMHAL_LOGEB("OMX_UseBuffer-0x%x", eError);
  143.             }
  144.         GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
  145.         这里在我看来还是很重要的,将我们从hal层申请的内存与preview port的bufferheader关联到一起,这里先填充一个bufferheader然后指向port param的mBufferHeader
  146.         pBufferHdr->pAppPrivate = (OMX_PTR)&bufArr[index];
  147.         pBufferHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
  148.         pBufferHdr->nVersion.s.nVersionMajor = 1 ;
  149.         pBufferHdr->nVersion.s.nVersionMinor = 1 ;
  150.         pBufferHdr->nVersion.s.nRevision = 0 ;
  151.         pBufferHdr->nVersion.s.nStep = 0;
  152.         mPreviewData->mBufferHeader[index] = pBufferHdr;
  153.     }

  154.     if ( mMeasurementEnabled )
  155.         {

  156.         for( int i = 0; i < num; i++ )
  157.             {
  158.             OMX_BUFFERHEADERTYPE *pBufHdr;
  159.             OMX_U8 *ptr;

  160.             ptr = (OMX_U8 *)camera_buffer_get_omx_ptr (&mPreviewDataBuffers[i]);
  161.             eError = OMX_UseBuffer( mCameraAdapterParameters.mHandleComp,
  162.                                     &pBufHdr,
  163.                                     mCameraAdapterParameters.mMeasurementPortIndex,
  164.                                     0,
  165.                                     measurementData->mBufSize,
  166.                                     ptr);

  167.              if ( eError == OMX_ErrorNone )
  168.                 {
  169.                 这里在我看来还是很重要的,将我们从hal层申请的内存与measurement port的bufferheader关联到一起,这里先填充一个bufferheader然后指向port param的mBufferHeader
  170.                 pBufHdr->pAppPrivate = (OMX_PTR *)&mPreviewDataBuffers[i];
  171.                 pBufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
  172.                 pBufHdr->nVersion.s.nVersionMajor = 1 ;
  173.                 pBufHdr->nVersion.s.nVersionMinor = 1 ;
  174.                 pBufHdr->nVersion.s.nRevision = 0 ;
  175.                 pBufHdr->nVersion.s.nStep = 0;
  176.                 measurementData->mBufferHeader[i] = pBufHdr;
  177.                 }
  178.             else
  179.                 {
  180.                 CAMHAL_LOGEB("OMX_UseBuffer -0x%x", eError);
  181.                 ret = BAD_VALUE;
  182.                 break;
  183.                 }
  184.             }

  185.         }

  186.     CAMHAL_LOGDA("Registering preview buffers");

  187.     ret = mUsePreviewSem.WaitTimeout(OMX_CMD_TIMEOUT);

  188.     //If somethiing bad happened while we wait
  189.     if (mComponentState == OMX_StateInvalid)
  190.       {
  191.         CAMHAL_LOGEA("Invalid State after Registering preview buffers Exitting!!!");
  192.         goto EXIT;
  193.       }

  194.     if ( NO_ERROR == ret )
  195.         {
  196.         CAMHAL_LOGDA("Preview buffer registration successfull");
  197.         }
  198.     else
  199.         {
  200.         if ( mComponentState == OMX_StateLoaded )
  201.             {
  202.             ret |= RemoveEvent(mCameraAdapterParameters.mHandleComp,
  203.                                OMX_EventCmdComplete,
  204.                                OMX_CommandStateSet,
  205.                                OMX_StateIdle,
  206.                                NULL);
  207.             }
  208.         else
  209.             {
  210.             ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
  211.                                OMX_EventCmdComplete,
  212.                                OMX_CommandPortEnable,
  213.                                mCameraAdapterParameters.mPrevPortIndex,
  214.                                NULL);
  215.             }
  216.         CAMHAL_LOGEA("Timeout expired on preview buffer registration");
  217.         goto EXIT;
  218.         }

  219.     LOG_FUNCTION_NAME_EXIT;

  220.     return (ret | ErrorUtils::omxToAndroidError(eError));

  221.     ///If there is any failure, we reach here.
  222.     ///Here, we do any resource freeing and convert from OMX error code to Camera Hal error code
  223. EXIT:
  224.     mStateSwitchLock.unlock();

  225.     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
  226.     performCleanupAfterError();
  227.     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);

  228.     LOG_FUNCTION_NAME_EXIT;

  229.     return (ret | ErrorUtils::omxToAndroidError(eError));
  230. }
到这里我所关注的初始化已经完成了,其实一些初始动作,这里暂时不关注,最后hal层调用OMXCameraAdapter的startPreview真正要开始preview了
接下来的分析就要仔细一点了,相对来说很重要,不能马虎,慢慢研究startPreview的实现吧
  1. status_t OMXCameraAdapter::startPreview()
  2. {
  3.     status_t ret = NO_ERROR;
  4.     OMX_ERRORTYPE eError = OMX_ErrorNone;
  5.     OMXCameraPortParameters *mPreviewData = NULL;
  6.     OMXCameraPortParameters *measurementData = NULL;

  7.     LOG_FUNCTION_NAME;

  8.     if( 0 != mStartPreviewSem.Count() )
  9.         {
  10.         CAMHAL_LOGEB("Error mStartPreviewSem semaphore count %d", mStartPreviewSem.Count());
  11.         ret = NO_INIT;
  12.         goto EXIT;
  13.         }

  14.     // Enable all preview mode extra data.
  15.     if ( OMX_ErrorNone == eError) {
  16.         ret |= setExtraData(true, mCameraAdapterParameters.mPrevPortIndex, OMX_AncillaryData);
  17.         ret |= setExtraData(true, OMX_ALL, OMX_TI_VectShotInfo);
  18.     }
  19.     
  20.     这里获取到preview port和measurement port param结构的指针,方便之后的使用
  21.     mPreviewData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
  22.     measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];

  23.     if( OMX_StateIdle == mComponentState )
  24.         {
  25.         ///Register for EXECUTING state transition.
  26.         ///This method just inserts a message in Event Q, which is checked in the callback
  27.         ///The sempahore passed is signalled by the callback
  28.         ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
  29.                                OMX_EventCmdComplete,
  30.                                OMX_CommandStateSet,
  31.                                OMX_StateExecuting,
  32.                                mStartPreviewSem);

  33.         if(ret!=NO_ERROR)
  34.             {
  35.             CAMHAL_LOGEB("Error in registering for event %d", ret);
  36.             goto EXIT;
  37.             }

  38.         ///Switch to EXECUTING state,为fillbuffer做准备
  39.         eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
  40.                                  OMX_CommandStateSet,
  41.                                  OMX_StateExecuting,
  42.                                  NULL);

  43.         if(eError!=OMX_ErrorNone)
  44.             {
  45.             CAMHAL_LOGEB("OMX_SendCommand(OMX_StateExecuting)-0x%x", eError);
  46.             }

  47.         CAMHAL_LOGDA("+Waiting for component to go into EXECUTING state");
  48.         ret = mStartPreviewSem.WaitTimeout(OMX_CMD_TIMEOUT);

  49.         //If somethiing bad happened while we wait
  50.         if (mComponentState == OMX_StateInvalid)
  51.           {
  52.             CAMHAL_LOGEA("Invalid State after IDLE_EXECUTING Exitting!!!");
  53.             goto EXIT;
  54.           }

  55.         if ( NO_ERROR == ret )
  56.             {
  57.             CAMHAL_LOGDA("+Great. Component went into executing state!!");
  58.             }
  59.         else
  60.             {
  61.             ret |= RemoveEvent(mCameraAdapterParameters.mHandleComp,
  62.                                OMX_EventCmdComplete,
  63.                                OMX_CommandStateSet,
  64.                                OMX_StateExecuting,
  65.                                NULL);
  66.             CAMHAL_LOGDA("Timeout expired on executing state switch!");
  67.             goto EXIT;
  68.             }

  69.         mComponentState = OMX_StateExecuting;

  70.         }

  71.     mStateSwitchLock.unlock();

  72.     //Queue all the buffers on preview port
  73.     这里把所有的preview port的bufferheader fill到preview port上,然后等待数据经过处理,buffer被填充后通过fillBufferDone回调给应用层
  74.     for(int index=0;index< mPreviewData->mMaxQueueable;index++)
  75.         {
  76.         CAMHAL_LOGDB("Queuing buffer on Preview port - 0x%x", (uint32_t)mPreviewData->mBufferHeader[index]->pBuffer);
  77.         mPreviewData->mStatus[index] = OMXCameraPortParameters::FILL;
  78.         eError = OMX_FillThisBuffer(mCameraAdapterParameters.mHandleComp,
  79.                     (OMX_BUFFERHEADERTYPE*)mPreviewData->mBufferHeader[index]);
  80.         if(eError!=OMX_ErrorNone)
  81.             {
  82.             CAMHAL_LOGEB("OMX_FillThisBuffer-0x%x", eError);
  83.             }
  84.         mFramesWithDucati++;
  85. #ifdef CAMERAHAL_DEBUG
  86.         mBuffersWithDucati.add((int)mPreviewData->mBufferHeader[index]->pAppPrivate,1);
  87. #endif
  88.         GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
  89.         }

  90.     if ( mMeasurementEnabled )
  91.         {
  92.         这里把所有的measure port的bufferheader fill到measure port上,然后等待数据经过处理,buffer被填充后通过fillBufferDone回调给应用层
  93.         for(int index=0;index< mPreviewData->mNumBufs;index++)
  94.             {
  95.             CAMHAL_LOGDB("Queuing buffer on Measurement port - 0x%x", (uint32_t) measurementData->mBufferHeader[index]->pBuffer);
  96.             measurementData->mStatus[index] = OMXCameraPortParameters::FILL;
  97.             eError = OMX_FillThisBuffer(mCameraAdapterParameters.mHandleComp,
  98.                             (OMX_BUFFERHEADERTYPE*) measurementData->mBufferHeader[index]);
  99.             if(eError!=OMX_ErrorNone)
  100.                 {
  101.                 CAMHAL_LOGEB("OMX_FillThisBuffer-0x%x", eError);
  102.                 }
  103.             GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
  104.             }

  105.         }

  106.     setFocusCallback(true);

  107.     //reset frame rate estimates
  108.     mFPS = 0.0f;
  109.     mLastFPS = 0.0f;
  110.     // start frame count from 0. i.e first frame after
  111.     // startPreview will be the 0th reference frame
  112.     // this way we will wait for second frame until
  113.     // takePicture/autoFocus is allowed to run. we
  114.     // are seeing SetConfig/GetConfig fail after
  115.     // calling after the first frame and not failing
  116.     // after the second frame
  117.     mFrameCount = -1;
  118.     mLastFrameCount = 0;
  119.     mIter = 1;
  120.     mLastFPSTime = systemTime();
  121.     mTunnelDestroyed = false;

  122.     LOG_FUNCTION_NAME_EXIT;

  123.     return (ret | ErrorUtils::omxToAndroidError(eError));

  124.     EXIT:

  125.     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
  126.     performCleanupAfterError();
  127.     mStateSwitchLock.unlock();
  128.     LOG_FUNCTION_NAME_EXIT;

  129.     return (ret | ErrorUtils::omxToAndroidError(eError));

  130. }
经过上面的调用,之前初始化ok的buffer全部被分别fill到preview和measure port上,然后我上面也已经说过了,我们就等待组件处理完,并填充buffer,然后通知我,那么我们是在哪里接到组件的通知的呢??
不错,就是上面说的FillBufferDone方法,下面就多花点时间看看这个FillBufferDone方法
  1. /*========================================================*/
  2. /* @ fn SampleTest_FillBufferDone :: Application callback*/
  3. /*========================================================*/
  4. OMX_ERRORTYPE OMXCameraAdapterFillBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
  5.                                    OMX_IN OMX_PTR pAppData,
  6.                                    OMX_IN OMX_BUFFERHEADERTYPE* pBuffHeader)
  7. {
  8.     TIUTILS::Message msg;
  9.     OMX_ERRORTYPE eError = OMX_ErrorNone;

  10.     if (UNLIKELY(mDebugFps)) {
  11.         debugShowFPS();
  12.     }

  13.     OMXCameraAdapter *adapter = ( OMXCameraAdapter * ) pAppData;
  14.     if ( NULL != adapter )
  15.         {
  16.         msg.command = OMXCameraAdapter::OMXCallbackHandler::CAMERA_FILL_BUFFER_DONE;
  17.         msg.arg1 = ( void * ) hComponent;
  18.         msg.arg2 = ( void * ) pBuffHeader;
  19.         adapter->mOMXCallbackHandler->put(&msg);
  20.         }

  21.     return eError;
  22. }
分析一下上面的fillbufferdone方法,他没有直接对组件发给我们的消息做任何操作,他只是有点懒,他对发来的消息只是进行了打包然后就丢下去,让下面的小弟去做那些繁琐的处理过程,就是之前在初始化时启动的OMXCallbackHandler
线程去做这件事请的,那么就看看这个handle方法吧,看看他到底是怎么处理的
  1. bool OMXCameraAdapter::OMXCallbackHandler::Handler()
  2. {
  3.     TIUTILS::Message msg;
  4.     volatile int forever = 1;
  5.     status_t ret = NO_ERROR;

  6.     LOG_FUNCTION_NAME;

  7.     while(forever){
  8.         TIUTILS::MessageQueue::waitForMsg(&mCommandMsgQ, NULL, NULL, -1);
  9.         {
  10.         Mutex::Autolock lock(mLock);
  11.         mCommandMsgQ.get(&msg);
  12.         mIsProcessed = false;
  13.         }

  14.         switch ( msg.command ) {
  15.             case OMXCallbackHandler::CAMERA_FILL_BUFFER_DONE:
  16.             {
  17.                 ret = mCameraAdapter->OMXCameraAdapterFillBufferDone(( OMX_HANDLETYPE ) msg.arg1, ( OMX_BUFFERHEADERTYPE *) msg.arg2);
  18.                 break;
  19.             }
  20.             case OMXCallbackHandler::CAMERA_FOCUS_STATUS:
  21.             {
  22.                 mCameraAdapter->handleFocusCallback();
  23.                 break;
  24.             }
  25.             case CommandHandler::COMMAND_EXIT:
  26.             {
  27.                 CAMHAL_LOGDA("Exiting OMX callback handler");
  28.                 forever = 0;
  29.                 break;
  30.             }
  31.         }

  32.         {
  33.             android::AutoMutex locker(mLock);
  34.             CAMHAL_UNUSED(locker);

  35.             mIsProcessed = mCommandMsgQ.isEmpty();
  36.             if ( mIsProcessed )
  37.                 mCondition.signal();
  38.         }
  39.     }

  40.     // force the condition to wake
  41.     {
  42.         android::AutoMutex locker(mLock);
  43.         CAMHAL_UNUSED(locker);

  44.         mIsProcessed = true;
  45.         mCondition.signal();
  46.     }

  47.     LOG_FUNCTION_NAME_EXIT;
  48.     return false;
  49. }
不错,上面标注部分就是组件给我们返回来的消息,开始处理喽,这个处理过程第一次看很复杂,没办法啊,谁让他那么重要呢??硬着头皮看看吧
  1. /*========================================================*/
  2. /* @ fn SampleTest_FillBufferDone :: Application callback*/
  3. /*========================================================*/
  4. OMX_ERRORTYPE OMXCameraAdapter::OMXCameraAdapterFillBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
  5.                                    OMX_IN OMX_BUFFERHEADERTYPE* pBuffHeader)
  6. {

  7.     status_t stat = NO_ERROR;
  8.     status_t res1, res2;
  9.     OMXCameraPortParameters *pPortParam;
  10.     OMX_ERRORTYPE eError = OMX_ErrorNone;
  11.     CameraFrame::FrameType typeOfFrame = CameraFrame::ALL_FRAMES;
  12.     unsigned int refCount = 0;
  13.     BaseCameraAdapter::AdapterState state, nextState;
  14.     BaseCameraAdapter::getState(state);
  15.     BaseCameraAdapter::getNextState(nextState);
  16.     sp<CameraMetadataResult> metadataResult = NULL;
  17.     unsigned int mask = 0xFFFF;
  18.     CameraFrame cameraFrame;
  19.     OMX_OTHER_EXTRADATATYPE *extraData;
  20.     OMX_TI_ANCILLARYDATATYPE *ancillaryData = NULL;
  21.     bool snapshotFrame = false;

  22.     if ( NULL == pBuffHeader ) {
  23.         return OMX_ErrorBadParameter;
  24.     }

  25. #ifdef CAMERAHAL_OMX_PROFILING

  26.     storeProfilingData(pBuffHeader);

  27. #endif

  28.     res1 = res2 = NO_ERROR;

  29.     if ( !pBuffHeader || !pBuffHeader->pBuffer ) {
  30.         CAMHAL_LOGEA("NULL Buffer from OMX");
  31.         return OMX_ErrorNone;
  32.     }
  33.     这里这个pPortParm到底应该是哪个port的param呢??其实是不一定的
  34.     1.如果这个消息是preview port 的fillbufferdone,那么自然这里这个pPortParm指针指向的就是preview port 的param
  35.     2.如果这个消息是measurement port 的fillbufferdone,那么自然这里这个pPortParm指针指向的就是measurement port 的param
  36.     pPortParam = &(mCameraAdapterParameters.mCameraPortParams[pBuffHeader->nOutputPortIndex]);

  37.     // Find buffer and mark it as filled,首先比对,比对ok后标记为filldone
  38.     for (int i = 0; i < pPortParam->mNumBufs; i++) {
  39.         if (pPortParam->mBufferHeader[i] == pBuffHeader) {
  40.             pPortParam->mStatus[i] = OMXCameraPortParameters::DONE;
  41.         }
  42.     }
  43.     从这里开始就要进行分类处理了,对应不同output port type有不同的处理方法
  44.     1.OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW(对应preview过程
  45.     if (pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW)
  46.         {

  47.         if ( ( PREVIEW_ACTIVE & state ) != PREVIEW_ACTIVE )
  48.             {
  49.             return OMX_ErrorNone;
  50.             }

  51.         从这里开始我们暂时不做过多研究,只是对preview环境的一些初始化
  52.         if ( mWaitingForSnapshot ) {
  53.             extraData = getExtradata(pBuffHeader->pPlatformPrivate,
  54.                                      (OMX_EXTRADATATYPE) OMX_AncillaryData);

  55.             if ( NULL != extraData ) {
  56.                 ancillaryData = (OMX_TI_ANCILLARYDATATYPE*) extraData->data;
  57.                 if ((OMX_2D_Snap == ancillaryData->eCameraView)
  58.                     || (OMX_3D_Left_Snap == ancillaryData->eCameraView)
  59.                     || (OMX_3D_Right_Snap == ancillaryData->eCameraView)) {
  60.                     snapshotFrame = OMX_TRUE;
  61.                 } else {
  62.                     snapshotFrame = OMX_FALSE;
  63.                 }
  64.                 mPending3Asettings |= SetFocus;
  65.             }
  66.         }

  67.         ///Prepare the frames to be sent - initialize CameraFrame object and reference count
  68.         // TODO(XXX): ancillary data for snapshot frame is not being sent for video snapshot
  69.         // if we are waiting for a snapshot and in video mode...go ahead and send
  70.         // this frame as a snapshot
  71.         if( mWaitingForSnapshot && (mCapturedFrames > 0) &&
  72.             (snapshotFrame || (mCapMode == VIDEO_MODE)))
  73.             {
  74.             typeOfFrame = CameraFrame::SNAPSHOT_FRAME;
  75.             mask = (unsigned int)CameraFrame::SNAPSHOT_FRAME;

  76.             // video snapshot gets ancillary data and wb info from last snapshot frame
  77.             mCaptureAncillaryData = ancillaryData;
  78.             mWhiteBalanceData = NULL;
  79.             extraData = getExtradata(pBuffHeader->pPlatformPrivate,
  80.                                      (OMX_EXTRADATATYPE) OMX_WhiteBalance);
  81.             if ( NULL != extraData )
  82.                 {
  83.                 mWhiteBalanceData = (OMX_TI_WHITEBALANCERESULTTYPE*) extraData->data;
  84.                 }
  85.             }
  86.         else
  87.             {
  88.             typeOfFrame = CameraFrame::PREVIEW_FRAME_SYNC;
  89.             mask = (unsigned int)CameraFrame::PREVIEW_FRAME_SYNC;
  90.             }

  91.         if (mRecording)
  92.             {
  93.             mask |= (unsigned int)CameraFrame::VIDEO_FRAME_SYNC;
  94.             mFramesWithEncoder++;
  95.             }

  96.         //LOGV("FBD pBuffer = 0x%x", pBuffHeader->pBuffer);

  97.         if( mWaitingForSnapshot )
  98.           {
  99.             if (!mBracketingEnabled &&
  100.                  ((HIGH_SPEED == mCapMode) || (VIDEO_MODE == mCapMode)) )
  101.               {
  102.                 notifyShutterSubscribers();
  103.               }
  104.           }

  105.         这里这个sendCallBacks还是要好好研究一下的
  106.         stat = sendCallBacks(cameraFrame, pBuffHeader, mask, pPortParam);
  107.         mFramesWithDisplay++;

  108.         mFramesWithDucati--;
  109.         下面暂不做研究
  110. #ifdef CAMERAHAL_DEBUG
  111.         if(mBuffersWithDucati.indexOfKey((uint32_t)pBuffHeader->pBuffer)<0)
  112.             {
  113.             LOGE("Buffer was never with Ducati!! %p", pBuffHeader->pBuffer);
  114.             for(unsigned int i=0;i<mBuffersWithDucati.size();i++) LOGE("0x%x", mBuffersWithDucati.keyAt(i));
  115.             }
  116.         mBuffersWithDucati.removeItem((int)pBuffHeader->pBuffer);
  117. #endif

  118.         if(mDebugFcs)
  119.             CAMHAL_LOGEB("C[%d] D[%d] E[%d]", mFramesWithDucati, mFramesWithDisplay, mFramesWithEncoder);

  120.         recalculateFPS();

  121.         createPreviewMetadata(pBuffHeader, metadataResult, pPortParam->mWidth, pPortParam->mHeight);
  122.         if ( NULL != metadataResult.get() ) {
  123.             notifyMetadataSubscribers(metadataResult);
  124.             metadataResult.clear();
  125.         }

  126.         {
  127.             Mutex::Autolock lock(mFaceDetectionLock);
  128.             if ( mFDSwitchAlgoPriority ) {

  129.                  //Disable region priority and enable face priority for AF
  130.                  setAlgoPriority(REGION_PRIORITY, FOCUS_ALGO, false);
  131.                  setAlgoPriority(FACE_PRIORITY, FOCUS_ALGO , true);

  132.                  //Disable Region priority and enable Face priority
  133.                  setAlgoPriority(REGION_PRIORITY, EXPOSURE_ALGO, false);
  134.                  setAlgoPriority(FACE_PRIORITY, EXPOSURE_ALGO, true);
  135.                  mFDSwitchAlgoPriority = false;
  136.             }
  137.         }

  138.         sniffDccFileDataSave(pBuffHeader);

  139.         stat |= advanceZoom();

  140.         // On the fly update to 3A settings not working
  141.         // Do not update 3A here if we are in the middle of a capture
  142.         // or in the middle of transitioning to it
  143.         if( mPending3Asettings &&
  144.                 ( (nextState & CAPTURE_ACTIVE) == 0 ) &&
  145.                 ( (state & CAPTURE_ACTIVE) == 0 ) ) {
  146.             apply3Asettings(mParameters3A);
  147.         }

  148.         }
  149.     2.OMX_CAMERA_PORT_VIDEO_OUT_MEASUREMENT 
  150.     else if( pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_VIDEO_OUT_MEASUREMENT )
  151.         {
  152.         typeOfFrame = CameraFrame::FRAME_DATA_SYNC;
  153.         mask = (unsigned int)CameraFrame::FRAME_DATA_SYNC;

  154.         stat = sendCallBacks(cameraFrame, pBuffHeader, mask, pPortParam);
  155.        }
  156.     3.OMX_CAMERA_PORT_IMAGE_OUT_IMAGE 
  157.     else if( pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_IMAGE_OUT_IMAGE )
  158.     {
  159.         OMX_COLOR_FORMATTYPE pixFormat;
  160.         const char *valstr = NULL;

  161.         pixFormat = pPortParam->mColorFormat;

  162.         if ( OMX_COLOR_FormatUnused == pixFormat )
  163.             {
  164.             typeOfFrame = CameraFrame::IMAGE_FRAME;
  165.             mask = (unsigned int) CameraFrame::IMAGE_FRAME;
  166.         } else if ( pixFormat == OMX_COLOR_FormatCbYCrY &&
  167.                   ((mPictureFormatFromClient &&
  168.                           !strcmp(mPictureFormatFromClient,
  169.                                   CameraParameters::PIXEL_FORMAT_JPEG)) ||
  170.                    !mPictureFormatFromClient) ) {
  171.             // signals to callbacks that this needs to be coverted to jpeg
  172.             // before returning to framework
  173.             typeOfFrame = CameraFrame::IMAGE_FRAME;
  174.             mask = (unsigned int) CameraFrame::IMAGE_FRAME;
  175.             cameraFrame.mQuirks |= CameraFrame::ENCODE_RAW_YUV422I_TO_JPEG;
  176.             cameraFrame.mQuirks |= CameraFrame::FORMAT_YUV422I_UYVY;

  177.             // populate exif data and pass to subscribers via quirk
  178.             // subscriber is in charge of freeing exif data
  179.             ExifElementsTable* exif = new ExifElementsTable();
  180.             setupEXIF_libjpeg(exif, mCaptureAncillaryData, mWhiteBalanceData);
  181.             cameraFrame.mQuirks |= CameraFrame::HAS_EXIF_DATA;
  182.             cameraFrame.mCookie2 = (void*) exif;
  183.         } else {
  184.             typeOfFrame = CameraFrame::RAW_FRAME;
  185.             mask = (unsigned int) CameraFrame::RAW_FRAME;
  186.         }

  187.             pPortParam->mImageType = typeOfFrame;

  188.             if((mCapturedFrames>0) && !mCaptureSignalled)
  189.                 {
  190.                 mCaptureSignalled = true;
  191.                 mCaptureSem.Signal();
  192.                 }

  193.             if( ( CAPTURE_ACTIVE & state ) != CAPTURE_ACTIVE )
  194.                 {
  195.                 goto EXIT;
  196.                 }

  197.             {
  198.             Mutex::Autolock lock(mBracketingLock);
  199.             if ( mBracketingEnabled )
  200.                 {
  201.                 doBracketing(pBuffHeader, typeOfFrame);
  202.                 return eError;
  203.                 }
  204.             }

  205.             if (mZoomBracketingEnabled) {
  206.                 doZoom(mZoomBracketingValues[mCurrentZoomBracketing]);
  207.                 CAMHAL_LOGDB("Current Zoom Bracketing: %d", mZoomBracketingValues[mCurrentZoomBracketing]);
  208.                 mCurrentZoomBracketing++;
  209.                 if (mCurrentZoomBracketing == ARRAY_SIZE(mZoomBracketingValues)) {
  210.                     mZoomBracketingEnabled = false;
  211.                 }
  212.             }

  213.         if ( 1 > mCapturedFrames )
  214.             {
  215.             goto EXIT;
  216.             }

  217. #ifdef OMAP_ENHANCEMENT_CPCAM
  218.         setMetaData(cameraFrame.mMetaData, pBuffHeader->pPlatformPrivate);
  219. #endif

  220.         CAMHAL_LOGDB("Captured Frames: %d", mCapturedFrames);

  221.         mCapturedFrames--;

  222. #ifdef CAMERAHAL_USE_RAW_IMAGE_SAVING
  223.         if (mYuvCapture) {
  224.             struct timeval timeStampUsec;
  225.             gettimeofday(&timeStampUsec, NULL);

  226.             time_t saveTime;
  227.             time(&saveTime);
  228.             const struct tm * const timeStamp = gmtime(&saveTime);

  229.             char filename[256];
  230.             snprintf(filename,256, "%s/yuv_%d_%d_%d_%lu.yuv",
  231.                     kYuvImagesOutputDirPath,
  232.                     timeStamp->tm_hour,
  233.                     timeStamp->tm_min,
  234.                     timeStamp->tm_sec,
  235.                     timeStampUsec.tv_usec);

  236.             const status_t saveBufferStatus = saveBufferToFile(((CameraBuffer*)pBuffHeader->pAppPrivate)->mapped,
  237.                                                pBuffHeader->nFilledLen, filename);

  238.             if (saveBufferStatus != OK) {
  239.                 CAMHAL_LOGE("ERROR: %d, while saving yuv!", saveBufferStatus);
  240.             } else {
  241.                 CAMHAL_LOGD("yuv_%d_%d_%d_%lu.yuv successfully saved in %s",
  242.                         timeStamp->tm_hour,
  243.                         timeStamp->tm_min,
  244.                         timeStamp->tm_sec,
  245.                         timeStampUsec.tv_usec,
  246.                         kYuvImagesOutputDirPath);
  247.             }
  248.         }
  249. #endif

  250.         stat = sendCallBacks(cameraFrame, pBuffHeader, mask, pPortParam);
  251.         }
  252.         4.OMX_CAMERA_PORT_VIDEO_OUT_VIDEO
  253.         else if (pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_VIDEO_OUT_VIDEO) {
  254.             typeOfFrame = CameraFrame::RAW_FRAME;
  255.             pPortParam->mImageType = typeOfFrame;
  256.             {
  257.                 Mutex::Autolock lock(mLock);
  258.                 if( ( CAPTURE_ACTIVE & state ) != CAPTURE_ACTIVE ) {
  259.                     goto EXIT;
  260.                 }
  261.             }

  262.             CAMHAL_LOGD("RAW buffer done on video port, length = %d", pBuffHeader->nFilledLen);

  263.             mask = (unsigned int) CameraFrame::RAW_FRAME;

  264. #ifdef CAMERAHAL_USE_RAW_IMAGE_SAVING
  265.             if ( mRawCapture ) {
  266.                 struct timeval timeStampUsec;
  267.                 gettimeofday(&timeStampUsec, NULL);

  268.                 time_t saveTime;
  269.                 time(&saveTime);
  270.                 const struct tm * const timeStamp = gmtime(&saveTime);

  271.                 char filename[256];
  272.                 snprintf(filename,256, "%s/raw_%d_%d_%d_%lu.raw",
  273.                          kRawImagesOutputDirPath,
  274.                          timeStamp->tm_hour,
  275.                          timeStamp->tm_min,
  276.                          timeStamp->tm_sec,
  277.                          timeStampUsec.tv_usec);

  278.                 const status_t saveBufferStatus = saveBufferToFile( ((CameraBuffer*)pBuffHeader->pAppPrivate)->mapped,
  279.                                                    pBuffHeader->nFilledLen, filename);

  280.                 if (saveBufferStatus != OK) {
  281.                     CAMHAL_LOGE("ERROR: %d , while saving raw!", saveBufferStatus);
  282.                 } else {
  283.                     CAMHAL_LOGD("raw_%d_%d_%d_%lu.raw successfully saved in %s",
  284.                                 timeStamp->tm_hour,
  285.                                 timeStamp->tm_min,
  286.                                 timeStamp->tm_sec,
  287.                                 timeStampUsec.tv_usec,
  288.                                 kRawImagesOutputDirPath);
  289.                     stat = sendCallBacks(cameraFrame, pBuffHeader, mask, pPortParam);
  290.                 }
  291.             }
  292. #endif
  293.         } else {
  294.             CAMHAL_LOGEA("Frame received for non-(preview/capture/measure) port. This is yet to be supported");
  295.             goto EXIT;
  296.         }
     这里在上面的操作完成之后都会进行下面的方法returnFrame,这个returnFrame同样要好好分析一下
  1.     if ( NO_ERROR != stat )
  2.         {
  3.         CameraBuffer *camera_buffer;

  4.         camera_buffer = (CameraBuffer *)pBuffHeader->pAppPrivate;

  5.         CAMHAL_LOGDB("sendFrameToSubscribers error: %d", stat);
  6.         returnFrame(camera_buffer, typeOfFrame);
  7.         }

  8.     return eError;

  9.     EXIT:

  10.     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, stat, eError);

  11.     if ( NO_ERROR != stat )
  12.         {
  13.         if ( NULL != mErrorNotifier )
  14.             {
  15.             mErrorNotifier->errorNotify(CAMERA_ERROR_UNKNOWN);
  16.             }
  17.         }

  18.     return eError;
  19. }
首先看一下sendCallbacks方法的实现
  1. status_t OMXCameraAdapter::sendCallBacks(CameraFrame frame, OMX_IN OMX_BUFFERHEADERTYPE *pBuffHeader, unsigned int mask, OMXCameraPortParameters *port)
  2. {
  3.   status_t ret = NO_ERROR;

  4.   LOG_FUNCTION_NAME;

  5.   if ( NULL == port)
  6.     {
  7.       CAMHAL_LOGEA("Invalid portParam");
  8.       return -EINVAL;
  9.     }

  10.   if ( NULL == pBuffHeader )
  11.     {
  12.       CAMHAL_LOGEA("Invalid Buffer header");
  13.       return -EINVAL;
  14.     }

  15.   Mutex::Autolock lock(mSubscriberLock);
  16.   首先填充我们将要发送的camerabuffer
  17.   //frame.mFrameType = typeOfFrame;
  18.   frame.mFrameMask = mask;
  19.   frame.mBuffer = (CameraBuffer *)pBuffHeader->pAppPrivate;
  20.   frame.mLength = pBuffHeader->nFilledLen;
  21.   frame.mAlignment = port->mStride;
  22.   frame.mOffset = pBuffHeader->nOffset;
  23.   frame.mWidth = port->mWidth;
  24.   frame.mHeight = port->mHeight;
  25.   frame.mYuv[0] = NULL;
  26.   frame.mYuv[1] = NULL;

  27.   if ( onlyOnce && mRecording )
  28.     {
  29.       mTimeSourceDelta = (pBuffHeader->nTimeStamp * 1000) - systemTime(SYSTEM_TIME_MONOTONIC);
  30.       onlyOnce = false;
  31.     }

  32.   frame.mTimestamp = (pBuffHeader->nTimeStamp * 1000) - mTimeSourceDelta;

  33.   ret = setInitFrameRefCount(frame.mBuffer, mask);

  34.   if (ret != NO_ERROR) {
  35.      CAMHAL_LOGDB("Error in setInitFrameRefCount %d", ret);
  36.   } else {
  37.       ret = sendFrameToSubscribers(&frame);
  38.   }

  39.   CAMHAL_LOGVB("B 0x%x T %llu", frame.mBuffer, pBuffHeader->nTimeStamp);

  40.   LOG_FUNCTION_NAME_EXIT;

  41.   return ret;
  42. }
上面两个方法的实现也是很重点的部分,先看setInitFrameRefCount的实现
  1. int BaseCameraAdapter::setInitFrameRefCount(CameraBuffer * buf, unsigned int mask)
  2. {
  3.   int ret = NO_ERROR;
  4.   unsigned int lmask;

  5.   LOG_FUNCTION_NAME;

  6.   if (buf == NULL)
  7.     {
  8.       return -EINVAL;
  9.     }

  10.   for( lmask = 1; lmask < CameraFrame::ALL_FRAMES; lmask <<= 1){
  11.     if( lmask & mask ){
  12.       switch( lmask ){

  13.       case CameraFrame::IMAGE_FRAME:
  14.         {
  15.           把buffer添加到mImageSubscribers的最后的key上
  16.           setFrameRefCount(buf, CameraFrame::IMAGE_FRAME, (int) mImageSubscribers.size());
  17.         }
  18.         break;
  19.       case CameraFrame::RAW_FRAME:
  20.         {
  21.           setFrameRefCount(buf, CameraFrame::RAW_FRAME, mRawSubscribers.size());
  22.         }
  23.         break;
  24.       case CameraFrame::PREVIEW_FRAME_SYNC:
  25.         {
  26.           setFrameRefCount(buf, CameraFrame::PREVIEW_FRAME_SYNC, mFrameSubscribers.size());
  27.         }
  28.         break;
  29.       case CameraFrame::SNAPSHOT_FRAME:
  30.         {
  31.           setFrameRefCount(buf, CameraFrame::SNAPSHOT_FRAME, mSnapshotSubscribers.size());
  32.         }
  33.         break;
  34.       case CameraFrame::VIDEO_FRAME_SYNC:
  35.         {
  36.           setFrameRefCount(buf,CameraFrame::VIDEO_FRAME_SYNC, mVideoSubscribers.size());
  37.         }
  38.         break;
  39.       case CameraFrame::FRAME_DATA_SYNC:
  40.         {
  41.           setFrameRefCount(buf, CameraFrame::FRAME_DATA_SYNC, mFrameDataSubscribers.size());
  42.         }
  43.         break;
  44.       case CameraFrame::REPROCESS_INPUT_FRAME:
  45.         {
  46.           setFrameRefCount(buf,CameraFrame::REPROCESS_INPUT_FRAME, mVideoInSubscribers.size());
  47.         }
  48.         break;
  49.       default:
  50.         CAMHAL_LOGEB("FRAMETYPE NOT SUPPORTED 0x%x", lmask);
  51.         break;
  52.       }//SWITCH
  53.       mask &= ~lmask;
  54.     }//IF
  55.   }//FOR
  56.   LOG_FUNCTION_NAME_EXIT;
  57.   return ret;
  58. }
  1. void BaseCameraAdapter::setFrameRefCount(CameraBuffer * frameBuf, CameraFrame::FrameType frameType, int refCount)
  2. {

  3.     LOG_FUNCTION_NAME;

  4.     switch ( frameType )
  5.         {
  6.         case CameraFrame::IMAGE_FRAME:
  7.         case CameraFrame::RAW_FRAME:
  8.                 {
  9.                 Mutex::Autolock lock(mCaptureBufferLock);
  10.                 mCaptureBuffersAvailable.replaceValueFor(frameBuf, refCount);
  11.                 }
  12.             break;
  13.         case CameraFrame::SNAPSHOT_FRAME:
  14.                 {
  15.                 Mutex::Autolock lock(mSnapshotBufferLock);
  16.                 mSnapshotBuffersAvailable.replaceValueFor( ( unsigned int ) frameBuf, refCount);
  17.                 }
  18.             break;
  19.         case CameraFrame::PREVIEW_FRAME_SYNC:
  20.                 {
  21.                 Mutex::Autolock lock(mPreviewBufferLock);
  22.                 更新framebuf在mPreviewBuffersAviailable中的key
  23.                 mPreviewBuffersAvailable.replaceValueFor(frameBuf, refCount);
  24.                 }
  25.             break;
  26.         case CameraFrame::FRAME_DATA_SYNC:
  27.                 {
  28.                 Mutex::Autolock lock(mPreviewDataBufferLock);
  29.                 mPreviewDataBuffersAvailable.replaceValueFor(frameBuf, refCount);
  30.                 }
  31.             break;
  32.         case CameraFrame::VIDEO_FRAME_SYNC:
  33.                 {
  34.                 Mutex::Autolock lock(mVideoBufferLock);
  35.                 mVideoBuffersAvailable.replaceValueFor(frameBuf, refCount);
  36.                 }
  37.             break;
  38.         case CameraFrame::REPROCESS_INPUT_FRAME: {
  39.             Mutex::Autolock lock(mVideoInBufferLock);
  40.             mVideoInBuffersAvailable.replaceValueFor(frameBuf, refCount);
  41.         }
  42.             break;
  43.         default:
  44.             break;
  45.         };

  46.     LOG_FUNCTION_NAME_EXIT;

  47. }
然后我们再看看sendFrameToSubscribers这个很重要的方法,最终调用以下方法
  1. status_t BaseCameraAdapter::__sendFrameToSubscribers(CameraFrame* frame,
  2.                                                      KeyedVector<int, frame_callback> *subscribers,
  3.                                                      CameraFrame::FrameType frameType)
  4. {
  5.     size_t refCount = 0;
  6.     status_t ret = NO_ERROR;
  7.     frame_callback callback = NULL;

  8.     frame->mFrameType = frameType;

  9.     if ( (frameType == CameraFrame::PREVIEW_FRAME_SYNC) ||
  10.          (frameType == CameraFrame::VIDEO_FRAME_SYNC) ||
  11.          (frameType == CameraFrame::SNAPSHOT_FRAME) ){
  12.         if (mFrameQueue.size() > 0){
  13.           CameraFrame *lframe = (CameraFrame *)mFrameQueue.valueFor(frame->mBuffer);
  14.           frame->mYuv[0] = lframe->mYuv[0];
  15.           frame->mYuv[1] = frame->mYuv[0] + (frame->mLength + frame->mOffset)*2/3;
  16.         }
  17.         else{
  18.           CAMHAL_LOGDA("Empty Frame Queue");
  19.           return -EINVAL;
  20.         }
  21.       }

  22.     if (NULL != subscribers) {
  23.         refCount = getFrameRefCount(frame->mBuffer, frameType);

  24.         if (refCount == 0) {
  25.             CAMHAL_LOGDA("Invalid ref count of 0");
  26.             return -EINVAL;
  27.         }

  28.         if (refCount > subscribers->size()) {
  29.             CAMHAL_LOGEB("Invalid ref count for frame type: 0x%x", frameType);
  30.             return -EINVAL;
  31.         }

  32.         CAMHAL_LOGVB("Type of Frame: 0x%x address: 0x%x refCount start %d",
  33.                      frame->mFrameType,
  34.                      ( uint32_t ) frame->mBuffer,
  35.                      refCount);

  36.         for ( unsigned int i = 0 ; i < refCount; i++ ) {
  37.             frame->mCookie = ( void * ) subscribers->keyAt(i);
  38.             callback = (frame_callback) subscribers->valueAt(i);

  39.             if (!callback) {
  40.                 CAMHAL_LOGEB("callback not set for frame type: 0x%x", frameType);
  41.                 return -EINVAL;
  42.             }

  43.             callback(frame);
  44.         }
  45.     } else {
  46.         CAMHAL_LOGEA("Subscribers is null??");
  47.         return -EINVAL;
  48.     }

  49.     return ret;
  50. }
通过获得callback最终实现数据网上层回调
待续。。。。。
阅读(370) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~