Home | History | Annotate | Download | only in test
      1 /* Copyright (c) 2012-2016, The Linux Foundation. All rights reserved.
      2  *
      3  * Redistribution and use in source and binary forms, with or without
      4  * modification, are permitted provided that the following conditions are
      5  * met:
      6  *     * Redistributions of source code must retain the above copyright
      7  *       notice, this list of conditions and the following disclaimer.
      8  *     * Redistributions in binary form must reproduce the above
      9  *       copyright notice, this list of conditions and the following
     10  *       disclaimer in the documentation and/or other materials provided
     11  *       with the distribution.
     12  *     * Neither the name of The Linux Foundation nor the names of its
     13  *       contributors may be used to endorse or promote products derived
     14  *       from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
     17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
     23  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     24  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
     25  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
     26  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  *
     28  */
     29 
     30 #include <stdlib.h>
     31 #include <unistd.h>
     32 #include <fcntl.h>
     33 #include <time.h>
     34 #include <semaphore.h>
     35 #include <pthread.h>
     36 
     37 #include <sys/types.h>
     38 #include <sys/stat.h>
     39 #include <sys/wait.h>
     40 
     41 #include <ui/DisplayInfo.h>
     42 #include <gui/Surface.h>
     43 #include <gui/SurfaceComposerClient.h>
     44 #include <gui/ISurfaceComposer.h>
     45 
     46 #include <system/camera.h>
     47 
     48 #include <camera/Camera.h>
     49 #include <camera/ICamera.h>
     50 #include <camera/CameraParameters.h>
     51 #include <media/mediarecorder.h>
     52 
     53 #include <utils/RefBase.h>
     54 #include <utils/Mutex.h>
     55 #include <utils/Condition.h>
     56 #include <binder/IPCThreadState.h>
     57 #include <binder/ProcessState.h>
     58 #include <binder/IServiceManager.h>
     59 #include <cutils/properties.h>
     60 #include <cutils/memory.h>
     61 #include <SkImageDecoder.h>
     62 #include <SkImageEncoder.h>
     63 #include <MediaCodec.h>
     64 #include <OMX_IVCommon.h>
     65 #include <foundation/AMessage.h>
     66 #include <media/ICrypto.h>
     67 #include <MediaMuxer.h>
     68 #include <foundation/ABuffer.h>
     69 #include <MediaErrors.h>
     70 #include <gralloc_priv.h>
     71 #include <math.h>
     72 
     73 #include "qcamera_test.h"
     74 #include "cam_types.h"
     75 #include "mm_camera_dbg.h"
     76 
     77 #define VIDEO_BUF_ALLIGN(size, allign) \
     78   (((size) + (allign-1)) & (typeof(size))(~(allign-1)))
     79 
     80 namespace qcamera {
     81 
     82 using namespace android;
     83 
     84 int CameraContext::JpegIdx = 0;
     85 int CameraContext::mPiPIdx = 0;
     86 const char CameraContext::KEY_ZSL[] = "zsl";
     87 
     88 /*===========================================================================
     89  * FUNCTION   : previewCallback
     90  *
     91  * DESCRIPTION: preview callback preview mesages are enabled
     92  *
     93  * PARAMETERS :
     94  *   @mem : preview buffer
     95  *
     96  * RETURN     : None
     97  *==========================================================================*/
     98 void CameraContext::previewCallback(const sp<IMemory>& mem)
     99 {
    100     printf("PREVIEW Callback %p", mem->pointer());
    101     uint8_t *ptr = (uint8_t*) mem->pointer();
    102     if (NULL != ptr) {
    103         printf("PRV_CB: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x",
    104                 ptr[0],
    105                 ptr[1],
    106                 ptr[2],
    107                 ptr[3],
    108                 ptr[4],
    109                 ptr[5],
    110                 ptr[6],
    111                 ptr[7],
    112                 ptr[8],
    113                 ptr[9]);
    114     } else {
    115         ALOGE(" no preview for NULL CB\n");
    116     }
    117 }
    118 
    119 /*===========================================================================
    120  * FUNCTION   : useLock
    121  *
    122  * DESCRIPTION: Mutex lock for CameraContext
    123  *
    124  * PARAMETERS : none
    125  *
    126  * RETURN     : none
    127  *==========================================================================*/
    128 void CameraContext::useLock()
    129 {
    130     Mutex::Autolock l(mLock);
    131     while (mInUse) {
    132         mCond.wait(mLock);
    133     }
    134     mInUse = true;
    135 }
    136 
    137 /*===========================================================================
    138  * FUNCTION   : signalFinished
    139  *
    140  * DESCRIPTION: Mutex unlock CameraContext
    141  *
    142  * PARAMETERS : none
    143  *
    144  * RETURN     : none
    145  *==========================================================================*/
    146 void CameraContext::signalFinished()
    147 {
    148     Mutex::Autolock l(mLock);
    149     mInUse = false;
    150     mCond.signal();
    151 }
    152 
    153 /*===========================================================================
    154  * FUNCTION   : saveFile
    155  *
    156  * DESCRIPTION: helper function for saving buffers on filesystem
    157  *
    158  * PARAMETERS :
    159  *   @mem : buffer to save to filesystem
    160  *   @path: File path
    161  *
    162  * RETURN     : status_t type of status
    163  *              NO_ERROR  -- success
    164  *              none-zero failure code
    165  *==========================================================================*/
    166 status_t CameraContext::saveFile(const sp<IMemory>& mem, String8 path)
    167 {
    168     unsigned char *buff = NULL;
    169     ssize_t size;
    170     int fd = -1;
    171 
    172     if (mem == NULL) {
    173         return BAD_VALUE;
    174     }
    175 
    176     fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0655);
    177     if(fd < 0) {
    178         printf("Unable to open file %s %s\n", path.string(), strerror(fd));
    179         return -errno;
    180     }
    181 
    182     size = (ssize_t)mem->size();
    183     if (size <= 0) {
    184         printf("IMemory object is of zero size\n");
    185         close(fd);
    186         return BAD_VALUE;
    187     }
    188 
    189     buff = (unsigned char *)mem->pointer();
    190     if (!buff) {
    191         printf("Buffer pointer is invalid\n");
    192         close(fd);
    193         return BAD_VALUE;
    194     }
    195 
    196     if (size != write(fd, buff, (size_t)size)) {
    197         printf("Bad Write error (%d)%s\n", errno, strerror(errno));
    198         close(fd);
    199         return INVALID_OPERATION;
    200     }
    201 
    202     printf("%s: buffer=%p, size=%lld stored at %s\n",
    203             __FUNCTION__, buff, (long long int) size, path.string());
    204 
    205     if (fd >= 0)
    206         close(fd);
    207 
    208     return NO_ERROR;
    209 }
    210 
    211 /*===========================================================================
    212  * FUNCTION   : PiPCopyToOneFile
    213  *
    214  * DESCRIPTION: Copy the smaller picture to the bigger one
    215  *
    216  * PARAMETERS :
    217  *   @bitmap0 : Decoded image buffer 0
    218  *   @bitmap1 : Decoded image buffer 1
    219  *
    220  * RETURN     : decoded picture in picture in SkBitmap
    221  *==========================================================================*/
    222 SkBitmap * CameraContext::PiPCopyToOneFile(
    223     SkBitmap *bitmap0, SkBitmap *bitmap1)
    224 {
    225     size_t size0;
    226     size_t size1;
    227     SkBitmap *src;
    228     SkBitmap *dst;
    229     unsigned int dstOffset;
    230     unsigned int srcOffset;
    231 
    232     if (bitmap0 == NULL || bitmap1 == NULL) {
    233         ALOGE(" bitmap0 : %p, bitmap1 : %p\n",  bitmap0, bitmap1);
    234         return NULL;
    235     }
    236 
    237     size0 = bitmap0->getSize();
    238     if (size0 <= 0) {
    239         printf("Decoded image 0 is of zero size\n");
    240         return NULL;
    241     }
    242 
    243     size1 = bitmap1->getSize();
    244         if (size1 <= 0) {
    245             printf("Decoded image 1 is of zero size\n");
    246             return NULL;
    247         }
    248 
    249     if (size0 > size1) {
    250         dst = bitmap0;
    251         src = bitmap1;
    252     } else if (size1 > size0){
    253         dst = bitmap1;
    254         src = bitmap0;
    255     } else {
    256         printf("Picture size should be with different size!\n");
    257         return NULL;
    258     }
    259 
    260     for (unsigned int i = 0; i < (unsigned int)src->height(); i++) {
    261         dstOffset = i * (unsigned int)dst->width() * mfmtMultiplier;
    262         srcOffset = i * (unsigned int)src->width() * mfmtMultiplier;
    263         memcpy(((unsigned char *)dst->getPixels()) + dstOffset,
    264                 ((unsigned char *)src->getPixels()) + srcOffset,
    265                 (unsigned int)src->width() * mfmtMultiplier);
    266     }
    267 
    268     return dst;
    269 }
    270 
    271 /*===========================================================================
    272  * FUNCTION   : decodeJPEG
    273  *
    274  * DESCRIPTION: decode jpeg input buffer.
    275  *
    276  * PARAMETERS :
    277  *   @mem     : buffer to decode
    278  *   @skBM    : decoded buffer
    279  *
    280  * RETURN     : status_t type of status
    281  *              NO_ERROR  -- success
    282  *              none-zero failure code
    283 
    284  *==========================================================================*/
    285 status_t CameraContext::decodeJPEG(const sp<IMemory>& mem, SkBitmap *skBM)
    286 {
    287 #ifndef USE_SDK_20_OR_HIGHER
    288     SkBitmap::Config prefConfig = SkBitmap::kARGB_8888_Config;
    289     const void *buff = NULL;
    290     size_t size;
    291 
    292     buff = (const void *)mem->pointer();
    293     size= mem->size();
    294 
    295     switch(prefConfig) {
    296         case SkBitmap::kARGB_8888_Config:
    297         {
    298             mfmtMultiplier = 4;
    299         }
    300             break;
    301 
    302         case SkBitmap::kARGB_4444_Config:
    303         {
    304             mfmtMultiplier = 2;
    305         }
    306         break;
    307 
    308         case SkBitmap::kRGB_565_Config:
    309         {
    310             mfmtMultiplier = 2;
    311         }
    312         break;
    313 
    314         case SkBitmap::kIndex8_Config:
    315         {
    316             mfmtMultiplier = 4;
    317         }
    318         break;
    319 
    320         case SkBitmap::kA8_Config:
    321         {
    322             mfmtMultiplier = 4;
    323         }
    324         break;
    325 
    326         default:
    327         {
    328             mfmtMultiplier = 0;
    329             printf("Decode format is not correct!\n");
    330         }
    331         break;
    332     }
    333 
    334     if (SkImageDecoder::DecodeMemory(buff, size, skBM, prefConfig,
    335             SkImageDecoder::kDecodePixels_Mode) == false) {
    336         printf("%s():%d:: Failed during jpeg decode\n",__FUNCTION__,__LINE__);
    337         return BAD_VALUE;
    338     }
    339 #else
    340     SkColorType prefConfig = kRGBA_8888_SkColorType;
    341     const void *buff = NULL;
    342     size_t size;
    343 
    344     buff = (const void *)mem->pointer();
    345     size= mem->size();
    346 
    347     switch(prefConfig) {
    348         case kRGBA_8888_SkColorType:
    349         {
    350             mfmtMultiplier = 4;
    351         }
    352         break;
    353 
    354         case kBGRA_8888_SkColorType:
    355         {
    356             mfmtMultiplier = 4;
    357         }
    358         break;
    359 
    360         case kARGB_4444_SkColorType:
    361         {
    362             mfmtMultiplier = 2;
    363         }
    364         break;
    365 
    366         case kRGB_565_SkColorType:
    367         {
    368             mfmtMultiplier = 2;
    369         }
    370         break;
    371 
    372         case kIndex_8_SkColorType:
    373         {
    374             mfmtMultiplier = 4;
    375         }
    376         break;
    377 
    378         case kAlpha_8_SkColorType:
    379         {
    380             mfmtMultiplier = 4;
    381         }
    382         break;
    383 
    384         default:
    385         {
    386             mfmtMultiplier = 0;
    387             printf("Decode format is not correct!\n");
    388         }
    389         break;
    390     }
    391 
    392     if (SkImageDecoder::DecodeMemory(buff, size, skBM, prefConfig,
    393             SkImageDecoder::kDecodePixels_Mode) == false) {
    394         printf("%s():%d:: Failed during jpeg decode\n",__FUNCTION__,__LINE__);
    395         return BAD_VALUE;
    396     }
    397 
    398 #endif
    399     return NO_ERROR;
    400 }
    401 
    402 /*===========================================================================
    403  * FUNCTION   : encodeJPEG
    404  *
    405  * DESCRIPTION: encode the decoded input buffer.
    406  *
    407  * PARAMETERS :
    408  *   @stream  : SkWStream
    409  *   @bitmap  : SkBitmap decoded image to encode
    410  *   @path    : File path
    411  *
    412  * RETURN     : status_t type of status
    413  *              NO_ERROR  -- success
    414  *              none-zero failure code
    415 
    416  *==========================================================================*/
    417 status_t CameraContext::encodeJPEG(SkWStream * stream,
    418     const SkBitmap *bitmap, String8 path)
    419 {
    420     int qFactor = 100;
    421 
    422     skJpegEnc = SkImageEncoder::Create(SkImageEncoder::kJPEG_Type);
    423     if (!skJpegEnc) {
    424         ALOGE(" skJpegEnc is NULL\n");
    425         return BAD_VALUE;
    426     }
    427 
    428     if (skJpegEnc->encodeStream(stream, *bitmap, qFactor) == false) {
    429         return BAD_VALUE;
    430     }
    431 
    432     FILE *fh = fopen(path.string(), "r+");
    433     if ( !fh ) {
    434         printf("Could not open file %s\n", path.string());
    435         return BAD_VALUE;
    436     }
    437 
    438     fseek(fh, 0, SEEK_END);
    439     size_t len = (size_t)ftell(fh);
    440     rewind(fh);
    441 
    442     if( !len ) {
    443         printf("File %s is empty !\n", path.string());
    444         fclose(fh);
    445         return BAD_VALUE;
    446     }
    447 
    448     unsigned char *buff = (unsigned char*)malloc(len);
    449     if (!buff) {
    450         printf("Cannot allocate memory for buffer reading!\n");
    451         return BAD_VALUE;
    452     }
    453 
    454     size_t readSize = fread(buff, 1, len, fh);
    455     if (readSize != len) {
    456         printf("Reading error\n");
    457         return BAD_VALUE;
    458     }
    459 
    460     status_t ret = ReadSectionsFromBuffer(buff, len, READ_ALL);
    461     if (ret != NO_ERROR) {
    462         printf("Cannot read sections from buffer\n");
    463         DiscardData();
    464         DiscardSections();
    465         return BAD_VALUE;
    466     }
    467     free(buff);
    468     rewind(fh);
    469 
    470     unsigned char temp = 0xff;
    471     size_t writeSize = fwrite(&temp, sizeof(unsigned char), 1, fh);
    472     if (1 != writeSize) {
    473         printf("Writing error\n");
    474     }
    475     temp = 0xd8;
    476     fwrite(&temp, sizeof(unsigned char), 1, fh);
    477 
    478     for (size_t i = 0; i < mSectionsRead; i++) {
    479         switch((mSections[i].Type)) {
    480 
    481         case 0x123:
    482             fwrite(mSections[i].Data, sizeof(unsigned char),
    483                 mSections[i].Size, fh);
    484             break;
    485 
    486         case 0xe0:
    487             temp = 0xff;
    488             fwrite(&temp, sizeof(unsigned char), 1, fh);
    489             temp = 0xe1;
    490             fwrite(&temp, sizeof(unsigned char), 1, fh);
    491             fwrite(mJEXIFSection.Data, sizeof(unsigned char),
    492                 mJEXIFSection.Size, fh);
    493             break;
    494 
    495         default:
    496             temp = 0xff;
    497             fwrite(&temp, sizeof(unsigned char), 1, fh);
    498             fwrite(&mSections[i].Type, sizeof(unsigned char), 1, fh);
    499             fwrite(mSections[i].Data, sizeof(unsigned char),
    500                 mSections[i].Size, fh);
    501             break;
    502         }
    503     }
    504     fseek(fh, 0, SEEK_END);
    505     len = (size_t)ftell(fh);
    506     rewind(fh);
    507     printf("%s: buffer=%p, size=%zu stored at %s\n",
    508             __FUNCTION__, bitmap->getPixels(), len, path.string());
    509 
    510     free(mJEXIFSection.Data);
    511     DiscardData();
    512     DiscardSections();
    513     fclose(fh);
    514     ret = NO_ERROR;
    515 
    516     return ret;
    517 }
    518 
    519 /*===========================================================================
    520  * FUNCTION   : readSectionsFromBuffer
    521  *
    522  * DESCRIPTION: read all jpeg sections of input buffer.
    523  *
    524  * PARAMETERS :
    525  *   @mem : buffer to read from Metadata Sections
    526  *   @buffer_size: buffer size
    527  *   @ReadMode: Read mode - all, jpeg or exif
    528  *
    529  * RETURN     : status_t type of status
    530  *              NO_ERROR  -- success
    531  *              none-zero failure code
    532  *==========================================================================*/
    533 status_t CameraContext::ReadSectionsFromBuffer (unsigned char *buffer,
    534         size_t buffer_size, ReadMode_t ReadMode)
    535 {
    536     int a;
    537     size_t pos = 0;
    538     int HaveCom = 0;
    539     mSectionsAllocated = 10;
    540 
    541     mSections = (Sections_t *)malloc(sizeof(Sections_t) * mSectionsAllocated);
    542     if (!mSections) {
    543         printf(" not enough memory\n");
    544         return BAD_VALUE;
    545     }
    546 
    547     if (!buffer) {
    548         printf("Input buffer is null\n");
    549         return BAD_VALUE;
    550     }
    551 
    552     if (buffer_size < 1) {
    553         printf("Input size is 0\n");
    554         return BAD_VALUE;
    555     }
    556 
    557     a = (int) buffer[pos++];
    558 
    559     if (a != 0xff || buffer[pos++] != M_SOI){
    560         printf("No valid image\n");
    561         return BAD_VALUE;
    562     }
    563 
    564     for(;;){
    565         size_t itemlen;
    566         int marker = 0;
    567         size_t ll,lh;
    568         unsigned char * Data;
    569 
    570         CheckSectionsAllocated();
    571 
    572         // The call to CheckSectionsAllocated() may reallocate mSections
    573         // so need to check for NULL again.
    574         if (mSections == NULL) {
    575             printf(" not enough memory\n");
    576             return BAD_VALUE;
    577         }
    578 
    579         for (a = 0; a <= 16; a++){
    580             marker = buffer[pos++];
    581             if (marker != 0xff) break;
    582 
    583             if (a >= 16){
    584                 fprintf(stderr,"too many padding bytes\n");
    585                 return BAD_VALUE;
    586             }
    587         }
    588 
    589         mSections[mSectionsRead].Type = marker;
    590 
    591         // Read the length of the section.
    592         lh = buffer[pos++];
    593         ll = buffer[pos++];
    594 
    595         itemlen = (lh << 8) | ll;
    596 
    597         if (itemlen < 2) {
    598             ALOGE("invalid marker");
    599             return BAD_VALUE;
    600         }
    601 
    602         mSections[mSectionsRead].Size = itemlen;
    603 
    604         Data = (unsigned char *)malloc(itemlen);
    605         if (Data == NULL) {
    606             ALOGE("Could not allocate memory");
    607             return NO_MEMORY;
    608         }
    609         mSections[mSectionsRead].Data = Data;
    610 
    611         // Store first two pre-read bytes.
    612         Data[0] = (unsigned char)lh;
    613         Data[1] = (unsigned char)ll;
    614 
    615         if (pos+itemlen-2 > buffer_size) {
    616             ALOGE("Premature end of file?");
    617             return BAD_VALUE;
    618         }
    619 
    620         memcpy(Data+2, buffer+pos, itemlen-2); // Read the whole section.
    621         pos += itemlen-2;
    622 
    623         mSectionsRead += 1;
    624 
    625         switch(marker){
    626 
    627             case M_SOS:   // stop before hitting compressed data
    628                 // If reading entire image is requested, read the rest of the
    629                 // data.
    630                 if (ReadMode & READ_IMAGE){
    631                     size_t size;
    632                     // Determine how much file is left.
    633                     size = buffer_size - pos;
    634 
    635                     if (size < 1) {
    636                         ALOGE("could not read the rest of the image");
    637                         return BAD_VALUE;
    638                     }
    639                     Data = (unsigned char *)malloc(size);
    640                     if (Data == NULL) {
    641                         ALOGE("%d: could not allocate data for entire "
    642                                 "image size: %d", __LINE__, size);
    643                         return BAD_VALUE;
    644                     }
    645 
    646                     memcpy(Data, buffer+pos, size);
    647 
    648                     CheckSectionsAllocated();
    649 
    650                     // The call to CheckSectionsAllocated()
    651                     // may reallocate mSections
    652                     // so need to check for NULL again.
    653                     if (mSections == NULL) {
    654                         printf(" not enough memory\n");
    655                         return BAD_VALUE;
    656                     }
    657 
    658                     mSections[mSectionsRead].Data = Data;
    659                     mSections[mSectionsRead].Size = size;
    660                     mSections[mSectionsRead].Type = PSEUDO_IMAGE_MARKER;
    661                     mSectionsRead ++;
    662                     mHaveAll = 1;
    663                 }
    664                 return NO_ERROR;
    665 
    666             case M_EOI:   // in case it's a tables-only JPEG stream
    667                 ALOGE("No image in jpeg!\n");
    668                 return BAD_VALUE;
    669 
    670             case M_COM: // Comment section
    671                 if (HaveCom || ((ReadMode & READ_METADATA) == 0)){
    672                     // Discard this section.
    673                     free(mSections[--mSectionsRead].Data);
    674                 }
    675                 break;
    676 
    677             case M_JFIF:
    678                 // Regular jpegs always have this tag, exif images have the
    679                 // exif marker instead, althogh ACDsee will write images
    680                 // with both markers.
    681                 // this program will re-create this marker on absence of exif
    682                 // marker.
    683                 // hence no need to keep the copy from the file.
    684                 if (ReadMode & READ_METADATA){
    685                     if (memcmp(Data+2, "JFIF", 4) == 0) {
    686                         break;
    687                     }
    688                     free(mSections[--mSectionsRead].Data);
    689                 }
    690                 break;
    691 
    692             case M_EXIF:
    693                 // There can be different section using the same marker.
    694                 if (ReadMode & READ_METADATA){
    695                     if (memcmp(Data+2, "Exif", 4) == 0){
    696                         break;
    697                     }else if (memcmp(Data+2, "http:", 5) == 0){
    698                         // Change tag for internal purposes.
    699                         mSections[mSectionsRead-1].Type = M_XMP;
    700                         break;
    701                     }
    702                 }
    703                 // Oterwise, discard this section.
    704                 free(mSections[--mSectionsRead].Data);
    705                 break;
    706 
    707             case M_IPTC:
    708                 if (ReadMode & READ_METADATA){
    709                     // Note: We just store the IPTC section.
    710                     // Its relatively straightforward
    711                     // and we don't act on any part of it,
    712                     // so just display it at parse time.
    713                 }else{
    714                     free(mSections[--mSectionsRead].Data);
    715                 }
    716                 break;
    717 
    718             case M_SOF0:
    719             case M_SOF1:
    720             case M_SOF2:
    721             case M_SOF3:
    722             case M_SOF5:
    723             case M_SOF6:
    724             case M_SOF7:
    725             case M_SOF9:
    726             case M_SOF10:
    727             case M_SOF11:
    728             case M_SOF13:
    729             case M_SOF14:
    730             case M_SOF15:
    731                 break;
    732             default:
    733                 // Skip any other sections.
    734                 break;
    735         }
    736     }
    737     return NO_ERROR;
    738 }
    739 
    740 /*===========================================================================
    741  * FUNCTION   : CheckSectionsAllocated
    742  *
    743  * DESCRIPTION: Check allocated jpeg sections.
    744  *
    745  * PARAMETERS : none
    746  *
    747  * RETURN     : none
    748 
    749  *==========================================================================*/
    750 void CameraContext::CheckSectionsAllocated(void)
    751 {
    752     if (mSectionsRead > mSectionsAllocated){
    753         ALOGE("allocation screw up");
    754     }
    755     if (mSectionsRead >= mSectionsAllocated){
    756         mSectionsAllocated += mSectionsAllocated +1;
    757         mSections = (Sections_t *)realloc(mSections,
    758             sizeof(Sections_t) * mSectionsAllocated);
    759         if (mSections == NULL){
    760             ALOGE("could not allocate data for entire image");
    761         }
    762     }
    763 }
    764 
    765 /*===========================================================================
    766  * FUNCTION   : findSection
    767  *
    768  * DESCRIPTION: find the desired Section of the JPEG buffer.
    769  *
    770  * PARAMETERS :
    771  *  @SectionType: Section type
    772  *
    773  * RETURN     : return the found section
    774 
    775  *==========================================================================*/
    776 CameraContext::Sections_t *CameraContext::FindSection(int SectionType)
    777 {
    778     for (unsigned int a = 0; a < mSectionsRead; a++) {
    779         if (mSections[a].Type == SectionType){
    780             return &mSections[a];
    781         }
    782     }
    783     // Could not be found.
    784     return NULL;
    785 }
    786 
    787 
    788 /*===========================================================================
    789  * FUNCTION   : DiscardData
    790  *
    791  * DESCRIPTION: DiscardData
    792  *
    793  * PARAMETERS : none
    794  *
    795  * RETURN     : none
    796 
    797  *==========================================================================*/
    798 void CameraContext::DiscardData()
    799 {
    800     for (unsigned int a = 0; a < mSectionsRead; a++) {
    801         free(mSections[a].Data);
    802     }
    803 
    804     mSectionsRead = 0;
    805     mHaveAll = 0;
    806 }
    807 
    808 /*===========================================================================
    809  * FUNCTION   : DiscardSections
    810  *
    811  * DESCRIPTION: Discard allocated sections
    812  *
    813  * PARAMETERS : none
    814  *
    815  * RETURN     : none
    816 
    817  *==========================================================================*/
    818 void CameraContext::DiscardSections()
    819 {
    820     free(mSections);
    821     mSectionsAllocated = 0;
    822     mHaveAll = 0;
    823 }
    824 
    825 /*===========================================================================
    826  * FUNCTION   : notify
    827  *
    828  * DESCRIPTION: notify callback
    829  *
    830  * PARAMETERS :
    831  *   @msgType : type of callback
    832  *   @ext1: extended parameters
    833  *   @ext2: extended parameters
    834  *
    835  * RETURN     : None
    836  *==========================================================================*/
    837 void CameraContext::notify(int32_t msgType, int32_t ext1, int32_t ext2)
    838 {
    839     printf("Notify cb: %d %d %d\n", msgType, ext1, ext2);
    840 
    841     if (( msgType & CAMERA_MSG_PREVIEW_FRAME)
    842 #ifndef VANILLA_HAL
    843             && (ext1 == CAMERA_FRAME_DATA_FD)
    844 #endif
    845        )
    846     {
    847         int fd = dup(ext2);
    848         printf("notify Preview Frame fd: %d dup fd: %d\n", ext2, fd);
    849         close(fd);
    850     }
    851 
    852     if ( msgType & CAMERA_MSG_FOCUS ) {
    853         printf("AutoFocus %s \n",
    854                (ext1) ? "OK" : "FAIL");
    855     }
    856 
    857     if ( msgType & CAMERA_MSG_SHUTTER ) {
    858         printf("Shutter done \n");
    859     }
    860 
    861     if ( msgType & CAMERA_MSG_ERROR) {
    862         printf("Camera Test CAMERA_MSG_ERROR\n");
    863         stopPreview();
    864         closeCamera();
    865     }
    866 }
    867 
    868 /*===========================================================================
    869  * FUNCTION   : postData
    870  *
    871  * DESCRIPTION: handles data callbacks
    872  *
    873  * PARAMETERS :
    874  *   @msgType : type of callback
    875  *   @dataPtr: buffer data
    876  *   @metadata: additional metadata where available
    877  *
    878  * RETURN     : None
    879  *==========================================================================*/
    880 void CameraContext::postData(int32_t msgType,
    881                              const sp<IMemory>& dataPtr,
    882                              camera_frame_metadata_t *metadata)
    883 {
    884     mInterpr->PiPLock();
    885     Size currentPictureSize = mSupportedPictureSizes.itemAt(
    886         mCurrentPictureSizeIdx);
    887     unsigned char *buff = NULL;
    888     size_t size;
    889     status_t ret = 0;
    890 
    891     memset(&mJEXIFSection, 0, sizeof(mJEXIFSection)),
    892 
    893     printf("Data cb: %d\n", msgType);
    894 
    895     if ( msgType & CAMERA_MSG_PREVIEW_FRAME ) {
    896         previewCallback(dataPtr);
    897     }
    898 
    899     if ( msgType & CAMERA_MSG_RAW_IMAGE ) {
    900         printf("RAW done \n");
    901     }
    902 
    903     if (msgType & CAMERA_MSG_POSTVIEW_FRAME) {
    904         printf("Postview frame \n");
    905     }
    906 
    907     if (msgType & CAMERA_MSG_COMPRESSED_IMAGE ) {
    908         String8 jpegPath;
    909         jpegPath = jpegPath.format(QCAMERA_DUMP_FRM_LOCATION"img_%d.jpg",
    910                 JpegIdx);
    911         if (!mPiPCapture) {
    912             // Normal capture case
    913             printf("JPEG done\n");
    914             saveFile(dataPtr, jpegPath);
    915             JpegIdx++;
    916         } else {
    917             // PiP capture case
    918             SkFILEWStream *wStream;
    919             ret = decodeJPEG(dataPtr, &skBMtmp);
    920             if (NO_ERROR != ret) {
    921                 printf("Error in decoding JPEG!\n");
    922                 mInterpr->PiPUnlock();
    923                 return;
    924             }
    925 
    926             mWidthTmp = currentPictureSize.width;
    927             mHeightTmp = currentPictureSize.height;
    928             PiPPtrTmp = dataPtr;
    929             // If there are two jpeg buffers
    930             if (mPiPIdx == 1) {
    931                 printf("PiP done\n");
    932 
    933                 // Find the the capture with higher width and height and read
    934                 // its jpeg sections
    935                 if ((mInterpr->camera[0]->mWidthTmp * mInterpr->camera[0]->mHeightTmp) >
    936                         (mInterpr->camera[1]->mWidthTmp * mInterpr->camera[1]->mHeightTmp)) {
    937                     buff = (unsigned char *)PiPPtrTmp->pointer();
    938                     size= PiPPtrTmp->size();
    939                 } else if ((mInterpr->camera[0]->mWidthTmp * mInterpr->camera[0]->mHeightTmp) <
    940                         (mInterpr->camera[1]->mWidthTmp * mInterpr->camera[1]->mHeightTmp)) {
    941                     buff = (unsigned char *)PiPPtrTmp->pointer();
    942                     size= PiPPtrTmp->size();
    943                 } else {
    944                     printf("Cannot take PiP. Images are with the same width"
    945                             " and height size!!!\n");
    946                     mInterpr->PiPUnlock();
    947                     return;
    948                 }
    949 
    950                 if (buff != NULL && size != 0) {
    951                     ret = ReadSectionsFromBuffer(buff, size, READ_ALL);
    952                     if (ret != NO_ERROR) {
    953                         printf("Cannot read sections from buffer\n");
    954                         DiscardData();
    955                         DiscardSections();
    956                         mInterpr->PiPUnlock();
    957                         return;
    958                     }
    959 
    960                     mJEXIFTmp = FindSection(M_EXIF);
    961                     if (!mJEXIFTmp) {
    962                         ALOGE("skBMDec is null\n");
    963                         DiscardData();
    964                         DiscardSections();
    965                         return;
    966                     }
    967                     mJEXIFSection = *mJEXIFTmp;
    968                     mJEXIFSection.Data = (unsigned char*)malloc(mJEXIFTmp->Size);
    969                     if (!mJEXIFSection.Data) {
    970                         ALOGE(" Not enough memory\n");
    971                         DiscardData();
    972                         DiscardSections();
    973                         return;
    974                     }
    975                     memcpy(mJEXIFSection.Data,
    976                         mJEXIFTmp->Data, mJEXIFTmp->Size);
    977                     DiscardData();
    978                     DiscardSections();
    979 
    980                     wStream = new SkFILEWStream(jpegPath.string());
    981                     skBMDec = PiPCopyToOneFile(&mInterpr->camera[0]->skBMtmp,
    982                             &mInterpr->camera[1]->skBMtmp);
    983                     if (!skBMDec) {
    984                         ALOGE("skBMDec is null\n");
    985                         delete wStream;
    986                         return;
    987                     }
    988 
    989                     if (encodeJPEG(wStream, skBMDec, jpegPath) != false) {
    990                         printf("%s():%d:: Failed during jpeg encode\n",
    991                                 __FUNCTION__,__LINE__);
    992                         mInterpr->PiPUnlock();
    993                         return;
    994                     }
    995                     mPiPIdx = 0;
    996                     JpegIdx++;
    997                     delete wStream;
    998                 }
    999             } else {
   1000                 mPiPIdx++;
   1001             }
   1002             disablePiPCapture();
   1003         }
   1004     }
   1005 
   1006     if ((msgType & CAMERA_MSG_PREVIEW_METADATA) && (NULL != metadata)) {
   1007         printf("Face detected %d \n", metadata->number_of_faces);
   1008     }
   1009     mInterpr->PiPUnlock();
   1010 
   1011 }
   1012 
   1013 /*===========================================================================
   1014  * FUNCTION   : postDataTimestamp
   1015  *
   1016  * DESCRIPTION: handles recording callbacks
   1017  *
   1018  * PARAMETERS :
   1019  *   @timestamp : timestamp of buffer
   1020  *   @msgType : type of buffer
   1021  *   @dataPtr : buffer data
   1022  *
   1023  * RETURN     : None
   1024  *==========================================================================*/
   1025 void CameraContext::postDataTimestamp(nsecs_t timestamp,
   1026                                       int32_t msgType,
   1027                                       const sp<IMemory>& dataPtr)
   1028 {
   1029     printf("Recording cb: %d %lld %p\n",
   1030             msgType, (long long int)timestamp, dataPtr.get());
   1031 }
   1032 
   1033 /*===========================================================================
   1034  * FUNCTION   : dataCallbackTimestamp
   1035  *
   1036  * DESCRIPTION: handles recording callbacks. Used for ViV recording
   1037  *
   1038  * PARAMETERS :
   1039  *   @timestamp : timestamp of buffer
   1040  *   @msgType : type of buffer
   1041  *   @dataPtr : buffer data
   1042  *
   1043  * RETURN     : None
   1044  *==========================================================================*/
   1045 void CameraContext::dataCallbackTimestamp(nsecs_t timestamp,
   1046         int32_t msgType,
   1047         const sp<IMemory>& dataPtr)
   1048 {
   1049     mInterpr->ViVLock();
   1050     // Not needed check. Just avoiding warnings of not used variables.
   1051     if (timestamp > 0)
   1052         timestamp = 0;
   1053     // Not needed check. Just avoiding warnings of not used variables.
   1054     if (msgType > 0)
   1055         msgType = 0;
   1056     size_t i = 0;
   1057     void * srcBuff = NULL;
   1058     void * dstBuff = NULL;
   1059 
   1060     size_t srcYStride = 0, dstYStride = 0;
   1061     size_t srcUVStride = 0, dstUVStride = 0;
   1062     size_t srcYScanLines = 0, dstYScanLines = 0;
   1063     size_t srcUVScanLines = 0, dstUVScanLines = 0;
   1064     size_t srcOffset = 0, dstOffset = 0;
   1065     size_t srcBaseOffset = 0;
   1066     size_t dstBaseOffset = 0;
   1067     Size currentVideoSize = mSupportedVideoSizes.itemAt(mCurrentVideoSizeIdx);
   1068     status_t err = NO_ERROR;
   1069     ANativeWindowBuffer* anb = NULL;
   1070 
   1071     dstBuff = (void *) dataPtr->pointer();
   1072     if (NULL == dstBuff) {
   1073         printf("Cannot access destination buffer!!!\n");
   1074         mInterpr->ViVUnlock();
   1075         return;
   1076     }
   1077 
   1078     if (mCameraIndex == mInterpr->mViVVid.sourceCameraID) {
   1079         srcYStride = calcStride(currentVideoSize.width);
   1080         srcUVStride = calcStride(currentVideoSize.width);
   1081         srcYScanLines = calcYScanLines(currentVideoSize.height);
   1082         srcUVScanLines = calcUVScanLines(currentVideoSize.height);
   1083         mInterpr->mViVBuff.srcWidth = (size_t)currentVideoSize.width;
   1084         mInterpr->mViVBuff.srcHeight = (size_t)currentVideoSize.height;
   1085 
   1086 
   1087         mInterpr->mViVBuff.YStride = srcYStride;
   1088         mInterpr->mViVBuff.UVStride = srcUVStride;
   1089         mInterpr->mViVBuff.YScanLines = srcYScanLines;
   1090         mInterpr->mViVBuff.UVScanLines = srcUVScanLines;
   1091 
   1092         memcpy( mInterpr->mViVBuff.buff, dstBuff,
   1093             mInterpr->mViVBuff.buffSize);
   1094 
   1095         mInterpr->mViVVid.isBuffValid = true;
   1096     } else if (mCameraIndex == mInterpr->mViVVid.destinationCameraID) {
   1097         if(mInterpr->mViVVid.isBuffValid == true) {
   1098             dstYStride = calcStride(currentVideoSize.width);
   1099             dstUVStride = calcStride(currentVideoSize.width);
   1100             dstYScanLines = calcYScanLines(currentVideoSize.height);
   1101             dstUVScanLines = calcUVScanLines(currentVideoSize.height);
   1102 
   1103             srcYStride = mInterpr->mViVBuff.YStride;
   1104             srcUVStride = mInterpr->mViVBuff.UVStride;
   1105             srcYScanLines = mInterpr->mViVBuff.YScanLines;
   1106             srcUVScanLines = mInterpr->mViVBuff.UVScanLines;
   1107 
   1108 
   1109             for (i = 0; i < mInterpr->mViVBuff.srcHeight; i++) {
   1110                 srcOffset = i*srcYStride;
   1111                 dstOffset = i*dstYStride;
   1112                 memcpy((unsigned char *) dstBuff + dstOffset,
   1113                     (unsigned char *) mInterpr->mViVBuff.buff +
   1114                     srcOffset, mInterpr->mViVBuff.srcWidth);
   1115             }
   1116             srcBaseOffset = srcYStride * srcYScanLines;
   1117             dstBaseOffset = dstYStride * dstYScanLines;
   1118             for (i = 0; i < mInterpr->mViVBuff.srcHeight / 2; i++) {
   1119                 srcOffset = i*srcUVStride + srcBaseOffset;
   1120                 dstOffset = i*dstUVStride + dstBaseOffset;
   1121                 memcpy((unsigned char *) dstBuff + dstOffset,
   1122                     (unsigned char *) mInterpr->mViVBuff.buff +
   1123                     srcOffset, mInterpr->mViVBuff.srcWidth);
   1124             }
   1125 
   1126             err = native_window_dequeue_buffer_and_wait(
   1127                 mInterpr->mViVVid.ANW.get(),&anb);
   1128             if (err != NO_ERROR) {
   1129                 printf("Cannot dequeue anb for sensor %d!!!\n", mCameraIndex);
   1130                 mInterpr->ViVUnlock();
   1131                 return;
   1132             }
   1133             mInterpr->mViVVid.graphBuf = new GraphicBuffer(anb, false);
   1134             if(NULL == mInterpr->mViVVid.graphBuf.get()) {
   1135                 printf("Invalid Graphic buffer\n");
   1136                 mInterpr->ViVUnlock();
   1137                 return;
   1138             }
   1139             err = mInterpr->mViVVid.graphBuf->lock(
   1140                 GRALLOC_USAGE_SW_WRITE_OFTEN,
   1141                 (void**)(&mInterpr->mViVVid.mappedBuff));
   1142             if (err != NO_ERROR) {
   1143                 printf("Graphic buffer could not be locked %d!!!\n", err);
   1144                 mInterpr->ViVUnlock();
   1145                 return;
   1146             }
   1147 
   1148             srcYStride = dstYStride;
   1149             srcUVStride = dstUVStride;
   1150             srcYScanLines = dstYScanLines;
   1151             srcUVScanLines = dstUVScanLines;
   1152             srcBuff = dstBuff;
   1153 
   1154             for (i = 0; i < (size_t)currentVideoSize.height; i++) {
   1155                 srcOffset = i*srcYStride;
   1156                 dstOffset = i*dstYStride;
   1157                 memcpy((unsigned char *) mInterpr->mViVVid.mappedBuff +
   1158                     dstOffset, (unsigned char *) srcBuff +
   1159                     srcOffset, (size_t)currentVideoSize.width);
   1160             }
   1161 
   1162             srcBaseOffset = srcYStride * srcYScanLines;
   1163             dstBaseOffset = dstUVStride * (size_t)currentVideoSize.height;
   1164 
   1165             for (i = 0; i < (size_t)currentVideoSize.height / 2; i++) {
   1166                 srcOffset = i*srcUVStride + srcBaseOffset;
   1167                 dstOffset = i*dstUVStride + dstBaseOffset;
   1168                 memcpy((unsigned char *) mInterpr->mViVVid.mappedBuff +
   1169                     dstOffset, (unsigned char *) srcBuff +
   1170                     srcOffset, (size_t)currentVideoSize.width);
   1171             }
   1172 
   1173 
   1174             mInterpr->mViVVid.graphBuf->unlock();
   1175 
   1176             err = mInterpr->mViVVid.ANW->queueBuffer(
   1177                 mInterpr->mViVVid.ANW.get(), anb, -1);
   1178             if(err)
   1179                 printf("Failed to enqueue buffer to recorder!!!\n");
   1180         }
   1181     }
   1182     mCamera->releaseRecordingFrame(dataPtr);
   1183 
   1184     mInterpr->ViVUnlock();
   1185 }
   1186 
   1187 /*===========================================================================
   1188  * FUNCTION   : ViVEncoderThread
   1189  *
   1190  * DESCRIPTION: Creates a separate thread for ViV recording
   1191  *
   1192  * PARAMETERS : None
   1193  *
   1194  * RETURN     : None
   1195  *==========================================================================*/
   1196 status_t Interpreter::ViVEncoderThread()
   1197 {
   1198     int ret = NO_ERROR;
   1199     pthread_attr_t attr;
   1200     pthread_attr_init(&attr);
   1201 
   1202     ret = pthread_create(&mViVEncThread, &attr, ThreadWrapper, this);
   1203     ret = pthread_attr_destroy(&attr);
   1204 
   1205     return ret;
   1206 }
   1207 
   1208 /*===========================================================================
   1209  * FUNCTION   : ThreadWrapper
   1210  *
   1211  * DESCRIPTION: Helper function for for ViV recording thread
   1212  *
   1213  * PARAMETERS : Interpreter context
   1214  *
   1215  * RETURN     : None
   1216  *==========================================================================*/
   1217 void *Interpreter::ThreadWrapper(void *context) {
   1218     Interpreter *writer = static_cast<Interpreter *>(context);
   1219     writer->ViVEncode();
   1220     return NULL;
   1221 }
   1222 
   1223 /*===========================================================================
   1224  * FUNCTION   : ViVEncode
   1225  *
   1226  * DESCRIPTION: Thread for ViV encode. Buffers from video codec are sent to
   1227  *              muxer and saved in a file.
   1228  *
   1229  * PARAMETERS : Interpreter context
   1230  *
   1231  * RETURN     : None
   1232  *==========================================================================*/
   1233 void Interpreter::ViVEncode()
   1234 {
   1235     status_t err = NO_ERROR;
   1236     ssize_t trackIdx = -1;
   1237     uint32_t debugNumFrames = 0;
   1238 
   1239     size_t bufIndex, offset, size;
   1240     int64_t ptsUsec;
   1241     uint32_t flags;
   1242     bool DoRecording = true;
   1243 
   1244 
   1245     err = mTestContext->mViVVid.codec->getOutputBuffers(
   1246         &mTestContext->mViVVid.buffers);
   1247     if (err != NO_ERROR) {
   1248         printf("Unable to get output buffers (err=%d)\n", err);
   1249     }
   1250 
   1251     while (DoRecording) {
   1252         err = mTestContext->mViVVid.codec->dequeueOutputBuffer(
   1253             &bufIndex,
   1254             &offset,
   1255             &size,
   1256             &ptsUsec,
   1257             &flags, -1);
   1258 
   1259         switch (err) {
   1260 
   1261         case NO_ERROR:
   1262             // got a buffer
   1263             if ((flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) != 0) {
   1264                 // ignore this -- we passed the CSD into MediaMuxer when
   1265                 // we got the format change notification
   1266                 size = 0;
   1267             }
   1268             if (size != 0) {
   1269                 // If the virtual display isn't providing us with timestamps,
   1270                 // use the current time.
   1271                 if (ptsUsec == 0) {
   1272                     ptsUsec = systemTime(SYSTEM_TIME_MONOTONIC) / 1000;
   1273                 }
   1274 
   1275                 // The MediaMuxer docs are unclear, but it appears that we
   1276                 // need to pass either the full set of BufferInfo flags, or
   1277                 // (flags & BUFFER_FLAG_SYNCFRAME).
   1278                 err = mTestContext->mViVVid.muxer->writeSampleData(
   1279                     mTestContext->mViVVid.buffers[bufIndex],
   1280                     (size_t)trackIdx,
   1281                     ptsUsec,
   1282                     flags);
   1283                 if (err != NO_ERROR) {
   1284                     fprintf(stderr, "Failed writing data to muxer (err=%d)\n",
   1285                             err);
   1286                 }
   1287                 debugNumFrames++;
   1288             }
   1289             err = mTestContext->mViVVid.codec->releaseOutputBuffer(bufIndex);
   1290             if (err != NO_ERROR) {
   1291                 fprintf(stderr, "Unable to release output buffer (err=%d)\n",
   1292                         err);
   1293             }
   1294             if ((flags & MediaCodec::BUFFER_FLAG_EOS) != 0) {
   1295                 // Not expecting EOS from SurfaceFlinger.  Go with it.
   1296                 printf("Received end-of-stream\n");
   1297                 //DoRecording = false;
   1298             }
   1299             break;
   1300         case -EAGAIN:                       // INFO_TRY_AGAIN_LATER
   1301             ALOGV("Got -EAGAIN, looping");
   1302             break;
   1303         case INFO_FORMAT_CHANGED:           // INFO_OUTPUT_FORMAT_CHANGED
   1304         {
   1305             // format includes CSD, which we must provide to muxer
   1306             sp<AMessage> newFormat;
   1307             mTestContext->mViVVid.codec->getOutputFormat(&newFormat);
   1308             trackIdx = mTestContext->mViVVid.muxer->addTrack(newFormat);
   1309             err = mTestContext->mViVVid.muxer->start();
   1310             if (err != NO_ERROR) {
   1311                 printf("Unable to start muxer (err=%d)\n", err);
   1312             }
   1313         }
   1314         break;
   1315         case INFO_OUTPUT_BUFFERS_CHANGED:   // INFO_OUTPUT_BUFFERS_CHANGED
   1316             // not expected for an encoder; handle it anyway
   1317             ALOGV("Encoder buffers changed");
   1318             err = mTestContext->mViVVid.codec->getOutputBuffers(
   1319                 &mTestContext->mViVVid.buffers);
   1320             if (err != NO_ERROR) {
   1321                 printf("Unable to get new output buffers (err=%d)\n", err);
   1322             }
   1323         break;
   1324         case INVALID_OPERATION:
   1325             DoRecording = false;
   1326         break;
   1327         default:
   1328             printf("Got weird result %d from dequeueOutputBuffer\n", err);
   1329         break;
   1330         }
   1331     }
   1332 
   1333     return;
   1334 }
   1335 
   1336 /*===========================================================================
   1337  * FUNCTION   : calcBufferSize
   1338  *
   1339  * DESCRIPTION: Temp buffer size calculation. Temp buffer is used to store
   1340  *              the buffer from the camera with smaller resolution. It is
   1341  *              copied to the buffer from camera with higher resolution.
   1342  *
   1343  * PARAMETERS :
   1344  *   @width   : video size width
   1345  *   @height  : video size height
   1346  *
   1347  * RETURN     : size_t
   1348  *==========================================================================*/
   1349 size_t CameraContext::calcBufferSize(int width, int height)
   1350 {
   1351     size_t size = 0;
   1352     size_t UVAlignment;
   1353     size_t YPlane, UVPlane, YStride, UVStride, YScanlines, UVScanlines;
   1354     if (!width || !height) {
   1355         return size;
   1356     }
   1357     UVAlignment = 4096;
   1358     YStride = calcStride(width);
   1359     UVStride = calcStride(width);
   1360     YScanlines = calcYScanLines(height);
   1361     UVScanlines = calcUVScanLines(height);
   1362     YPlane = YStride * YScanlines;
   1363     UVPlane = UVStride * UVScanlines + UVAlignment;
   1364     size = YPlane + UVPlane;
   1365     size = VIDEO_BUF_ALLIGN(size, 4096);
   1366 
   1367     return size;
   1368 }
   1369 
   1370 /*===========================================================================
   1371  * FUNCTION   : calcStride
   1372  *
   1373  * DESCRIPTION: Temp buffer stride calculation.
   1374  *
   1375  * PARAMETERS :
   1376  *   @width   : video size width
   1377  *
   1378  * RETURN     : size_t
   1379  *==========================================================================*/
   1380 size_t CameraContext::calcStride(int width)
   1381 {
   1382     size_t alignment, stride = 0;
   1383     if (!width) {
   1384         return stride;
   1385     }
   1386     alignment = 128;
   1387     stride = VIDEO_BUF_ALLIGN((size_t)width, alignment);
   1388 
   1389     return stride;
   1390 }
   1391 
   1392 /*===========================================================================
   1393  * FUNCTION   : calcYScanLines
   1394  *
   1395  * DESCRIPTION: Temp buffer scanlines calculation for Y plane.
   1396  *
   1397  * PARAMETERS :
   1398  *   @width   : video size height
   1399  *
   1400  * RETURN     : size_t
   1401  *==========================================================================*/
   1402 size_t CameraContext::calcYScanLines(int height)
   1403 {
   1404     size_t alignment, scanlines = 0;
   1405         if (!height) {
   1406             return scanlines;
   1407         }
   1408     alignment = 32;
   1409     scanlines = VIDEO_BUF_ALLIGN((size_t)height, alignment);
   1410 
   1411     return scanlines;
   1412 }
   1413 
   1414 /*===========================================================================
   1415  * FUNCTION   : calcUVScanLines
   1416  *
   1417  * DESCRIPTION: Temp buffer scanlines calculation for UV plane.
   1418  *
   1419  * PARAMETERS :
   1420  *   @width   : video size height
   1421  *
   1422  * RETURN     : size_t
   1423  *==========================================================================*/
   1424 size_t CameraContext::calcUVScanLines(int height)
   1425 {
   1426     size_t alignment, scanlines = 0;
   1427     if (!height) {
   1428         return scanlines;
   1429     }
   1430     alignment = 16;
   1431     scanlines = VIDEO_BUF_ALLIGN((size_t)((height + 1) >> 1), alignment);
   1432 
   1433     return scanlines;
   1434 }
   1435 
   1436 /*===========================================================================
   1437  * FUNCTION   : printSupportedParams
   1438  *
   1439  * DESCRIPTION: dump common supported parameters
   1440  *
   1441  * PARAMETERS : None
   1442  *
   1443  * RETURN     : None
   1444  *==========================================================================*/
   1445 void CameraContext::printSupportedParams()
   1446 {
   1447     const char *camera_ids = mParams.get("camera-indexes");
   1448     const char *pic_sizes = mParams.get(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES);
   1449     const char *pic_formats = mParams.get(CameraParameters::KEY_SUPPORTED_PICTURE_FORMATS);
   1450     const char *preview_sizes = mParams.get(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES);
   1451     const char *video_sizes = mParams.get(CameraParameters::KEY_SUPPORTED_VIDEO_SIZES);
   1452     const char *preview_formats = mParams.get(CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS);
   1453     const char *frame_rates = mParams.get(CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES);
   1454     const char *thumb_sizes = mParams.get(CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES);
   1455     const char *wb_modes = mParams.get(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE);
   1456     const char *effects = mParams.get(CameraParameters::KEY_SUPPORTED_EFFECTS);
   1457     const char *scene_modes = mParams.get(CameraParameters::KEY_SUPPORTED_SCENE_MODES);
   1458     const char *focus_modes = mParams.get(CameraParameters::KEY_SUPPORTED_FOCUS_MODES);
   1459     const char *antibanding_modes = mParams.get(CameraParameters::KEY_SUPPORTED_ANTIBANDING);
   1460     const char *flash_modes = mParams.get(CameraParameters::KEY_SUPPORTED_FLASH_MODES);
   1461     int focus_areas = mParams.getInt(CameraParameters::KEY_MAX_NUM_FOCUS_AREAS);
   1462     const char *fps_ranges = mParams.get(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE);
   1463     const char *focus_distances = mParams.get(CameraParameters::KEY_FOCUS_DISTANCES);
   1464 
   1465     printf("\n\r\tSupported Cameras: %s",
   1466            (camera_ids != NULL)? camera_ids : "NULL");
   1467     printf("\n\r\tSupported Picture Sizes: %s",
   1468            (pic_sizes != NULL)? pic_sizes : "NULL");
   1469     printf("\n\r\tSupported Picture Formats: %s",
   1470            (pic_formats != NULL)? pic_formats : "NULL");
   1471     printf("\n\r\tSupported Preview Sizes: %s",
   1472            (preview_sizes != NULL)? preview_sizes : "NULL");
   1473     printf("\n\r\tSupported Video Sizes: %s",
   1474             (video_sizes != NULL)? video_sizes : "NULL");
   1475     printf("\n\r\tSupported Preview Formats: %s",
   1476            (preview_formats != NULL)? preview_formats : "NULL");
   1477     printf("\n\r\tSupported Preview Frame Rates: %s",
   1478            (frame_rates != NULL)? frame_rates : "NULL");
   1479     printf("\n\r\tSupported Thumbnail Sizes: %s",
   1480            (thumb_sizes != NULL)? thumb_sizes : "NULL");
   1481     printf("\n\r\tSupported Whitebalance Modes: %s",
   1482            (wb_modes != NULL)? wb_modes : "NULL");
   1483     printf("\n\r\tSupported Effects: %s",
   1484            (effects != NULL)? effects : "NULL");
   1485     printf("\n\r\tSupported Scene Modes: %s",
   1486            (scene_modes != NULL)? scene_modes : "NULL");
   1487     printf("\n\r\tSupported Focus Modes: %s",
   1488            (focus_modes != NULL)? focus_modes : "NULL");
   1489     printf("\n\r\tSupported Antibanding Options: %s",
   1490            (antibanding_modes != NULL)? antibanding_modes : "NULL");
   1491     printf("\n\r\tSupported Flash Modes: %s",
   1492            (flash_modes != NULL)? flash_modes : "NULL");
   1493     printf("\n\r\tSupported Focus Areas: %d", focus_areas);
   1494     printf("\n\r\tSupported FPS ranges : %s",
   1495            (fps_ranges != NULL)? fps_ranges : "NULL");
   1496     printf("\n\r\tFocus Distances: %s \n",
   1497            (focus_distances != NULL)? focus_distances : "NULL");
   1498 }
   1499 
   1500 /*===========================================================================
   1501  * FUNCTION   : createPreviewSurface
   1502  *
   1503  * DESCRIPTION: helper function for creating preview surfaces
   1504  *
   1505  * PARAMETERS :
   1506  *   @width : preview width
   1507  *   @height: preview height
   1508  *   @pixFormat : surface pixelformat
   1509  *
   1510  * RETURN     : status_t type of status
   1511  *              NO_ERROR  -- success
   1512  *              none-zero failure code
   1513  *==========================================================================*/
   1514 status_t CameraContext::createPreviewSurface(int width, int height, int32_t pixFormat)
   1515 {
   1516     int ret = NO_ERROR;
   1517     DisplayInfo dinfo;
   1518     sp<IBinder> display(SurfaceComposerClient::getBuiltInDisplay(
   1519                         ISurfaceComposer::eDisplayIdMain));
   1520     SurfaceComposerClient::getDisplayInfo(display, &dinfo);
   1521     uint32_t previewWidth, previewHeight;
   1522 
   1523     if ((0 >= width) || (0 >= height)) {
   1524         printf("Bad preview surface size %dx%d\n", width, height);
   1525         return BAD_VALUE;
   1526     }
   1527 
   1528     if ((int)dinfo.w < width) {
   1529         previewWidth = dinfo.w;
   1530     } else {
   1531         previewWidth = (unsigned int)width;
   1532     }
   1533 
   1534     if ((int)dinfo.h < height) {
   1535         previewHeight = dinfo.h;
   1536     } else {
   1537         previewHeight = (unsigned int)height;
   1538     }
   1539 
   1540     mClient = new SurfaceComposerClient();
   1541 
   1542     if ( NULL == mClient.get() ) {
   1543         printf("Unable to establish connection to Surface Composer \n");
   1544         return NO_INIT;
   1545     }
   1546 
   1547     mSurfaceControl = mClient->createSurface(String8("QCamera_Test"),
   1548                                              previewWidth,
   1549                                              previewHeight,
   1550                                              pixFormat,
   1551                                              0);
   1552     if ( NULL == mSurfaceControl.get() ) {
   1553         printf("Unable to create preview surface \n");
   1554         return NO_INIT;
   1555     }
   1556 
   1557     mPreviewSurface = mSurfaceControl->getSurface();
   1558     if ( NULL != mPreviewSurface.get() ) {
   1559         mClient->openGlobalTransaction();
   1560         ret |= mSurfaceControl->setLayer(0x7fffffff);
   1561         if ( mCameraIndex == 0 )
   1562             ret |= mSurfaceControl->setPosition(0, 0);
   1563         else
   1564             ret |= mSurfaceControl->setPosition((float)(dinfo.w - previewWidth),
   1565                     (float)(dinfo.h - previewHeight));
   1566 
   1567         ret |= mSurfaceControl->setSize(previewWidth, previewHeight);
   1568         ret |= mSurfaceControl->show();
   1569         mClient->closeGlobalTransaction();
   1570 
   1571         if ( NO_ERROR != ret ) {
   1572             printf("Preview surface configuration failed! \n");
   1573         }
   1574     } else {
   1575         ret = NO_INIT;
   1576     }
   1577 
   1578     return ret;
   1579 }
   1580 
   1581 /*===========================================================================
   1582  * FUNCTION   : destroyPreviewSurface
   1583  *
   1584  * DESCRIPTION: closes previously open preview surface
   1585  *
   1586  * PARAMETERS : None
   1587  *
   1588  * RETURN     : status_t type of status
   1589  *              NO_ERROR  -- success
   1590  *              none-zero failure code
   1591  *==========================================================================*/
   1592 status_t CameraContext::destroyPreviewSurface()
   1593 {
   1594     if ( NULL != mPreviewSurface.get() ) {
   1595         mPreviewSurface.clear();
   1596     }
   1597 
   1598     if ( NULL != mSurfaceControl.get() ) {
   1599         mSurfaceControl->clear();
   1600         mSurfaceControl.clear();
   1601     }
   1602 
   1603     if ( NULL != mClient.get() ) {
   1604         mClient->dispose();
   1605         mClient.clear();
   1606     }
   1607 
   1608     return NO_ERROR;
   1609 }
   1610 
   1611 /*===========================================================================
   1612  * FUNCTION   : CameraContext
   1613  *
   1614  * DESCRIPTION: camera context constructor
   1615  *
   1616  * PARAMETERS : None
   1617  *
   1618  * RETURN     : None
   1619  *==========================================================================*/
   1620 CameraContext::CameraContext(int cameraIndex) :
   1621     mCameraIndex(cameraIndex),
   1622     mResizePreview(true),
   1623     mHardwareActive(false),
   1624     mPreviewRunning(false),
   1625     mRecordRunning(false),
   1626     mVideoFd(-1),
   1627     mVideoIdx(0),
   1628     mRecordingHint(false),
   1629     mDoPrintMenu(true),
   1630     mPiPCapture(false),
   1631     mfmtMultiplier(1),
   1632     mSectionsRead(false),
   1633     mSectionsAllocated(0),
   1634     mSections(NULL),
   1635     mJEXIFTmp(NULL),
   1636     mHaveAll(false),
   1637     mCamera(NULL),
   1638     mClient(NULL),
   1639     mSurfaceControl(NULL),
   1640     mPreviewSurface(NULL),
   1641     mInUse(false)
   1642 {
   1643     mRecorder = new MediaRecorder(String16("camera"));
   1644 }
   1645 
   1646 /*===========================================================================
   1647  * FUNCTION     : setTestCtxInstance
   1648  *
   1649  * DESCRIPTION  : Sends TestContext instance to CameraContext
   1650  *
   1651  * PARAMETERS   :
   1652  *    @instance : TestContext instance
   1653  *
   1654  * RETURN     : None
   1655  *==========================================================================*/
   1656 void CameraContext::setTestCtxInstance(TestContext  *instance)
   1657 {
   1658     mInterpr = instance;
   1659 }
   1660 
   1661 /*===========================================================================
   1662  * FUNCTION     : setTestCtxInst
   1663  *
   1664  * DESCRIPTION  : Sends TestContext instance to Interpreter
   1665  *
   1666  * PARAMETERS   :
   1667  *    @instance : TestContext instance
   1668  *
   1669  * RETURN     : None
   1670  *==========================================================================*/
   1671 void Interpreter::setTestCtxInst(TestContext  *instance)
   1672 {
   1673     mTestContext = instance;
   1674 }
   1675 
   1676 /*===========================================================================
   1677  * FUNCTION   : ~CameraContext
   1678  *
   1679  * DESCRIPTION: camera context destructor
   1680  *
   1681  * PARAMETERS : None
   1682  *
   1683  * RETURN     : None
   1684  *==========================================================================*/
   1685 CameraContext::~CameraContext()
   1686 {
   1687     stopPreview();
   1688     closeCamera();
   1689 }
   1690 
   1691 /*===========================================================================
   1692  * FUNCTION   : openCamera
   1693  *
   1694  * DESCRIPTION: connects to and initializes camera
   1695  *
   1696  * PARAMETERS : None
   1697  *
   1698  * RETURN     : status_t type of status
   1699  *              NO_ERROR  -- success
   1700  *              none-zero failure code
   1701  *==========================================================================*/
   1702 status_t  CameraContext::openCamera()
   1703 {
   1704     useLock();
   1705     const char *ZSLStr = NULL;
   1706     size_t ZSLStrSize = 0;
   1707 
   1708     if ( NULL != mCamera.get() ) {
   1709         printf("Camera already open! \n");
   1710         signalFinished();
   1711         return NO_ERROR;
   1712     }
   1713 
   1714     printf("openCamera(camera_index=%d)\n", mCameraIndex);
   1715 
   1716 #ifndef USE_JB_MR1
   1717 
   1718     String16 packageName("CameraTest");
   1719 
   1720     mCamera = Camera::connect(mCameraIndex,
   1721                               packageName,
   1722                               Camera::USE_CALLING_UID);
   1723 
   1724 #else
   1725 
   1726     mCamera = Camera::connect(mCameraIndex);
   1727 
   1728 #endif
   1729 
   1730     if ( NULL == mCamera.get() ) {
   1731         printf("Unable to connect to CameraService\n");
   1732         signalFinished();
   1733         return NO_INIT;
   1734     }
   1735 
   1736     mParams = mCamera->getParameters();
   1737     mParams.getSupportedPreviewSizes(mSupportedPreviewSizes);
   1738     mParams.getSupportedPictureSizes(mSupportedPictureSizes);
   1739     mParams.getSupportedVideoSizes(mSupportedVideoSizes);
   1740 
   1741     mCurrentPictureSizeIdx = mSupportedPictureSizes.size() / 2;
   1742     mCurrentPreviewSizeIdx = mSupportedPreviewSizes.size() / 2;
   1743     mCurrentVideoSizeIdx   = mSupportedVideoSizes.size() / 2;
   1744 
   1745     mCamera->setListener(this);
   1746     mHardwareActive = true;
   1747 
   1748     mInterpr->setViVSize((Size) mSupportedVideoSizes.itemAt(
   1749         mCurrentVideoSizeIdx),
   1750         mCameraIndex);
   1751 
   1752     ZSLStr = mParams.get(CameraContext::KEY_ZSL);
   1753     if (NULL != ZSLStr) {
   1754         ZSLStrSize = strlen(ZSLStr);
   1755         if (!strncmp(ZSLStr, "on", ZSLStrSize)) {
   1756             mInterpr->mIsZSLOn = true;
   1757         } else if (!strncmp(ZSLStr, "off", ZSLStrSize)) {
   1758             mInterpr->mIsZSLOn = false;
   1759         } else {
   1760             printf("zsl value is not valid!\n");
   1761         }
   1762     } else {
   1763         printf("zsl is NULL\n");
   1764     }
   1765 
   1766     signalFinished();
   1767 
   1768     return NO_ERROR;
   1769 }
   1770 
   1771 /*===========================================================================
   1772  * FUNCTION   : onAsBinder
   1773  *
   1774  * DESCRIPTION: onAsBinder
   1775  *
   1776  * PARAMETERS : None
   1777  *
   1778  * RETURN     : Pointer to IBinder
   1779  *==========================================================================*/
   1780 IBinder* CameraContext::onAsBinder() {
   1781     return NULL;
   1782 }
   1783 
   1784 /*===========================================================================
   1785  * FUNCTION   : getNumberOfCameras
   1786  *
   1787  * DESCRIPTION: returns the number of supported camera by the system
   1788  *
   1789  * PARAMETERS : None
   1790  *
   1791  * RETURN     : supported camera count
   1792  *==========================================================================*/
   1793 int CameraContext::getNumberOfCameras()
   1794 {
   1795     int ret = -1;
   1796 
   1797     if ( NULL != mCamera.get() ) {
   1798         ret = mCamera->getNumberOfCameras();
   1799     }
   1800 
   1801     return ret;
   1802 }
   1803 
   1804 /*===========================================================================
   1805  * FUNCTION   : closeCamera
   1806  *
   1807  * DESCRIPTION: closes a previously the initialized camera reference
   1808  *
   1809  * PARAMETERS : None
   1810  *
   1811  * RETURN     : status_t type of status
   1812  *              NO_ERROR  -- success
   1813  *              none-zero failure code
   1814  *==========================================================================*/
   1815 status_t CameraContext::closeCamera()
   1816 {
   1817     useLock();
   1818     if ( NULL == mCamera.get() ) {
   1819         return NO_INIT;
   1820     }
   1821 
   1822     mCamera->disconnect();
   1823     mCamera.clear();
   1824 
   1825     mRecorder->init();
   1826     mRecorder->close();
   1827     mRecorder->release();
   1828     mRecorder.clear();
   1829 
   1830     mHardwareActive = false;
   1831     mPreviewRunning = false;
   1832     mRecordRunning = false;
   1833 
   1834     signalFinished();
   1835     return NO_ERROR;
   1836 }
   1837 
   1838 /*===========================================================================
   1839  * FUNCTION   : startPreview
   1840  *
   1841  * DESCRIPTION: starts camera preview
   1842  *
   1843  * PARAMETERS : None
   1844  *
   1845  * RETURN     : status_t type of status
   1846  *              NO_ERROR  -- success
   1847  *              none-zero failure code
   1848  *==========================================================================*/
   1849 status_t CameraContext::startPreview()
   1850 {
   1851     useLock();
   1852 
   1853     int ret = NO_ERROR;
   1854     int previewWidth, previewHeight;
   1855     Size calculatedPreviewSize;
   1856     Size currentPreviewSize = mSupportedPreviewSizes.itemAt(
   1857         mCurrentPreviewSizeIdx);
   1858     Size currentPictureSize = mSupportedPictureSizes.itemAt(
   1859         mCurrentPictureSizeIdx);
   1860     Size currentVideoSize   = mSupportedVideoSizes.itemAt(
   1861         mCurrentVideoSizeIdx);
   1862 
   1863 #ifndef USE_JB_MR1
   1864 
   1865     sp<IGraphicBufferProducer> gbp;
   1866 
   1867 #endif
   1868 
   1869     if (!mHardwareActive ) {
   1870         printf("Camera not active! \n");
   1871         return NO_INIT;
   1872     }
   1873 
   1874     if (mPreviewRunning) {
   1875         printf("Preview is already running! \n");
   1876         signalFinished();
   1877         return NO_ERROR;
   1878     }
   1879 
   1880     if (mResizePreview) {
   1881         mPreviewRunning = false;
   1882 
   1883         if ( mRecordingHint ) {
   1884             calculatedPreviewSize =
   1885                 getPreviewSizeFromVideoSizes(currentVideoSize);
   1886             previewWidth = calculatedPreviewSize.width;
   1887             previewHeight = calculatedPreviewSize.height;
   1888         } else {
   1889             previewWidth = currentPreviewSize.width;
   1890             previewHeight = currentPreviewSize.height;
   1891         }
   1892 
   1893         ret = createPreviewSurface(previewWidth,
   1894                                    previewHeight,
   1895                                    HAL_PIXEL_FORMAT_YCrCb_420_SP);
   1896         if (  NO_ERROR != ret ) {
   1897             printf("Error while creating preview surface\n");
   1898             return ret;
   1899         }
   1900 
   1901         // set rdi mode if system prop is set for front camera
   1902         if (mCameraIndex == 1) {
   1903             char value[32];
   1904             property_get("persist.camera.rdimode", value, "0");
   1905             int rdimode = atoi(value);
   1906             printf("rdi mode = %d\n", rdimode);
   1907             if (rdimode == 1) {
   1908                 mParams.set("rdi-mode", "enable");
   1909             } else {
   1910                 mParams.set("rdi-mode", "disable");
   1911             }
   1912         } else {
   1913             mParams.set("rdi-mode", "disable");
   1914         }
   1915 
   1916         //mParams.set("rdi-mode", "enable");
   1917         mParams.set("recording-hint", "true");
   1918         mParams.setPreviewSize(previewWidth, previewHeight);
   1919         mParams.setPictureSize(currentPictureSize.width,
   1920             currentPictureSize.height);
   1921         mParams.setVideoSize(
   1922             currentVideoSize.width, currentVideoSize.height);
   1923 
   1924         ret |= mCamera->setParameters(mParams.flatten());
   1925 
   1926 #ifndef USE_JB_MR1
   1927 
   1928         gbp = mPreviewSurface->getIGraphicBufferProducer();
   1929         ret |= mCamera->setPreviewTarget(gbp);
   1930 
   1931 #else
   1932 
   1933         ret |= mCamera->setPreviewDisplay(mPreviewSurface);
   1934 
   1935 #endif
   1936         mResizePreview = false;
   1937     }
   1938 
   1939     if ( !mPreviewRunning ) {
   1940         ret |= mCamera->startPreview();
   1941         if ( NO_ERROR != ret ) {
   1942             printf("Preview start failed! \n");
   1943             return ret;
   1944         }
   1945 
   1946         mPreviewRunning = true;
   1947     }
   1948 
   1949     signalFinished();
   1950 
   1951     return ret;
   1952 }
   1953 
   1954 /*===========================================================================
   1955  * FUNCTION   : getPreviewSizeFromVideoSizes
   1956  *
   1957  * DESCRIPTION: Get the preview size from video size. Find all resolutions with
   1958  *              the same aspect ratio and choose the same or the closest
   1959  *              from them.
   1960  *
   1961  * PARAMETERS :
   1962  *   @currentVideoSize: current video size
   1963 
   1964  *
   1965  * RETURN     : PreviewSize
   1966  *==========================================================================*/
   1967 Size CameraContext::getPreviewSizeFromVideoSizes(Size currentVideoSize)
   1968 {
   1969 
   1970     Size tmpPreviewSize;
   1971     Size PreviewSize;
   1972     Size PreviewSizes[mSupportedPreviewSizes.size()];
   1973     double tolerance = 0.00001;
   1974     double videoRatio;
   1975     double previewRatio;
   1976     size_t i = 0;
   1977     size_t j = 0;
   1978     int delta;
   1979 
   1980     // Find all the resolutions with the same aspect ratio and choose the
   1981     // same or the closest resolution from them. Choose the closest resolution
   1982     // in case same aspect ratio is not found
   1983     if (currentVideoSize.width * currentVideoSize.height > 0 &&
   1984             mSupportedPreviewSizes.size() > 0) {
   1985         videoRatio = (float)currentVideoSize.width /
   1986             (float)currentVideoSize.height;
   1987         for (i=0; i<mSupportedPreviewSizes.size(); i++) {
   1988             tmpPreviewSize = mSupportedPreviewSizes.itemAt(i);
   1989             previewRatio = (float)tmpPreviewSize.width /
   1990                 (float)tmpPreviewSize.height;
   1991             if (fabs(videoRatio - previewRatio) < tolerance) {
   1992                 PreviewSizes[j] = tmpPreviewSize;
   1993                 j++;
   1994             }
   1995         }
   1996 
   1997         if ( j > 0 ) {
   1998             delta = abs((currentVideoSize.width *currentVideoSize.height)-
   1999                 (PreviewSizes[0].width * PreviewSizes[0].height));
   2000             PreviewSize = PreviewSizes[0];
   2001             for (i=0; i<j; i++) {
   2002                 if(abs(currentVideoSize.width * currentVideoSize.height) -
   2003                     (PreviewSizes[i].width * PreviewSizes[i].height) <
   2004                     delta) {
   2005                     PreviewSize = PreviewSizes[i];
   2006                     delta = abs((currentVideoSize.width *
   2007                         currentVideoSize.height) -
   2008                         (PreviewSizes[i].width * PreviewSizes[i].height));
   2009                 }
   2010             }
   2011         } else {
   2012             // Choose the closest resolution in case same aspect ratio is
   2013             // not found
   2014             tmpPreviewSize = mSupportedPreviewSizes.itemAt(j);
   2015             PreviewSize = tmpPreviewSize;
   2016             delta = abs(
   2017                     (currentVideoSize.width * currentVideoSize.height)-
   2018                     (tmpPreviewSize.width * tmpPreviewSize.height));
   2019             for (i=0; i<mSupportedPreviewSizes.size(); i++) {
   2020                 tmpPreviewSize = mSupportedPreviewSizes.itemAt(i);
   2021                 if(abs(
   2022                         (currentVideoSize.width * currentVideoSize.height)-
   2023                         (tmpPreviewSize.width * tmpPreviewSize.height)) <
   2024                         delta) {
   2025                     PreviewSize = tmpPreviewSize;
   2026                     delta = abs(
   2027                             (currentVideoSize.width * currentVideoSize.height)-
   2028                             (tmpPreviewSize.width * tmpPreviewSize.height));
   2029                 }
   2030             }
   2031         }
   2032     } else {
   2033         memset(&PreviewSize, 0, sizeof(PreviewSize));
   2034     }
   2035     return PreviewSize;
   2036 }
   2037 
   2038 /*===========================================================================
   2039  * FUNCTION   : autoFocus
   2040  *
   2041  * DESCRIPTION: Triggers autofocus
   2042  *
   2043  * PARAMETERS : None
   2044  *
   2045  * RETURN     : status_t type of status
   2046  *              NO_ERROR  -- success
   2047  *              none-zero failure code
   2048  *==========================================================================*/
   2049 status_t CameraContext::autoFocus()
   2050 {
   2051     useLock();
   2052     status_t ret = NO_ERROR;
   2053 
   2054     if ( mPreviewRunning ) {
   2055         ret = mCamera->autoFocus();
   2056     }
   2057 
   2058     signalFinished();
   2059     return ret;
   2060 }
   2061 
   2062 /*===========================================================================
   2063  * FUNCTION   : enablePreviewCallbacks
   2064  *
   2065  * DESCRIPTION: Enables preview callback messages
   2066  *
   2067  * PARAMETERS : None
   2068  *
   2069  * RETURN     : status_t type of status
   2070  *              NO_ERROR  -- success
   2071  *              none-zero failure code
   2072  *==========================================================================*/
   2073 status_t CameraContext::enablePreviewCallbacks()
   2074 {
   2075     useLock();
   2076     if ( mHardwareActive ) {
   2077         mCamera->setPreviewCallbackFlags(
   2078             CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK);
   2079     }
   2080 
   2081     signalFinished();
   2082     return NO_ERROR;
   2083 }
   2084 
   2085 /*===========================================================================
   2086  * FUNCTION   : takePicture
   2087  *
   2088  * DESCRIPTION: triggers image capture
   2089  *
   2090  * PARAMETERS : None
   2091  *
   2092  * RETURN     : status_t type of status
   2093  *              NO_ERROR  -- success
   2094  *              none-zero failure code
   2095  *==========================================================================*/
   2096 status_t CameraContext::takePicture()
   2097 {
   2098     status_t ret = NO_ERROR;
   2099     useLock();
   2100     if ( mPreviewRunning ) {
   2101         ret = mCamera->takePicture(
   2102             CAMERA_MSG_COMPRESSED_IMAGE|
   2103             CAMERA_MSG_RAW_IMAGE);
   2104         if (!mRecordingHint && !mInterpr->mIsZSLOn) {
   2105             mPreviewRunning = false;
   2106         }
   2107     } else {
   2108         printf("Please resume/start the preview before taking a picture!\n");
   2109     }
   2110     signalFinished();
   2111     return ret;
   2112 }
   2113 
   2114 /*===========================================================================
   2115  * FUNCTION   : configureRecorder
   2116  *
   2117  * DESCRIPTION: Configure video recorder
   2118  *
   2119  * PARAMETERS : None
   2120  *
   2121  * RETURN     : status_t type of status
   2122  *              NO_ERROR  -- success
   2123  *              none-zero failure code
   2124  *==========================================================================*/
   2125 status_t CameraContext::configureRecorder()
   2126 {
   2127     useLock();
   2128     status_t ret = NO_ERROR;
   2129 
   2130     mResizePreview = true;
   2131     mParams.set("recording-hint", "true");
   2132     mRecordingHint = true;
   2133     mCamera->setParameters(mParams.flatten());
   2134 
   2135     Size videoSize = mSupportedVideoSizes.itemAt(mCurrentVideoSizeIdx);
   2136     ret = mRecorder->setParameters(
   2137         String8("video-param-encoding-bitrate=64000"));
   2138     if ( ret != NO_ERROR ) {
   2139         LOGE("Could not configure recorder (%d)", ret);
   2140         return ret;
   2141     }
   2142 
   2143     ret = mRecorder->setCamera(
   2144         mCamera->remote(), mCamera->getRecordingProxy());
   2145     if ( ret != NO_ERROR ) {
   2146         LOGE("Could not set camera (%d)", ret);
   2147         return ret;
   2148     }
   2149     ret = mRecorder->setVideoSource(VIDEO_SOURCE_CAMERA);
   2150     if ( ret != NO_ERROR ) {
   2151         LOGE("Could not set video soruce (%d)", ret);
   2152         return ret;
   2153     }
   2154     ret = mRecorder->setAudioSource(AUDIO_SOURCE_DEFAULT);
   2155     if ( ret != NO_ERROR ) {
   2156         LOGE("Could not set audio source (%d)", ret);
   2157         return ret;
   2158     }
   2159     ret = mRecorder->setOutputFormat(OUTPUT_FORMAT_DEFAULT);
   2160     if ( ret != NO_ERROR ) {
   2161         LOGE("Could not set output format (%d)", ret);
   2162         return ret;
   2163     }
   2164 
   2165     ret = mRecorder->setVideoEncoder(VIDEO_ENCODER_DEFAULT);
   2166     if ( ret != NO_ERROR ) {
   2167         LOGE("Could not set video encoder (%d)", ret);
   2168         return ret;
   2169     }
   2170 
   2171     char fileName[100];
   2172 
   2173     snprintf(fileName, sizeof(fileName) / sizeof(char),
   2174             "/sdcard/vid_cam%d_%dx%d_%d.mpeg", mCameraIndex,
   2175             videoSize.width, videoSize.height, mVideoIdx++);
   2176 
   2177     if ( mVideoFd < 0 ) {
   2178         mVideoFd = open(fileName, O_CREAT | O_RDWR );
   2179     }
   2180 
   2181     if ( mVideoFd < 0 ) {
   2182         LOGE("Could not open video file for writing %s!", fileName);
   2183         return UNKNOWN_ERROR;
   2184     }
   2185 
   2186     ret = mRecorder->setOutputFile(mVideoFd, 0, 0);
   2187     if ( ret != NO_ERROR ) {
   2188         LOGE("Could not set output file (%d)", ret);
   2189         return ret;
   2190     }
   2191 
   2192     ret = mRecorder->setVideoSize(videoSize.width, videoSize.height);
   2193     if ( ret  != NO_ERROR ) {
   2194         LOGE("Could not set video size %dx%d", videoSize.width,
   2195             videoSize.height);
   2196         return ret;
   2197     }
   2198 
   2199     ret = mRecorder->setVideoFrameRate(30);
   2200     if ( ret != NO_ERROR ) {
   2201         LOGE("Could not set video frame rate (%d)", ret);
   2202         return ret;
   2203     }
   2204 
   2205     ret = mRecorder->setAudioEncoder(AUDIO_ENCODER_DEFAULT);
   2206     if ( ret != NO_ERROR ) {
   2207         LOGE("Could not set audio encoder (%d)", ret);
   2208         return ret;
   2209     }
   2210 
   2211     signalFinished();
   2212     return ret;
   2213 }
   2214 
   2215 /*===========================================================================
   2216  * FUNCTION   : unconfigureViVRecording
   2217  *
   2218  * DESCRIPTION: Unconfigures video in video recording
   2219  *
   2220  * PARAMETERS : None
   2221  *
   2222  * RETURN     : status_t type of status
   2223  *              NO_ERROR  -- success
   2224  *              none-zero failure code
   2225  *==========================================================================*/
   2226 status_t CameraContext::unconfigureRecorder()
   2227 {
   2228     useLock();
   2229 
   2230     if ( !mRecordRunning ) {
   2231         mResizePreview = true;
   2232         mParams.set("recording-hint", "false");
   2233         mRecordingHint = false;
   2234         mCamera->setParameters(mParams.flatten());
   2235     }
   2236 
   2237     signalFinished();
   2238     return NO_ERROR;
   2239 }
   2240 
   2241 /*===========================================================================
   2242  * FUNCTION   : configureViVRecording
   2243  *
   2244  * DESCRIPTION: Configures video in video recording
   2245  *
   2246  * PARAMETERS : None
   2247  *
   2248  * RETURN     : status_t type of status
   2249  *              NO_ERROR  -- success
   2250  *              none-zero failure code
   2251  *==========================================================================*/
   2252 status_t CameraContext::configureViVRecording()
   2253 {
   2254     status_t ret = NO_ERROR;
   2255 
   2256     mResizePreview = true;
   2257     mParams.set("recording-hint", "true");
   2258     mRecordingHint = true;
   2259     mCamera->setParameters(mParams.flatten());
   2260     mCamera->setRecordingProxyListener(this);
   2261 
   2262     signalFinished();
   2263     return ret;
   2264 }
   2265 
   2266 /*===========================================================================
   2267  * FUNCTION   : startRecording
   2268  *
   2269  * DESCRIPTION: triggers start recording
   2270  *
   2271  * PARAMETERS : None
   2272  *
   2273  * RETURN     : status_t type of status
   2274  *              NO_ERROR  -- success
   2275  *              none-zero failure code
   2276  *==========================================================================*/
   2277 status_t CameraContext::startRecording()
   2278 {
   2279     useLock();
   2280     status_t ret = NO_ERROR;
   2281 
   2282 
   2283     if ( mPreviewRunning ) {
   2284 
   2285         mCamera->unlock();
   2286 
   2287         ret = mRecorder->prepare();
   2288         if ( ret != NO_ERROR ) {
   2289             LOGE("Could not prepare recorder");
   2290             return ret;
   2291         }
   2292 
   2293         ret = mRecorder->start();
   2294         if ( ret != NO_ERROR ) {
   2295             LOGE("Could not start recorder");
   2296             return ret;
   2297         }
   2298 
   2299         mRecordRunning = true;
   2300     }
   2301     signalFinished();
   2302     return ret;
   2303 }
   2304 
   2305 /*===========================================================================
   2306  * FUNCTION   : stopRecording
   2307  *
   2308  * DESCRIPTION: triggers start recording
   2309  *
   2310  * PARAMETERS : None
   2311  *
   2312  * RETURN     : status_t type of status
   2313  *              NO_ERROR  -- success
   2314  *              none-zero failure code
   2315  *==========================================================================*/
   2316 status_t CameraContext::stopRecording()
   2317 {
   2318     useLock();
   2319     status_t ret = NO_ERROR;
   2320 
   2321     if ( mRecordRunning ) {
   2322             mRecorder->stop();
   2323             close(mVideoFd);
   2324             mVideoFd = -1;
   2325 
   2326         mRecordRunning = false;
   2327     }
   2328 
   2329     signalFinished();
   2330 
   2331     return ret;
   2332 }
   2333 
   2334 /*===========================================================================
   2335  * FUNCTION   : startViVRecording
   2336  *
   2337  * DESCRIPTION: Starts video in video recording
   2338  *
   2339  * PARAMETERS : None
   2340  *
   2341  * RETURN     : status_t type of status
   2342  *              NO_ERROR  -- success
   2343  *              none-zero failure code
   2344  *==========================================================================*/
   2345 status_t CameraContext::startViVRecording()
   2346 {
   2347     useLock();
   2348     status_t ret;
   2349 
   2350     if (mInterpr->mViVVid.VideoSizes[0].width *
   2351             mInterpr->mViVVid.VideoSizes[0].height >=
   2352             mInterpr->mViVVid.VideoSizes[1].width *
   2353             mInterpr->mViVVid.VideoSizes[1].height) {
   2354         mInterpr->mViVBuff.buffSize = calcBufferSize(
   2355             mInterpr->mViVVid.VideoSizes[1].width,
   2356             mInterpr->mViVVid.VideoSizes[1].height);
   2357         if (mInterpr->mViVBuff.buff == NULL) {
   2358             mInterpr->mViVBuff.buff =
   2359                 (void *)malloc(mInterpr->mViVBuff.buffSize);
   2360         }
   2361         mInterpr->mViVVid.sourceCameraID = 1;
   2362         mInterpr->mViVVid.destinationCameraID = 0;
   2363 
   2364     } else {
   2365         mInterpr->mViVBuff.buffSize = calcBufferSize(
   2366             mInterpr->mViVVid.VideoSizes[0].width,
   2367             mInterpr->mViVVid.VideoSizes[0].height);
   2368         if (mInterpr->mViVBuff.buff == NULL) {
   2369             mInterpr->mViVBuff.buff =
   2370                 (void *)malloc(mInterpr->mViVBuff.buffSize);
   2371         }
   2372         mInterpr->mViVVid.sourceCameraID = 0;
   2373         mInterpr->mViVVid.destinationCameraID = 1;
   2374     }
   2375 
   2376     ret = mCamera->startRecording();
   2377 
   2378     signalFinished();
   2379     return ret;
   2380 }
   2381 
   2382 /*===========================================================================
   2383  * FUNCTION   : stopViVRecording
   2384  *
   2385  * DESCRIPTION: Stops video in video recording
   2386  *
   2387  * PARAMETERS : None
   2388  *
   2389  * RETURN     : status_t type of status
   2390  *              NO_ERROR  -- success
   2391  *              none-zero failure code
   2392  *==========================================================================*/
   2393 status_t CameraContext::stopViVRecording()
   2394 {
   2395     useLock();
   2396     status_t ret = NO_ERROR;
   2397 
   2398     mCamera->stopRecording();
   2399 
   2400     signalFinished();
   2401     return ret;
   2402 }
   2403 
   2404 /*===========================================================================
   2405  * FUNCTION   : stopPreview
   2406  *
   2407  * DESCRIPTION: stops camera preview
   2408  *
   2409  * PARAMETERS : None
   2410  *
   2411  * RETURN     : status_t type of status
   2412  *              NO_ERROR  -- success
   2413  *              none-zero failure code
   2414  *==========================================================================*/
   2415 status_t CameraContext::stopPreview()
   2416 {
   2417     useLock();
   2418     status_t ret = NO_ERROR;
   2419 
   2420     if ( mHardwareActive ) {
   2421         mCamera->stopPreview();
   2422         ret = destroyPreviewSurface();
   2423     }
   2424 
   2425     mPreviewRunning  = false;
   2426     mResizePreview = true;
   2427 
   2428     signalFinished();
   2429 
   2430     return ret;
   2431 }
   2432 
   2433 /*===========================================================================
   2434  * FUNCTION   : resumePreview
   2435  *
   2436  * DESCRIPTION: resumes camera preview after image capture
   2437  *
   2438  * PARAMETERS : None
   2439  *
   2440  * RETURN     : status_t type of status
   2441  *              NO_ERROR  -- success
   2442  *              none-zero failure code
   2443  *==========================================================================*/
   2444 status_t CameraContext::resumePreview()
   2445 {
   2446     useLock();
   2447     status_t ret = NO_ERROR;
   2448 
   2449     if ( mHardwareActive ) {
   2450         ret = mCamera->startPreview();
   2451         mPreviewRunning = true;
   2452     } else {
   2453         ret = NO_INIT;
   2454     }
   2455 
   2456     signalFinished();
   2457     return ret;
   2458 }
   2459 
   2460 /*===========================================================================
   2461  * FUNCTION   : nextPreviewSize
   2462  *
   2463  * DESCRIPTION: Iterates through all supported preview sizes.
   2464  *
   2465  * PARAMETERS : None
   2466  *
   2467  * RETURN     : status_t type of status
   2468  *              NO_ERROR  -- success
   2469  *              none-zero failure code
   2470  *==========================================================================*/
   2471 status_t CameraContext::nextPreviewSize()
   2472 {
   2473     useLock();
   2474     if ( mHardwareActive ) {
   2475         mCurrentPreviewSizeIdx += 1;
   2476         mCurrentPreviewSizeIdx %= mSupportedPreviewSizes.size();
   2477         Size previewSize = mSupportedPreviewSizes.itemAt(
   2478             mCurrentPreviewSizeIdx);
   2479         mParams.setPreviewSize(previewSize.width,
   2480                                previewSize.height);
   2481         mResizePreview = true;
   2482 
   2483         if ( mPreviewRunning ) {
   2484             mCamera->stopPreview();
   2485             mCamera->setParameters(mParams.flatten());
   2486             mCamera->startPreview();
   2487         } else {
   2488             mCamera->setParameters(mParams.flatten());
   2489         }
   2490     }
   2491 
   2492     signalFinished();
   2493     return NO_ERROR;
   2494 }
   2495 
   2496 
   2497 /*===========================================================================
   2498  * FUNCTION   : setPreviewSize
   2499  *
   2500  * DESCRIPTION: Sets exact preview size if supported
   2501  *
   2502  * PARAMETERS : format size in the form of WIDTHxHEIGHT
   2503  *
   2504  * RETURN     : status_t type of status
   2505  *              NO_ERROR  -- success
   2506  *              none-zero failure code
   2507  *==========================================================================*/
   2508 status_t CameraContext::setPreviewSize(const char *format)
   2509 {
   2510     useLock();
   2511     if ( mHardwareActive ) {
   2512         int newHeight;
   2513         int newWidth;
   2514         sscanf(format, "%dx%d", &newWidth, &newHeight);
   2515 
   2516         unsigned int i;
   2517         for (i = 0; i < mSupportedPreviewSizes.size(); ++i) {
   2518             Size previewSize = mSupportedPreviewSizes.itemAt(i);
   2519             if ( newWidth == previewSize.width &&
   2520                  newHeight == previewSize.height )
   2521             {
   2522                 break;
   2523             }
   2524 
   2525         }
   2526         if ( i == mSupportedPreviewSizes.size())
   2527         {
   2528             printf("Preview size %dx%d not supported !\n",
   2529                 newWidth, newHeight);
   2530             return INVALID_OPERATION;
   2531         }
   2532 
   2533         mParams.setPreviewSize(newWidth,
   2534                                newHeight);
   2535         mResizePreview = true;
   2536 
   2537         if ( mPreviewRunning ) {
   2538             mCamera->stopPreview();
   2539             mCamera->setParameters(mParams.flatten());
   2540             mCamera->startPreview();
   2541         } else {
   2542             mCamera->setParameters(mParams.flatten());
   2543         }
   2544     }
   2545 
   2546     signalFinished();
   2547     return NO_ERROR;
   2548 }
   2549 
   2550 /*===========================================================================
   2551  * FUNCTION   : getCurrentPreviewSize
   2552  *
   2553  * DESCRIPTION: queries the currently configured preview size
   2554  *
   2555  * PARAMETERS :
   2556  *  @previewSize : preview size currently configured
   2557  *
   2558  * RETURN     : status_t type of status
   2559  *              NO_ERROR  -- success
   2560  *              none-zero failure code
   2561  *==========================================================================*/
   2562 status_t CameraContext::getCurrentPreviewSize(Size &previewSize)
   2563 {
   2564     useLock();
   2565     if ( mHardwareActive ) {
   2566         previewSize = mSupportedPreviewSizes.itemAt(mCurrentPreviewSizeIdx);
   2567     }
   2568     signalFinished();
   2569     return NO_ERROR;
   2570 }
   2571 
   2572 /*===========================================================================
   2573  * FUNCTION   : nextPictureSize
   2574  *
   2575  * DESCRIPTION: Iterates through all supported picture sizes.
   2576  *
   2577  * PARAMETERS : None
   2578  *
   2579  * RETURN     : status_t type of status
   2580  *              NO_ERROR  -- success
   2581  *              none-zero failure code
   2582  *==========================================================================*/
   2583 status_t CameraContext::nextPictureSize()
   2584 {
   2585     useLock();
   2586     if ( mHardwareActive ) {
   2587         mCurrentPictureSizeIdx += 1;
   2588         mCurrentPictureSizeIdx %= mSupportedPictureSizes.size();
   2589         Size pictureSize = mSupportedPictureSizes.itemAt(
   2590             mCurrentPictureSizeIdx);
   2591         mParams.setPictureSize(pictureSize.width,
   2592             pictureSize.height);
   2593         mCamera->setParameters(mParams.flatten());
   2594     }
   2595     signalFinished();
   2596     return NO_ERROR;
   2597 }
   2598 
   2599 /*===========================================================================
   2600  * FUNCTION   : setPictureSize
   2601  *
   2602  * DESCRIPTION: Sets exact preview size if supported
   2603  *
   2604  * PARAMETERS : format size in the form of WIDTHxHEIGHT
   2605  *
   2606  * RETURN     : status_t type of status
   2607  *              NO_ERROR  -- success
   2608  *              none-zero failure code
   2609  *==========================================================================*/
   2610 status_t CameraContext::setPictureSize(const char *format)
   2611 {
   2612     useLock();
   2613     if ( mHardwareActive ) {
   2614         int newHeight;
   2615         int newWidth;
   2616         sscanf(format, "%dx%d", &newWidth, &newHeight);
   2617 
   2618         unsigned int i;
   2619         for (i = 0; i < mSupportedPictureSizes.size(); ++i) {
   2620             Size PictureSize = mSupportedPictureSizes.itemAt(i);
   2621             if ( newWidth == PictureSize.width &&
   2622                  newHeight == PictureSize.height )
   2623             {
   2624                 break;
   2625             }
   2626 
   2627         }
   2628         if ( i == mSupportedPictureSizes.size())
   2629         {
   2630             printf("Preview size %dx%d not supported !\n",
   2631                 newWidth, newHeight);
   2632             return INVALID_OPERATION;
   2633         }
   2634 
   2635         mParams.setPictureSize(newWidth,
   2636                                newHeight);
   2637         mCamera->setParameters(mParams.flatten());
   2638     }
   2639 
   2640     signalFinished();
   2641     return NO_ERROR;
   2642 }
   2643 
   2644 /*===========================================================================
   2645  * FUNCTION   : nextVideoSize
   2646  *
   2647  * DESCRIPTION: Select the next available video size
   2648  *
   2649  * PARAMETERS : none
   2650  *
   2651  * RETURN     : status_t type of status
   2652  *              NO_ERROR  -- success
   2653  *              none-zero failure code
   2654  *==========================================================================*/
   2655 status_t CameraContext::nextVideoSize()
   2656 {
   2657     useLock();
   2658     if ( mHardwareActive ) {
   2659         mCurrentVideoSizeIdx += 1;
   2660         mCurrentVideoSizeIdx %= mSupportedVideoSizes.size();
   2661         Size videoSize = mSupportedVideoSizes.itemAt(mCurrentVideoSizeIdx);
   2662         mParams.setVideoSize(videoSize.width,
   2663                              videoSize.height);
   2664         mCamera->setParameters(mParams.flatten());
   2665         mInterpr->setViVSize((Size) mSupportedVideoSizes.itemAt(
   2666             mCurrentVideoSizeIdx), mCameraIndex);
   2667     }
   2668     signalFinished();
   2669     return NO_ERROR;
   2670 }
   2671 
   2672 /*===========================================================================
   2673  * FUNCTION   : setVideoSize
   2674  *
   2675  * DESCRIPTION: Set video size
   2676  *
   2677  * PARAMETERS :
   2678  *   @format  : format
   2679  *
   2680  * RETURN     : status_t type of status
   2681  *              NO_ERROR  -- success
   2682  *              none-zero failure code
   2683  *==========================================================================*/
   2684 status_t CameraContext::setVideoSize(const char *format)
   2685 {
   2686     useLock();
   2687     if ( mHardwareActive ) {
   2688         int newHeight;
   2689         int newWidth;
   2690         sscanf(format, "%dx%d", &newWidth, &newHeight);
   2691 
   2692         unsigned int i;
   2693         for (i = 0; i < mSupportedVideoSizes.size(); ++i) {
   2694             Size PictureSize = mSupportedVideoSizes.itemAt(i);
   2695             if ( newWidth == PictureSize.width &&
   2696                  newHeight == PictureSize.height )
   2697             {
   2698                 break;
   2699             }
   2700 
   2701         }
   2702         if ( i == mSupportedVideoSizes.size())
   2703         {
   2704             printf("Preview size %dx%d not supported !\n",
   2705                 newWidth, newHeight);
   2706             return INVALID_OPERATION;
   2707         }
   2708 
   2709         mParams.setVideoSize(newWidth,
   2710                              newHeight);
   2711         mCamera->setParameters(mParams.flatten());
   2712     }
   2713 
   2714     signalFinished();
   2715     return NO_ERROR;
   2716 }
   2717 
   2718 /*===========================================================================
   2719  * FUNCTION    : getCurrentVideoSize
   2720  *
   2721  * DESCRIPTION : Get current video size
   2722  *
   2723  * PARAMETERS  :
   2724  *   @videoSize: video Size
   2725  *
   2726  * RETURN      : status_t type of status
   2727  *               NO_ERROR  -- success
   2728  *               none-zero failure code
   2729  *==========================================================================*/
   2730 status_t CameraContext::getCurrentVideoSize(Size &videoSize)
   2731 {
   2732     useLock();
   2733     if ( mHardwareActive ) {
   2734         videoSize = mSupportedVideoSizes.itemAt(mCurrentVideoSizeIdx);
   2735     }
   2736     signalFinished();
   2737     return NO_ERROR;
   2738 }
   2739 
   2740 /*===========================================================================
   2741  * FUNCTION   : getCurrentPictureSize
   2742  *
   2743  * DESCRIPTION: queries the currently configured picture size
   2744  *
   2745  * PARAMETERS :
   2746  *  @pictureSize : picture size currently configured
   2747  *
   2748  * RETURN     : status_t type of status
   2749  *              NO_ERROR  -- success
   2750  *              none-zero failure code
   2751  *==========================================================================*/
   2752 status_t CameraContext::getCurrentPictureSize(Size &pictureSize)
   2753 {
   2754     useLock();
   2755     if ( mHardwareActive ) {
   2756         pictureSize = mSupportedPictureSizes.itemAt(mCurrentPictureSizeIdx);
   2757     }
   2758     signalFinished();
   2759     return NO_ERROR;
   2760 }
   2761 
   2762 }; //namespace qcamera ends here
   2763 
   2764 using namespace qcamera;
   2765 
   2766 /*===========================================================================
   2767  * FUNCTION   : printMenu
   2768  *
   2769  * DESCRIPTION: prints the available camera options
   2770  *
   2771  * PARAMETERS :
   2772  *  @currentCamera : camera context currently being used
   2773  *
   2774  * RETURN     : None
   2775  *==========================================================================*/
   2776 void CameraContext::printMenu(sp<CameraContext> currentCamera)
   2777 {
   2778     if ( !mDoPrintMenu ) return;
   2779     Size currentPictureSize, currentPreviewSize, currentVideoSize;
   2780     const char *zsl_mode = mParams.get(CameraContext::KEY_ZSL);
   2781 
   2782     assert(currentCamera.get());
   2783 
   2784     currentCamera->getCurrentPictureSize(currentPictureSize);
   2785     currentCamera->getCurrentPreviewSize(currentPreviewSize);
   2786     currentCamera->getCurrentVideoSize(currentVideoSize);
   2787 
   2788     printf("\n\n=========== FUNCTIONAL TEST MENU ===================\n\n");
   2789 
   2790     printf(" \n\nSTART / STOP / GENERAL SERVICES \n");
   2791     printf(" -----------------------------\n");
   2792     printf("   %c. Switch camera - Current Index: %d\n",
   2793             Interpreter::SWITCH_CAMERA_CMD,
   2794             currentCamera->getCameraIndex());
   2795     printf("   %c. Resume Preview after capture \n",
   2796             Interpreter::RESUME_PREVIEW_CMD);
   2797     printf("   %c. Quit \n",
   2798             Interpreter::EXIT_CMD);
   2799     printf("   %c. Camera Capability Dump",
   2800             Interpreter::DUMP_CAPS_CMD);
   2801 
   2802     printf(" \n\n PREVIEW SUB MENU \n");
   2803     printf(" -----------------------------\n");
   2804     printf("   %c. Start Preview\n",
   2805             Interpreter::START_PREVIEW_CMD);
   2806     printf("   %c. Stop Preview\n",
   2807             Interpreter::STOP_PREVIEW_CMD);
   2808     printf("   %c. Preview size:  %dx%d\n",
   2809             Interpreter::CHANGE_PREVIEW_SIZE_CMD,
   2810             currentPreviewSize.width,
   2811             currentPreviewSize.height);
   2812     printf("   %c. Video size:  %dx%d\n",
   2813             Interpreter::CHANGE_VIDEO_SIZE_CMD,
   2814             currentVideoSize.width,
   2815             currentVideoSize.height);
   2816     printf("   %c. Start Recording\n",
   2817             Interpreter::START_RECORD_CMD);
   2818     printf("   %c. Stop Recording\n",
   2819             Interpreter::STOP_RECORD_CMD);
   2820     printf("   %c. Start ViV Recording\n",
   2821             Interpreter::START_VIV_RECORD_CMD);
   2822     printf("   %c. Stop ViV Recording\n",
   2823             Interpreter::STOP_VIV_RECORD_CMD);
   2824     printf("   %c. Enable preview frames\n",
   2825             Interpreter::ENABLE_PRV_CALLBACKS_CMD);
   2826     printf("   %c. Trigger autofocus \n",
   2827             Interpreter::AUTOFOCUS_CMD);
   2828 
   2829     printf(" \n\n IMAGE CAPTURE SUB MENU \n");
   2830     printf(" -----------------------------\n");
   2831     printf("   %c. Take picture/Full Press\n",
   2832             Interpreter::TAKEPICTURE_CMD);
   2833     printf("   %c. Take picture in picture\n",
   2834             Interpreter::TAKEPICTURE_IN_PICTURE_CMD);
   2835     printf("   %c. Picture size:  %dx%d\n",
   2836             Interpreter::CHANGE_PICTURE_SIZE_CMD,
   2837             currentPictureSize.width,
   2838             currentPictureSize.height);
   2839     printf("   %c. zsl:  %s\n", Interpreter::ZSL_CMD,
   2840         (zsl_mode != NULL) ? zsl_mode : "NULL");
   2841 
   2842     printf("\n   Choice: ");
   2843 }
   2844 
   2845 /*===========================================================================
   2846  * FUNCTION   : enablePrintPreview
   2847  *
   2848  * DESCRIPTION: Enables printing the preview
   2849  *
   2850  * PARAMETERS : None
   2851  *
   2852  * RETURN     : None
   2853  *==========================================================================*/
   2854 void CameraContext::enablePrintPreview()
   2855 {
   2856     mDoPrintMenu = true;
   2857 }
   2858 
   2859 /*===========================================================================
   2860  * FUNCTION   : disablePrintPreview
   2861  *
   2862  * DESCRIPTION: Disables printing the preview
   2863  *
   2864  * PARAMETERS : None
   2865  *
   2866  * RETURN     : None
   2867  *==========================================================================*/
   2868 void CameraContext::disablePrintPreview()
   2869 {
   2870     mDoPrintMenu = false;
   2871 }
   2872 
   2873 /*===========================================================================
   2874  * FUNCTION   : enablePiPCapture
   2875  *
   2876  * DESCRIPTION: Enables picture in picture capture
   2877  *
   2878  * PARAMETERS : None
   2879  *
   2880  * RETURN     : None
   2881  *==========================================================================*/
   2882 void CameraContext::enablePiPCapture()
   2883 {
   2884     mPiPCapture = true;
   2885 }
   2886 
   2887 /*===========================================================================
   2888  * FUNCTION   : disablePiPCapture
   2889  *
   2890  * DESCRIPTION: Disables picture in picture capture
   2891  *
   2892  * PARAMETERS : None
   2893  *
   2894  * RETURN     : None
   2895  *==========================================================================*/
   2896 void CameraContext::disablePiPCapture()
   2897 {
   2898     mPiPCapture = false;
   2899 }
   2900 
   2901 /*===========================================================================
   2902  * FUNCTION   : getZSL
   2903  *
   2904  * DESCRIPTION: get ZSL value of current camera
   2905  *
   2906  * PARAMETERS : None
   2907  *
   2908  * RETURN     : current zsl value
   2909  *==========================================================================*/
   2910 const char *CameraContext::getZSL()
   2911 {
   2912     return mParams.get(CameraContext::KEY_ZSL);
   2913 }
   2914 
   2915 /*===========================================================================
   2916  * FUNCTION   : setZSL
   2917  *
   2918  * DESCRIPTION: set ZSL value of current camera
   2919  *
   2920  * PARAMETERS : zsl value to be set
   2921  *
   2922  * RETURN     : None
   2923  *==========================================================================*/
   2924 void CameraContext::setZSL(const char *value)
   2925 {
   2926     mParams.set(CameraContext::KEY_ZSL, value);
   2927     mCamera->setParameters(mParams.flatten());
   2928 }
   2929 
   2930 /*===========================================================================
   2931  * FUNCTION   : configureViVCodec
   2932  *
   2933  * DESCRIPTION: Configures video in video codec
   2934  *
   2935  * PARAMETERS : none
   2936  *
   2937  * RETURN     : status_t type of status
   2938  *              NO_ERROR  -- success
   2939  *              none-zero failure code
   2940  *==========================================================================*/
   2941 status_t Interpreter::configureViVCodec()
   2942 {
   2943     status_t ret = NO_ERROR;
   2944     char fileName[100];
   2945     sp<AMessage> format = new AMessage;
   2946     sp<ALooper> looper = new ALooper;
   2947 
   2948     if (mTestContext->mViVVid.VideoSizes[0].width *
   2949             mTestContext->mViVVid.VideoSizes[0].height >=
   2950             mTestContext->mViVVid.VideoSizes[1].width *
   2951             mTestContext->mViVVid.VideoSizes[1].height) {
   2952         snprintf(fileName, sizeof(fileName) / sizeof(char), "/sdcard/ViV_vid_%dx%d_%d.mp4",
   2953             mTestContext->mViVVid.VideoSizes[0].width,
   2954             mTestContext->mViVVid.VideoSizes[0].height,
   2955             mTestContext->mViVVid.ViVIdx++);
   2956         format->setInt32("width", mTestContext->mViVVid.VideoSizes[0].width);
   2957         format->setInt32("height", mTestContext->mViVVid.VideoSizes[0].height);
   2958     } else {
   2959         snprintf(fileName, sizeof(fileName) / sizeof(char), "/sdcard/ViV_vid_%dx%d_%d.mp4",
   2960             mTestContext->mViVVid.VideoSizes[1].width,
   2961             mTestContext->mViVVid.VideoSizes[1].height,
   2962             mTestContext->mViVVid.ViVIdx++);
   2963         format->setInt32("width", mTestContext->mViVVid.VideoSizes[1].width);
   2964         format->setInt32("height", mTestContext->mViVVid.VideoSizes[1].height);
   2965     }
   2966     int fd = open(fileName, O_CREAT | O_RDWR );
   2967     if (fd < 0) {
   2968         LOGE("Error opening file");
   2969         return UNKNOWN_ERROR;
   2970     }
   2971     mTestContext->mViVVid.muxer = new MediaMuxer(
   2972         fd, MediaMuxer::OUTPUT_FORMAT_MPEG_4);
   2973 
   2974     format->setString("mime", "video/avc");
   2975     format->setInt32("color-format", OMX_COLOR_FormatAndroidOpaque);
   2976 
   2977     format->setInt32("bitrate", 1000000);
   2978     format->setFloat("frame-rate", 30);
   2979     format->setInt32("i-frame-interval", 10);
   2980 
   2981     looper->setName("ViV_recording_looper");
   2982     looper->start();
   2983     ALOGV("Creating codec");
   2984     mTestContext->mViVVid.codec = MediaCodec::CreateByType(
   2985         looper, "video/avc", true);
   2986     if (mTestContext->mViVVid.codec == NULL) {
   2987         fprintf(stderr, "ERROR: unable to create video/avc codec instance\n");
   2988         return UNKNOWN_ERROR;
   2989     }
   2990     ret = mTestContext->mViVVid.codec->configure(format, NULL, NULL,
   2991             MediaCodec::CONFIGURE_FLAG_ENCODE);
   2992     if (ret != NO_ERROR) {
   2993         mTestContext->mViVVid.codec->release();
   2994         mTestContext->mViVVid.codec.clear();
   2995 
   2996         fprintf(stderr, "ERROR: unable to configure codec (err=%d)\n", ret);
   2997         return ret;
   2998     }
   2999 
   3000     ALOGV("Creating buffer producer");
   3001     ret = mTestContext->mViVVid.codec->createInputSurface(
   3002         &mTestContext->mViVVid.bufferProducer);
   3003     if (ret != NO_ERROR) {
   3004         mTestContext->mViVVid.codec->release();
   3005         mTestContext->mViVVid.codec.clear();
   3006 
   3007         fprintf(stderr,
   3008             "ERROR: unable to create encoder input surface (err=%d)\n", ret);
   3009         return ret;
   3010     }
   3011 
   3012     ret = mTestContext->mViVVid.codec->start();
   3013     if (ret != NO_ERROR) {
   3014         mTestContext->mViVVid.codec->release();
   3015         mTestContext->mViVVid.codec.clear();
   3016 
   3017         fprintf(stderr, "ERROR: unable to start codec (err=%d)\n", ret);
   3018         return ret;
   3019     }
   3020     ALOGV("Codec prepared");
   3021 
   3022     mTestContext->mViVVid.surface = new Surface(
   3023         mTestContext->mViVVid.bufferProducer);
   3024     mTestContext->mViVVid.ANW = mTestContext->mViVVid.surface;
   3025     ret = native_window_api_connect(mTestContext->mViVVid.ANW.get(),
   3026         NATIVE_WINDOW_API_CPU);
   3027     if (mTestContext->mViVVid.VideoSizes[0].width *
   3028         mTestContext->mViVVid.VideoSizes[0].height >=
   3029         mTestContext->mViVVid.VideoSizes[1].width *
   3030         mTestContext->mViVVid.VideoSizes[1].height) {
   3031         native_window_set_buffers_format(mTestContext->mViVVid.ANW.get(),
   3032                 HAL_PIXEL_FORMAT_NV12_ENCODEABLE);
   3033         native_window_set_buffers_dimensions(mTestContext->mViVVid.ANW.get(),
   3034                 mTestContext->mViVVid.VideoSizes[0].width,
   3035                 mTestContext->mViVVid.VideoSizes[0].height);
   3036     } else {
   3037         native_window_set_buffers_format(mTestContext->mViVVid.ANW.get(),
   3038                 HAL_PIXEL_FORMAT_NV12_ENCODEABLE);
   3039         native_window_set_buffers_dimensions(mTestContext->mViVVid.ANW.get(),
   3040                 mTestContext->mViVVid.VideoSizes[1].width,
   3041                 mTestContext->mViVVid.VideoSizes[1].height);
   3042     }
   3043     native_window_set_usage(mTestContext->mViVVid.ANW.get(),
   3044         GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
   3045     native_window_set_buffer_count(mTestContext->mViVVid.ANW.get(),
   3046         mTestContext->mViVVid.buff_cnt);
   3047 
   3048     ViVEncoderThread();
   3049 
   3050     return ret;
   3051 }
   3052 
   3053 /*===========================================================================
   3054  * FUNCTION   : unconfigureViVCodec
   3055  *
   3056  * DESCRIPTION: Unconfigures video in video codec
   3057  *
   3058  * PARAMETERS : none
   3059  *
   3060  * RETURN     : status_t type of status
   3061  *              NO_ERROR  -- success
   3062  *              none-zero failure code
   3063  *==========================================================================*/
   3064 status_t Interpreter::unconfigureViVCodec()
   3065 {
   3066     status_t ret = NO_ERROR;
   3067 
   3068     ret = native_window_api_disconnect(mTestContext->mViVVid.ANW.get(),
   3069         NATIVE_WINDOW_API_CPU);
   3070     mTestContext->mViVVid.bufferProducer = NULL;
   3071     mTestContext->mViVVid.codec->stop();
   3072     pthread_join(mViVEncThread, NULL);
   3073     mTestContext->mViVVid.muxer->stop();
   3074     mTestContext->mViVVid.codec->release();
   3075     mTestContext->mViVVid.codec.clear();
   3076     mTestContext->mViVVid.muxer.clear();
   3077     mTestContext->mViVVid.surface.clear();
   3078   return ret;
   3079 }
   3080 
   3081 /*===========================================================================
   3082  * FUNCTION   : Interpreter
   3083  *
   3084  * DESCRIPTION: Interpreter constructor
   3085  *
   3086  * PARAMETERS : none
   3087  *
   3088  * RETURN     : none
   3089  *==========================================================================*/
   3090 Interpreter::Interpreter(const char *file)
   3091     : mCmdIndex(0)
   3092     , mScript(NULL)
   3093 {
   3094     if (!file){
   3095         printf("no File Given\n");
   3096         mUseScript = false;
   3097         return;
   3098     }
   3099 
   3100     FILE *fh = fopen(file, "r");
   3101     if ( !fh ) {
   3102         printf("Could not open file %s\n", file);
   3103         mUseScript = false;
   3104         return;
   3105     }
   3106 
   3107     fseek(fh, 0, SEEK_END);
   3108     size_t len = (size_t)ftell(fh);
   3109     rewind(fh);
   3110 
   3111     if( !len ) {
   3112         printf("Script file %s is empty !\n", file);
   3113         fclose(fh);
   3114         return;
   3115     }
   3116 
   3117     mScript = new char[len + 1];
   3118     if ( !mScript ) {
   3119         fclose(fh);
   3120         return;
   3121     }
   3122 
   3123     fread(mScript, sizeof(char), len, fh);
   3124     mScript[len] = '\0'; // ensure null terminated;
   3125     fclose(fh);
   3126 
   3127 
   3128     char *p1;
   3129     char *p2;
   3130     p1 = p2 = mScript;
   3131 
   3132     do {
   3133         switch (*p1) {
   3134         case '\0':
   3135         case '|':
   3136             p1++;
   3137             break;
   3138         case SWITCH_CAMERA_CMD:
   3139         case RESUME_PREVIEW_CMD:
   3140         case START_PREVIEW_CMD:
   3141         case STOP_PREVIEW_CMD:
   3142         case CHANGE_PREVIEW_SIZE_CMD:
   3143         case CHANGE_PICTURE_SIZE_CMD:
   3144         case START_RECORD_CMD:
   3145         case STOP_RECORD_CMD:
   3146         case START_VIV_RECORD_CMD:
   3147         case STOP_VIV_RECORD_CMD:
   3148         case DUMP_CAPS_CMD:
   3149         case AUTOFOCUS_CMD:
   3150         case TAKEPICTURE_CMD:
   3151         case TAKEPICTURE_IN_PICTURE_CMD:
   3152         case ENABLE_PRV_CALLBACKS_CMD:
   3153         case EXIT_CMD:
   3154         case ZSL_CMD:
   3155         case DELAY:
   3156             p2 = p1;
   3157             while( (p2 != (mScript + len)) && (*p2 != '|')) {
   3158                 p2++;
   3159             }
   3160             *p2 = '\0';
   3161             if (p2 == (p1 + 1))
   3162                 mCommands.push_back(Command(
   3163                     static_cast<Interpreter::Commands_e>(*p1)));
   3164             else
   3165                 mCommands.push_back(Command(
   3166                     static_cast<Interpreter::Commands_e>(*p1), (p1 + 1)));
   3167             p1 = p2;
   3168             break;
   3169         default:
   3170             printf("Invalid cmd %c \n", *p1);
   3171             do {
   3172                 p1++;
   3173 
   3174             } while(*p1 != '|' && p1 != (mScript + len));
   3175 
   3176         }
   3177     } while(p1 != (mScript + len));
   3178     mUseScript = true;
   3179 }
   3180 
   3181 /*===========================================================================
   3182  * FUNCTION   : ~Interpreter
   3183  *
   3184  * DESCRIPTION: Interpreter destructor
   3185  *
   3186  * PARAMETERS : none
   3187  *
   3188  * RETURN     : none
   3189  *==========================================================================*/
   3190 Interpreter::~Interpreter()
   3191 {
   3192     if ( mScript )
   3193         delete[] mScript;
   3194 
   3195     mCommands.clear();
   3196 }
   3197 
   3198 /*===========================================================================
   3199  * FUNCTION        : getCommand
   3200  *
   3201  * DESCRIPTION     : Get a command from interpreter
   3202  *
   3203  * PARAMETERS      :
   3204  *   @currentCamera: Current camera context
   3205  *
   3206  * RETURN          : command
   3207  *==========================================================================*/
   3208 Interpreter::Command Interpreter::getCommand(
   3209     sp<CameraContext> currentCamera)
   3210 {
   3211     if( mUseScript ) {
   3212         return mCommands[mCmdIndex++];
   3213     } else {
   3214         currentCamera->printMenu(currentCamera);
   3215         return Interpreter::Command(
   3216             static_cast<Interpreter::Commands_e>(getchar()));
   3217     }
   3218 }
   3219 
   3220 /*===========================================================================
   3221  * FUNCTION        : TestContext
   3222  *
   3223  * DESCRIPTION     : TestContext constructor
   3224  *
   3225  * PARAMETERS      : None
   3226  *
   3227  * RETURN          : None
   3228  *==========================================================================*/
   3229 TestContext::TestContext()
   3230 {
   3231     int i = 0;
   3232     mTestRunning = false;
   3233     mInterpreter = NULL;
   3234     mViVVid.ViVIdx = 0;
   3235     mViVVid.buff_cnt = 9;
   3236     mViVVid.graphBuf = 0;
   3237     mViVVid.mappedBuff = NULL;
   3238     mViVVid.isBuffValid = false;
   3239     mViVVid.sourceCameraID = -1;
   3240     mViVVid.destinationCameraID = -1;
   3241     mPiPinUse = false;
   3242     mViVinUse = false;
   3243     mIsZSLOn = false;
   3244     memset(&mViVBuff, 0, sizeof(ViVBuff_t));
   3245 
   3246     ProcessState::self()->startThreadPool();
   3247 
   3248     do {
   3249         camera[i] = new CameraContext(i);
   3250         if ( NULL == camera[i].get() ) {
   3251             break;
   3252         }
   3253         camera[i]->setTestCtxInstance(this);
   3254 
   3255         //by default open only back camera
   3256         if (i==0) {
   3257             status_t stat = camera[i]->openCamera();
   3258             if ( NO_ERROR != stat ) {
   3259                 printf("Error encountered Openging camera id : %d\n", i);
   3260                 break;
   3261             }
   3262         }
   3263         mAvailableCameras.add(camera[i]);
   3264         i++;
   3265     } while ( i < camera[0]->getNumberOfCameras() ) ;
   3266 
   3267     if (i < camera[0]->getNumberOfCameras() ) {
   3268         for (size_t j = 0; j < mAvailableCameras.size(); j++) {
   3269             camera[j] = mAvailableCameras.itemAt(j);
   3270             camera[j]->closeCamera();
   3271             camera[j].clear();
   3272         }
   3273 
   3274         mAvailableCameras.clear();
   3275     }
   3276 }
   3277 
   3278 /*===========================================================================
   3279  * FUNCTION        : ~TestContext
   3280  *
   3281  * DESCRIPTION     : TestContext destructor
   3282  *
   3283  * PARAMETERS      : None
   3284  *
   3285  * RETURN          : None
   3286  *==========================================================================*/
   3287 TestContext::~TestContext()
   3288 {
   3289     delete mInterpreter;
   3290 
   3291     for (size_t j = 0; j < mAvailableCameras.size(); j++) {
   3292         camera[j] = mAvailableCameras.itemAt(j);
   3293         camera[j]->closeCamera();
   3294         camera[j].clear();
   3295     }
   3296 
   3297     mAvailableCameras.clear();
   3298 }
   3299 
   3300 /*===========================================================================
   3301  * FUNCTION        : GetCamerasNum
   3302  *
   3303  * DESCRIPTION     : Get the number of available cameras
   3304  *
   3305  * PARAMETERS      : None
   3306  *
   3307  * RETURN          : Number of cameras
   3308  *==========================================================================*/
   3309 size_t TestContext::GetCamerasNum()
   3310 {
   3311     return mAvailableCameras.size();
   3312 }
   3313 
   3314 /*===========================================================================
   3315  * FUNCTION        : AddScriptFromFile
   3316  *
   3317  * DESCRIPTION     : Add script from file
   3318  *
   3319  * PARAMETERS      :
   3320  *   @scriptFile   : Script file
   3321  *
   3322  * RETURN          : status_t type of status
   3323  *                   NO_ERROR  -- success
   3324  *                   none-zero failure code
   3325  *==========================================================================*/
   3326 status_t TestContext::AddScriptFromFile(const char *scriptFile)
   3327 {
   3328     mInterpreter = new Interpreter(scriptFile);
   3329     mInterpreter->setTestCtxInst(this);
   3330 
   3331     return NO_ERROR;
   3332 }
   3333 
   3334 /*===========================================================================
   3335  * FUNCTION        : releasePiPBuff
   3336  *
   3337  * DESCRIPTION     : Release video in video temp buffer
   3338  *
   3339  * PARAMETERS      : None
   3340  *
   3341  * RETURN          : None
   3342  *==========================================================================*/
   3343 void Interpreter::releasePiPBuff() {
   3344     free(mTestContext->mViVBuff.buff);
   3345     mTestContext->mViVBuff.buff = NULL;
   3346 }
   3347 
   3348 /*===========================================================================
   3349  * FUNCTION   : functionalTest
   3350  *
   3351  * DESCRIPTION: queries and executes client supplied commands for testing a
   3352  *              particular camera.
   3353  *
   3354  * PARAMETERS :
   3355  *  @availableCameras : List with all cameras supported
   3356  *
   3357  * RETURN     : status_t type of status
   3358  *              NO_ERROR  -- continue testing
   3359  *              none-zero -- quit test
   3360  *==========================================================================*/
   3361 status_t TestContext::FunctionalTest()
   3362 {
   3363     status_t stat = NO_ERROR;
   3364     const char *ZSLStr = NULL;
   3365     size_t ZSLStrSize = 0;
   3366 
   3367     assert(mAvailableCameras.size());
   3368 
   3369     if ( !mInterpreter ) {
   3370         mInterpreter = new Interpreter();
   3371         mInterpreter->setTestCtxInst(this);
   3372     }
   3373 
   3374     if (mAvailableCameras.size() == 0) {
   3375         printf("no cameras supported... exiting test app\n");
   3376     } else {
   3377         mTestRunning = true;
   3378     }
   3379 
   3380     while (mTestRunning) {
   3381         sp<CameraContext> currentCamera =
   3382             mAvailableCameras.itemAt(mCurrentCameraIndex);
   3383         Interpreter::Command command =
   3384             mInterpreter->getCommand(currentCamera);
   3385         currentCamera->enablePrintPreview();
   3386 
   3387         switch (command.cmd) {
   3388         case Interpreter::SWITCH_CAMERA_CMD:
   3389         {
   3390             mCurrentCameraIndex++;
   3391             mCurrentCameraIndex %= mAvailableCameras.size();
   3392             currentCamera = mAvailableCameras.itemAt(mCurrentCameraIndex);
   3393             stat = currentCamera->openCamera();
   3394         }
   3395             break;
   3396 
   3397         case Interpreter::RESUME_PREVIEW_CMD:
   3398         {
   3399             stat = currentCamera->resumePreview();
   3400         }
   3401             break;
   3402 
   3403         case Interpreter::START_PREVIEW_CMD:
   3404         {
   3405             stat = currentCamera->startPreview();
   3406         }
   3407             break;
   3408 
   3409         case Interpreter::STOP_PREVIEW_CMD:
   3410         {
   3411             stat = currentCamera->stopPreview();
   3412         }
   3413             break;
   3414 
   3415         case Interpreter::CHANGE_VIDEO_SIZE_CMD:
   3416         {
   3417             if ( command.arg )
   3418                 stat = currentCamera->setVideoSize(command.arg);
   3419             else
   3420                 stat = currentCamera->nextVideoSize();
   3421         }
   3422         break;
   3423 
   3424         case Interpreter::CHANGE_PREVIEW_SIZE_CMD:
   3425         {
   3426             if ( command.arg )
   3427                 stat = currentCamera->setPreviewSize(command.arg);
   3428             else
   3429                 stat = currentCamera->nextPreviewSize();
   3430         }
   3431             break;
   3432 
   3433         case Interpreter::CHANGE_PICTURE_SIZE_CMD:
   3434         {
   3435             if ( command.arg )
   3436                 stat = currentCamera->setPictureSize(command.arg);
   3437             else
   3438                 stat = currentCamera->nextPictureSize();
   3439         }
   3440             break;
   3441 
   3442         case Interpreter::DUMP_CAPS_CMD:
   3443         {
   3444             currentCamera->printSupportedParams();
   3445         }
   3446             break;
   3447 
   3448         case Interpreter::AUTOFOCUS_CMD:
   3449         {
   3450             stat = currentCamera->autoFocus();
   3451         }
   3452             break;
   3453 
   3454         case Interpreter::TAKEPICTURE_CMD:
   3455         {
   3456             stat = currentCamera->takePicture();
   3457         }
   3458             break;
   3459 
   3460         case Interpreter::TAKEPICTURE_IN_PICTURE_CMD:
   3461         {
   3462             if (mAvailableCameras.size() == 2) {
   3463                 mSaveCurrentCameraIndex = mCurrentCameraIndex;
   3464                 for (size_t i = 0; i < mAvailableCameras.size(); i++) {
   3465                     mCurrentCameraIndex = i;
   3466                     currentCamera = mAvailableCameras.itemAt(mCurrentCameraIndex);
   3467                     currentCamera->enablePiPCapture();
   3468                     stat = currentCamera->takePicture();
   3469                 }
   3470                 mCurrentCameraIndex = mSaveCurrentCameraIndex;
   3471             } else {
   3472                 printf("Number of available sensors should be 2\n");
   3473             }
   3474         }
   3475         break;
   3476 
   3477         case Interpreter::ENABLE_PRV_CALLBACKS_CMD:
   3478         {
   3479             stat = currentCamera->enablePreviewCallbacks();
   3480         }
   3481             break;
   3482 
   3483         case Interpreter::START_RECORD_CMD:
   3484         {
   3485             stat = currentCamera->stopPreview();
   3486             stat = currentCamera->configureRecorder();
   3487             stat = currentCamera->startPreview();
   3488             stat = currentCamera->startRecording();
   3489         }
   3490             break;
   3491 
   3492         case Interpreter::STOP_RECORD_CMD:
   3493         {
   3494             stat = currentCamera->stopRecording();
   3495 
   3496             stat = currentCamera->stopPreview();
   3497             stat = currentCamera->unconfigureRecorder();
   3498             stat = currentCamera->startPreview();
   3499         }
   3500             break;
   3501 
   3502         case Interpreter::START_VIV_RECORD_CMD:
   3503         {
   3504 
   3505             if (mAvailableCameras.size() == 2) {
   3506                 mSaveCurrentCameraIndex = mCurrentCameraIndex;
   3507                 stat = mInterpreter->configureViVCodec();
   3508                 for ( size_t i = 0; i < mAvailableCameras.size(); i++ ) {
   3509                     mCurrentCameraIndex = i;
   3510                     currentCamera = mAvailableCameras.itemAt(
   3511                         mCurrentCameraIndex);
   3512                     stat = currentCamera->stopPreview();
   3513                     stat = currentCamera->configureViVRecording();
   3514                     stat = currentCamera->startPreview();
   3515                     stat = currentCamera->startViVRecording();
   3516                 }
   3517                 mCurrentCameraIndex = mSaveCurrentCameraIndex;
   3518             } else {
   3519                 printf("Number of available sensors should be 2\n");
   3520             }
   3521 
   3522         }
   3523             break;
   3524 
   3525         case Interpreter::STOP_VIV_RECORD_CMD:
   3526         {
   3527             if (mAvailableCameras.size() == 2) {
   3528                 mSaveCurrentCameraIndex = mCurrentCameraIndex;
   3529                 for ( size_t i = 0; i < mAvailableCameras.size(); i++ ) {
   3530                     mCurrentCameraIndex = i;
   3531                     currentCamera = mAvailableCameras.itemAt(
   3532                         mCurrentCameraIndex);
   3533                     stat = currentCamera->stopViVRecording();
   3534                     stat = currentCamera->stopPreview();
   3535                     stat = currentCamera->unconfigureRecorder();
   3536                     stat = currentCamera->startPreview();
   3537                 }
   3538                 stat = mInterpreter->unconfigureViVCodec();
   3539                 mCurrentCameraIndex = mSaveCurrentCameraIndex;
   3540 
   3541                 mInterpreter->releasePiPBuff();
   3542             } else {
   3543                 printf("Number of available sensors should be 2\n");
   3544             }
   3545         }
   3546         break;
   3547 
   3548         case Interpreter::EXIT_CMD:
   3549         {
   3550             currentCamera->stopPreview();
   3551             mTestRunning = false;
   3552         }
   3553             break;
   3554 
   3555         case Interpreter::DELAY:
   3556         {
   3557             if ( command.arg ) {
   3558                 int delay = atoi(command.arg);
   3559                 if (0 < delay) {
   3560                     usleep(1000U * (unsigned int)delay);
   3561                 }
   3562             }
   3563         }
   3564             break;
   3565 
   3566         case Interpreter::ZSL_CMD:
   3567         {
   3568             currentCamera = mAvailableCameras.itemAt(
   3569                     mCurrentCameraIndex);
   3570             ZSLStr = currentCamera->getZSL();
   3571 
   3572             if (NULL != ZSLStr) {
   3573                 ZSLStrSize = strlen(ZSLStr);
   3574                 if (!strncmp(ZSLStr, "off", ZSLStrSize)) {
   3575                     currentCamera->setZSL("on");
   3576                     mIsZSLOn = true;
   3577                 } else if (!strncmp(ZSLStr, "on", ZSLStrSize)) {
   3578                     currentCamera->setZSL("off");
   3579                     mIsZSLOn = false;
   3580                 } else {
   3581                     printf("Set zsl failed!\n");
   3582                 }
   3583             } else {
   3584                 printf("zsl is NULL\n");
   3585             }
   3586         }
   3587             break;
   3588 
   3589         default:
   3590         {
   3591             currentCamera->disablePrintPreview();
   3592         }
   3593             break;
   3594         }
   3595         printf("Command status 0x%x \n", stat);
   3596     }
   3597 
   3598     return NO_ERROR;
   3599 }
   3600 
   3601 /*===========================================================================
   3602  * FUNCTION   : PiPLock
   3603  *
   3604  * DESCRIPTION: Mutex lock for PiP capture
   3605  *
   3606  * PARAMETERS : none
   3607  *
   3608  * RETURN     : none
   3609  *==========================================================================*/
   3610 void TestContext::PiPLock()
   3611 {
   3612     Mutex::Autolock l(mPiPLock);
   3613     while (mPiPinUse) {
   3614         mPiPCond.wait(mPiPLock);
   3615     }
   3616     mPiPinUse = true;
   3617 }
   3618 
   3619 /*===========================================================================
   3620  * FUNCTION   : PiPUnLock
   3621  *
   3622  * DESCRIPTION: Mutex unlock for PiP capture
   3623  *
   3624  * PARAMETERS : none
   3625  *
   3626  * RETURN     : none
   3627  *==========================================================================*/
   3628 void TestContext::PiPUnlock()
   3629 {
   3630     Mutex::Autolock l(mPiPLock);
   3631     mPiPinUse = false;
   3632     mPiPCond.signal();
   3633 }
   3634 
   3635 /*===========================================================================
   3636  * FUNCTION   : ViVLock
   3637  *
   3638  * DESCRIPTION: Mutex lock for ViV Video
   3639  *
   3640  * PARAMETERS : none
   3641  *
   3642  * RETURN     : none
   3643  *==========================================================================*/
   3644 void TestContext::ViVLock()
   3645 {
   3646     Mutex::Autolock l(mViVLock);
   3647     while (mViVinUse) {
   3648         mViVCond.wait(mViVLock);
   3649     }
   3650     mViVinUse = true;
   3651 }
   3652 
   3653 /*===========================================================================
   3654  * FUNCTION   : ViVUnlock
   3655  *
   3656  * DESCRIPTION: Mutex unlock for ViV Video
   3657  *
   3658  * PARAMETERS : none
   3659  *
   3660  * RETURN     : none
   3661  *==========================================================================*/
   3662 void TestContext::ViVUnlock()
   3663 {
   3664     Mutex::Autolock l(mViVLock);
   3665     mViVinUse = false;
   3666     mViVCond.signal();
   3667 }
   3668 
   3669 /*===========================================================================
   3670  * FUNCTION     : setViVSize
   3671  *
   3672  * DESCRIPTION  : Set video in video size
   3673  *
   3674  * PARAMETERS   :
   3675  *   @VideoSize : video size
   3676  *   @camIndex  : camera index
   3677  *
   3678  * RETURN       : none
   3679  *==========================================================================*/
   3680 void TestContext::setViVSize(Size VideoSize, int camIndex)
   3681 {
   3682     mViVVid.VideoSizes[camIndex] = VideoSize;
   3683 }
   3684 
   3685 /*===========================================================================
   3686  * FUNCTION     : main
   3687  *
   3688  * DESCRIPTION  : main function
   3689  *
   3690  * PARAMETERS   :
   3691  *   @argc      : argc
   3692  *   @argv      : argv
   3693  *
   3694  * RETURN       : int status
   3695  *==========================================================================*/
   3696 int main(int argc, char *argv[])
   3697 {
   3698     TestContext ctx;
   3699 
   3700     if (argc > 1) {
   3701         if ( ctx.AddScriptFromFile((const char *)argv[1]) ) {
   3702             printf("Could not add script file... "
   3703                 "continuing in normal menu mode! \n");
   3704         }
   3705     }
   3706 
   3707     ctx.FunctionalTest();
   3708 
   3709     return 0;
   3710 }
   3711