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