VideoEditorMain.cpp revision beb9fc8ee8d3bd14d141104e91d41809dcfe0e1a
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <dlfcn.h>
18#include <stdio.h>
19#include <unistd.h>
20#include <utils/Log.h>
21#include <utils/threads.h>
22#include <VideoEditorClasses.h>
23#include <VideoEditorJava.h>
24#include <VideoEditorOsal.h>
25#include <VideoEditorLogging.h>
26#include <marker.h>
27#include <VideoEditorClasses.h>
28#include <VideoEditorThumbnailMain.h>
29#include <M4OSA_Debug.h>
30#include <M4xVSS_Internal.h>
31#include <surfaceflinger/Surface.h>
32#include <surfaceflinger/ISurface.h>
33#include "VideoEditorPreviewController.h"
34
35#include "VideoEditorMain.h"
36
37extern "C" {
38#include <M4OSA_Clock.h>
39#include <M4OSA_CharStar.h>
40#include <M4OSA_Error.h>
41#include <M4OSA_FileCommon.h>
42#include <M4OSA_FileReader.h>
43#include <M4OSA_FileWriter.h>
44#include <M4OSA_FileExtra.h>
45#include <M4OSA_Memory.h>
46#include <M4OSA_String.h>
47#include <M4OSA_Thread.h>
48#include <M4xVSS_API.h>
49#include <M4VSS3GPP_ErrorCodes.h>
50#include <M4MCS_API.h>
51#include <M4MCS_ErrorCodes.h>
52#include <M4MDP_API.h>
53#include <M4READER_Common.h>
54#include <M4WRITER_common.h>
55};
56
57
58using namespace android;
59
60#define THREAD_STACK_SIZE       (65536)
61
62#define VIDEOEDITOR_VERSION_MAJOR     0
63#define VIDEOEDITOR_VERSION_MINOR     0
64#define VIDEOEDITOR_VERSION_REVISION  1
65
66
67typedef enum
68{
69    ManualEditState_NOT_INITIALIZED,
70    ManualEditState_INITIALIZED,
71    ManualEditState_ANALYZING,
72    ManualEditState_ANALYZING_ERROR,
73    ManualEditState_OPENED,
74    ManualEditState_SAVING,
75    ManualEditState_SAVING_ERROR,
76    ManualEditState_SAVED,
77    ManualEditState_STOPPING
78} ManualEditState;
79
80typedef struct
81{
82    JavaVM*                        pVM;
83    jobject                        engine;
84    jmethodID                      onCompletionMethodId;
85    jmethodID                      onErrorMethodId;
86    jmethodID                      onWarningMethodId;
87    jmethodID                      onProgressUpdateMethodId;
88    jmethodID                      onPreviewProgressUpdateMethodId;
89    jmethodID                      previewFrameEditInfoId;
90    M4xVSS_InitParams              initParams;
91    void*                          pTextRendererHandle;
92    M4xVSS_getTextRgbBufferFct     pTextRendererFunction;
93    M4OSA_Context                  engineContext;
94    ManualEditState                state;
95    M4VSS3GPP_EditSettings*        pEditSettings;
96    M4OSA_Context                  threadContext;
97    M4OSA_ERR                      threadResult;
98    M4OSA_UInt8                    threadProgress;
99    VideoEditorPreviewController   *mPreviewController;
100    M4xVSS_AudioMixingSettings     *mAudioSettings;
101    /* Audio Graph changes */
102    M4OSA_Context                   pAudioGraphMCSCtx;
103    M4OSA_Bool                      bSkipState;
104    jmethodID                       onAudioGraphProgressUpdateMethodId;
105    Mutex                           mLock;
106    bool                            mIsUpdateOverlay;
107    char                            *mOverlayFileName;
108    int                             mOverlayRenderingMode;
109} ManualEditContext;
110
111extern "C" M4OSA_ERR M4MCS_open_normalMode(
112                M4MCS_Context                       pContext,
113                M4OSA_Void*                         pFileIn,
114                M4VIDEOEDITING_FileType             InputFileType,
115                M4OSA_Void*                         pFileOut,
116                M4OSA_Void*                         pTempFile);
117
118static M4OSA_ERR videoEditor_toUTF8Fct(
119                M4OSA_Void*                         pBufferIn,
120                M4OSA_UInt8*                        pBufferOut,
121                M4OSA_UInt32*                       bufferOutSize);
122
123static M4OSA_ERR videoEditor_fromUTF8Fct(
124                M4OSA_UInt8*                        pBufferIn,
125                M4OSA_Void*                         pBufferOut,
126                M4OSA_UInt32*                       bufferOutSize);
127
128static M4OSA_ERR videoEditor_getTextRgbBufferFct(
129                M4OSA_Void*                         pRenderingData,
130                M4OSA_Void*                         pTextBuffer,
131                M4OSA_UInt32                        textBufferSize,
132                M4VIFI_ImagePlane**                 pOutputPlane);
133
134static void videoEditor_callOnProgressUpdate(
135                ManualEditContext*                  pContext,
136                int                                 task,
137                int                                 progress);
138
139static void videoEditor_freeContext(
140                JNIEnv*                             pEnv,
141                ManualEditContext**                 ppContext);
142
143static M4OSA_ERR videoEditor_threadProc(
144                M4OSA_Void*                         param);
145
146static jobject videoEditor_getVersion(
147                JNIEnv*                             pEnv,
148                jobject                             thiz);
149
150static void videoEditor_init(
151                JNIEnv*                             pEnv,
152                jobject                             thiz,
153                jstring                             tempPath,
154                jstring                             textRendererPath);
155
156static void videoEditor_loadSettings(
157                JNIEnv*                             pEnv,
158                jobject                             thiz,
159                jobject                             settings);
160
161static void videoEditor_unloadSettings(
162                JNIEnv*                             pEnv,
163                jobject                             thiz);
164
165
166static void videoEditor_stopEncoding(
167                JNIEnv*                             pEnv,
168                jobject                             thiz);
169
170static void videoEditor_release(
171                JNIEnv*                             pEnv,
172                jobject                             thiz);
173static int videoEditor_getPixels(
174                                 JNIEnv*                  env,
175                                 jobject                  thiz,
176                                 jstring                  path,
177                                 jintArray                pixelArray,
178                                 M4OSA_UInt32             width,
179                                 M4OSA_UInt32             height,
180                                 M4OSA_UInt32             timeMS);
181static int videoEditor_getPixelsList(
182                                     JNIEnv*                  env,
183                                     jobject                  thiz,
184                                     jstring                  path,
185                                     jintArray                pixelArray,
186                                     M4OSA_UInt32             width,
187                                     M4OSA_UInt32             height,
188                                     M4OSA_UInt32             deltatimeMS,
189                                     M4OSA_UInt32             noOfThumbnails,
190                                     M4OSA_UInt32             startTime,
191                                     M4OSA_UInt32             endTime);
192
193static void
194videoEditor_startPreview(
195                JNIEnv*                 pEnv,
196                jobject                 thiz,
197                jobject                 mSurface,
198                jlong                   fromMs,
199                jlong                   toMs,
200                jint                    callbackInterval,
201                jboolean                loop);
202
203static void
204videoEditor_populateSettings(
205                JNIEnv*                 pEnv,
206                jobject                 thiz,
207                jobject                 settings,
208                jobject                 object,
209                jobject                 audioSettingObject);
210
211static void videoEditor_stopPreview(JNIEnv*  pEnv,
212                              jobject  thiz);
213
214static jobject
215videoEditor_getProperties(
216                JNIEnv*                             pEnv,
217                jobject                             thiz,
218                jstring                             file);
219
220static int videoEditor_renderPreviewFrame(JNIEnv* pEnv,
221                                    jobject thiz,
222                                    jobject    mSurface,
223                                    jlong fromMs,
224                                    jint  surfaceWidth,
225                                    jint  surfaceHeight);
226
227static int videoEditor_registerManualEditMethods(
228                JNIEnv*                             pEnv);
229
230static void jniPreviewProgressCallback(void* cookie, M4OSA_UInt32 msgType,
231                                        void *argc);
232
233static int videoEditor_renderMediaItemPreviewFrame(JNIEnv* pEnv,
234                                                    jobject thiz,
235                                                    jobject mSurface,
236                                                    jstring filePath,
237                                                    jint frameWidth,
238                                                    jint frameHeight,
239                                                    jint surfaceWidth,
240                                                    jint surfaceHeight,
241                                                    jlong fromMs);
242
243static int videoEditor_generateAudioWaveFormSync ( JNIEnv*     pEnv,
244                                                  jobject     thiz,
245                                                  jstring     pcmfilePath,
246                                                  jstring     outGraphfilePath,
247                                                  jint        frameDuration,
248                                                  jint        channels,
249                                                  jint        samplesCount);
250
251static int videoEditor_generateAudioRawFile(JNIEnv* pEnv,
252                                    jobject thiz,
253                                    jstring infilePath,
254                                    jstring pcmfilePath );
255
256M4OSA_ERR videoEditor_generateAudio(JNIEnv* pEnv,ManualEditContext* pContext,
257                                    M4OSA_Char* infilePath,
258                                    M4OSA_Char* pcmfilePath );
259
260static int
261videoEditor_generateClip(
262                JNIEnv*                             pEnv,
263                jobject                             thiz,
264                jobject                             settings);
265
266static void videoEditor_clearSurface(JNIEnv* pEnv,
267                                    jobject thiz,
268                                    jobject surface);
269
270static JNINativeMethod gManualEditMethods[] = {
271    {"getVersion",               "()L"VERSION_CLASS_NAME";",
272                                (void *)videoEditor_getVersion      },
273    {"_init",                    "(Ljava/lang/String;Ljava/lang/String;)V",
274                                (void *)videoEditor_init    },
275    {"nativeStartPreview",       "(Landroid/view/Surface;JJIZ)V",
276                                (void *)videoEditor_startPreview    },
277    {"nativePopulateSettings",
278            "(L"EDIT_SETTINGS_CLASS_NAME";L"PREVIEW_PROPERTIES_CLASS_NAME";L"
279            AUDIO_SETTINGS_CLASS_NAME";)V",
280                                (void *)videoEditor_populateSettings    },
281    {"nativeRenderPreviewFrame", "(Landroid/view/Surface;JII)I",
282                                (int *)videoEditor_renderPreviewFrame     },
283    {"nativeRenderMediaItemPreviewFrame",
284    "(Landroid/view/Surface;Ljava/lang/String;IIIIJ)I",
285                        (int *)videoEditor_renderMediaItemPreviewFrame     },
286    {"nativeStopPreview",       "()V",
287                                (void *)videoEditor_stopPreview            },
288    {"stopEncoding",            "()V",
289                                (void *)videoEditor_stopEncoding         },
290    {"release",                 "()V",
291                                (void *)videoEditor_release            },
292    {"nativeGetPixels",         "(Ljava/lang/String;[IIIJ)I",
293                                (void*)videoEditor_getPixels               },
294    {"nativeGetPixelsList",     "(Ljava/lang/String;[IIIIIJJ)I",
295                                (void*)videoEditor_getPixelsList           },
296    {"getMediaProperties",
297    "(Ljava/lang/String;)Landroid/media/videoeditor/MediaArtistNativeHelper$Properties;",
298                                (void *)videoEditor_getProperties          },
299    {"nativeGenerateAudioGraph","(Ljava/lang/String;Ljava/lang/String;III)I",
300                                (int *)videoEditor_generateAudioWaveFormSync },
301    {"nativeGenerateRawAudio",  "(Ljava/lang/String;Ljava/lang/String;)I",
302                                (int *)videoEditor_generateAudioRawFile      },
303    {"nativeGenerateClip",      "(L"EDIT_SETTINGS_CLASS_NAME";)I",
304                                (void *)videoEditor_generateClip  },
305    {"nativeClearSurface",       "(Landroid/view/Surface;)V",
306                                (void *)videoEditor_clearSurface  },
307};
308
309// temp file name of VSS out file
310#define TEMP_MCS_OUT_FILE_PATH "tmpOut.3gp"
311
312void
313getClipSetting(
314                JNIEnv*                                       pEnv,
315                jobject                                       object,
316                M4VSS3GPP_ClipSettings*                       pSettings)
317{
318
319    jfieldID fid;
320    int field = 0;
321    bool needToBeLoaded = true;
322    jclass clazz = pEnv->FindClass(PROPERTIES_CLASS_NAME);
323
324    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
325                                             (M4OSA_NULL == clazz),
326                                             "not initialized");
327
328    fid = pEnv->GetFieldID(clazz,"duration","I");
329    pSettings->ClipProperties.uiClipDuration = pEnv->GetIntField(object,fid);
330    M4OSA_TRACE1_1("duration = %d",pSettings->ClipProperties.uiClipDuration);
331
332    fid = pEnv->GetFieldID(clazz,"videoFormat","I");
333    pSettings->ClipProperties.VideoStreamType =
334        (M4VIDEOEDITING_VideoFormat)pEnv->GetIntField(object,fid);
335    M4OSA_TRACE1_1("videoFormat = %d",pSettings->ClipProperties.VideoStreamType);
336
337    fid = pEnv->GetFieldID(clazz,"videoDuration","I");
338    pSettings->ClipProperties.uiClipVideoDuration = pEnv->GetIntField(object,fid);
339    M4OSA_TRACE1_1("videoDuration = %d",
340                    pSettings->ClipProperties.uiClipVideoDuration);
341
342    fid = pEnv->GetFieldID(clazz,"width","I");
343    pSettings->ClipProperties.uiVideoWidth = pEnv->GetIntField(object,fid);
344    M4OSA_TRACE1_1("width = %d",pSettings->ClipProperties.uiVideoWidth);
345
346    fid = pEnv->GetFieldID(clazz,"height","I");
347    pSettings->ClipProperties.uiVideoHeight = pEnv->GetIntField(object,fid);
348    M4OSA_TRACE1_1("height = %d",pSettings->ClipProperties.uiVideoHeight);
349
350    fid = pEnv->GetFieldID(clazz,"audioFormat","I");
351    pSettings->ClipProperties.AudioStreamType =
352        (M4VIDEOEDITING_AudioFormat)pEnv->GetIntField(object,fid);
353    M4OSA_TRACE1_1("audioFormat = %d",pSettings->ClipProperties.AudioStreamType);
354
355    fid = pEnv->GetFieldID(clazz,"audioDuration","I");
356    pSettings->ClipProperties.uiClipAudioDuration = pEnv->GetIntField(object,fid);
357    M4OSA_TRACE1_1("audioDuration = %d",
358                    pSettings->ClipProperties.uiClipAudioDuration);
359
360    fid = pEnv->GetFieldID(clazz,"audioBitrate","I");
361    pSettings->ClipProperties.uiAudioBitrate = pEnv->GetIntField(object,fid);
362    M4OSA_TRACE1_1("audioBitrate = %d",pSettings->ClipProperties.uiAudioBitrate);
363
364    fid = pEnv->GetFieldID(clazz,"audioChannels","I");
365    pSettings->ClipProperties.uiNbChannels = pEnv->GetIntField(object,fid);
366    M4OSA_TRACE1_1("audioChannels = %d",pSettings->ClipProperties.uiNbChannels);
367
368    fid = pEnv->GetFieldID(clazz,"audioSamplingFrequency","I");
369    pSettings->ClipProperties.uiSamplingFrequency = pEnv->GetIntField(object,fid);
370    M4OSA_TRACE1_1("audioSamplingFrequency = %d",
371                    pSettings->ClipProperties.uiSamplingFrequency);
372
373   fid = pEnv->GetFieldID(clazz,"audioVolumeValue","I");
374   pSettings->ClipProperties.uiClipAudioVolumePercentage =
375                    pEnv->GetIntField(object,fid);
376   M4OSA_TRACE1_1("audioVolumeValue = %d",
377                    pSettings->ClipProperties.uiClipAudioVolumePercentage);
378}
379
380static void jniPreviewProgressCallback (void* cookie, M4OSA_UInt32 msgType,
381                                        void *argc)
382{
383    ManualEditContext *pContext = (ManualEditContext *)cookie;
384    JNIEnv*     pEnv = NULL;
385    bool        isFinished = false;
386    int         currentMs = 0;
387    int         error = M4NO_ERROR;
388    bool        isUpdateOverlay = false;
389    int         overlayEffectIndex;
390    char        *extPos;
391    bool        isSendProgress = true;
392    jstring     tmpFileName;
393    VideoEditorCurretEditInfo *pCurrEditInfo;
394
395    // Attach the current thread.
396    pContext->pVM->AttachCurrentThread(&pEnv, NULL);
397    switch(msgType)
398    {
399        case MSG_TYPE_PROGRESS_INDICATION:
400            currentMs = *(int*)argc;
401            break;
402        case MSG_TYPE_PLAYER_ERROR:
403            currentMs = -1;
404            error = *(int*)argc;
405            break;
406        case MSG_TYPE_PREVIEW_END:
407            isFinished = true;
408            break;
409        case MSG_TYPE_OVERLAY_UPDATE:
410        {
411            int overlayFileNameLen = 0;
412            isSendProgress = false;
413            pContext->mIsUpdateOverlay = true;
414            pCurrEditInfo = (VideoEditorCurretEditInfo*)argc;
415            overlayEffectIndex = pCurrEditInfo->overlaySettingsIndex;
416            LOGV("MSG_TYPE_OVERLAY_UPDATE");
417
418            if (pContext->mOverlayFileName != NULL) {
419                M4OSA_free((M4OSA_MemAddr32)pContext->mOverlayFileName);
420                pContext->mOverlayFileName = NULL;
421            }
422
423            overlayFileNameLen =
424                strlen((const char*)pContext->pEditSettings->Effects[overlayEffectIndex].xVSS.pFramingFilePath);
425
426            pContext->mOverlayFileName =
427                (char*)M4OSA_malloc(overlayFileNameLen+1,
428                                    M4VS, (M4OSA_Char*)"videoEdito JNI overlayFile");
429            if (pContext->mOverlayFileName != NULL) {
430                strncpy (pContext->mOverlayFileName,
431                    (const char*)pContext->pEditSettings->\
432                    Effects[overlayEffectIndex].xVSS.pFramingFilePath, overlayFileNameLen);
433                //Change the name to png file
434                extPos = strstr(pContext->mOverlayFileName, ".rgb");
435                if (extPos != NULL) {
436                    *extPos = '\0';
437                } else {
438                    LOGE("ERROR the overlay file is incorrect");
439                }
440
441                strcat(pContext->mOverlayFileName, ".png");
442                LOGV("Conv string is %s", pContext->mOverlayFileName);
443                LOGV("Current Clip index = %d", pCurrEditInfo->clipIndex);
444
445                pContext->mOverlayRenderingMode = pContext->pEditSettings->\
446                         pClipList[pCurrEditInfo->clipIndex]->xVSS.MediaRendering;
447                LOGI("rendering mode %d ", pContext->mOverlayRenderingMode);
448
449            }
450
451            break;
452        }
453
454        case MSG_TYPE_OVERLAY_CLEAR:
455            isSendProgress = false;
456            pContext->mOverlayFileName = NULL;
457            LOGV("MSG_TYPE_OVERLAY_CLEAR");
458            //argc is not used
459            pContext->mIsUpdateOverlay = true;
460            break;
461        default:
462            break;
463    }
464
465    if (isSendProgress) {
466        tmpFileName  = pEnv->NewStringUTF(pContext->mOverlayFileName);
467        pEnv->CallVoidMethod(pContext->engine,
468                pContext->onPreviewProgressUpdateMethodId,
469                currentMs,isFinished, pContext->mIsUpdateOverlay,
470                tmpFileName, pContext->mOverlayRenderingMode);
471
472        if (pContext->mIsUpdateOverlay) {
473            pContext->mIsUpdateOverlay = false;
474        }
475
476        if (tmpFileName) {
477            pEnv->DeleteLocalRef(tmpFileName);
478        }
479    }
480
481    // Detach the current thread.
482    pContext->pVM->DetachCurrentThread();
483
484}
485static void videoEditor_stopPreview(JNIEnv*  pEnv,
486                              jobject  thiz)
487{
488    ManualEditContext* pContext = M4OSA_NULL;
489    bool needToBeLoaded = true;
490    // Get the context.
491    pContext =
492            (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded, pEnv, thiz);
493
494    // Make sure that the context was set.
495    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
496                                             (M4OSA_NULL == pContext),
497                                             "not initialized");
498    pContext->mPreviewController->stopPreview();
499
500    if (pContext->mOverlayFileName != NULL) {
501        M4OSA_free((M4OSA_MemAddr32)pContext->mOverlayFileName);
502        pContext->mOverlayFileName = NULL;
503    }
504}
505
506static void videoEditor_clearSurface(JNIEnv* pEnv,
507                                    jobject thiz,
508                                    jobject surface)
509{
510    bool needToBeLoaded = true;
511    M4OSA_ERR result = M4NO_ERROR;
512    VideoEditor_renderPreviewFrameStr frameStr;
513    const char* pMessage = NULL;
514    // Let the size be QVGA
515    int width = 320;
516    int height = 240;
517    ManualEditContext* pContext = M4OSA_NULL;
518
519    // Get the context.
520    pContext = (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded, pEnv, thiz);
521    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO,
522                                "VIDEO_EDITOR","pContext = 0x%x",pContext);
523
524    // Make sure that the context was set.
525    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
526                                             (M4OSA_NULL == pContext),
527                                             "not initialized");
528
529    // Make sure that the context was set.
530    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
531                                 (M4OSA_NULL == pContext->mPreviewController),
532                                 "not initialized");
533
534    // Validate the surface parameter.
535    videoEditJava_checkAndThrowIllegalArgumentException(&needToBeLoaded, pEnv,
536                                                (NULL == surface),
537                                                "surface is null");
538
539    jclass surfaceClass = pEnv->FindClass("android/view/Surface");
540    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
541                                             (M4OSA_NULL == surfaceClass),
542                                             "not initialized");
543
544    jfieldID surface_native =
545            pEnv->GetFieldID(surfaceClass, ANDROID_VIEW_SURFACE_JNI_ID, "I");
546    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
547                                             (M4OSA_NULL == surface_native),
548                                             "not initialized");
549
550    Surface* const p = (Surface*)pEnv->GetIntField(surface, surface_native);
551    sp<Surface> previewSurface = sp<Surface>(p);
552
553    frameStr.pBuffer = M4OSA_NULL;
554    frameStr.timeMs = 0;
555    frameStr.uiSurfaceWidth = width;
556    frameStr.uiSurfaceHeight = height;
557    frameStr.uiFrameWidth = width;
558    frameStr.uiFrameHeight = height;
559    frameStr.bApplyEffect = M4OSA_FALSE;
560    frameStr.clipBeginCutTime = 0;
561    frameStr.clipEndCutTime = 0;
562
563    result = pContext->mPreviewController->clearSurface(previewSurface,
564                                                              &frameStr);
565    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
566            (M4NO_ERROR != result), result);
567
568  }
569
570static int videoEditor_renderPreviewFrame(JNIEnv* pEnv,
571                                    jobject thiz,
572                                    jobject    mSurface,
573                                    jlong fromMs,
574                                    jint surfaceWidth,
575                                    jint surfaceHeight )
576{
577    bool needToBeLoaded = true;
578    M4OSA_ERR result = M4NO_ERROR;
579    M4OSA_UInt32 timeMs = (M4OSA_UInt32)fromMs;
580    M4OSA_UInt32 i=0,tnTimeMs = 0, framesizeYuv =0;
581    M4VIFI_UInt8 *pixelArray = M4OSA_NULL;
582    M4OSA_UInt32    iCurrentClipIndex = 0, uiNumberOfClipsInStoryBoard =0,
583                    uiClipDuration = 0, uiTotalClipDuration = 0,
584                    iIncrementedDuration = 0;
585    VideoEditor_renderPreviewFrameStr frameStr;
586    M4OSA_Context tnContext = M4OSA_NULL;
587    const char* pMessage = NULL;
588    M4VIFI_ImagePlane *yuvPlane = NULL;
589    VideoEditorCurretEditInfo  currEditInfo;
590
591    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO,
592        "VIDEO_EDITOR", "surfaceWidth = %d",surfaceWidth);
593    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO,
594        "VIDEO_EDITOR", "surfaceHeight = %d",surfaceHeight);
595    ManualEditContext* pContext = M4OSA_NULL;
596    // Get the context.
597    pContext =
598            (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded, pEnv, thiz);
599    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO,
600                                "VIDEO_EDITOR","pContext = 0x%x",pContext);
601
602    // Make sure that the context was set.
603    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
604                                             (M4OSA_NULL == pContext),
605                                             "not initialized");
606
607    // Make sure that the context was set.
608    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
609                                 (M4OSA_NULL == pContext->mPreviewController),
610                                 "not initialized");
611
612    // Validate the mSurface parameter.
613    videoEditJava_checkAndThrowIllegalArgumentException(&needToBeLoaded, pEnv,
614                                                (NULL == mSurface),
615                                                "mSurface is null");
616    jclass surfaceClass = pEnv->FindClass("android/view/Surface");
617    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
618                                             (M4OSA_NULL == surfaceClass),
619                                             "not initialized");
620
621    jfieldID surface_native =
622            pEnv->GetFieldID(surfaceClass, ANDROID_VIEW_SURFACE_JNI_ID, "I");
623    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
624                                             (M4OSA_NULL == surface_native),
625                                             "not initialized");
626
627    Surface* const p = (Surface*)pEnv->GetIntField(mSurface, surface_native);
628    sp<Surface> previewSurface = sp<Surface>(p);
629
630    /* Determine the total number of clips, total duration*/
631    uiNumberOfClipsInStoryBoard = pContext->pEditSettings->uiClipNumber;
632
633    for (i = 0; i < uiNumberOfClipsInStoryBoard; i++) {
634        uiClipDuration = pContext->pEditSettings->pClipList[i]->uiEndCutTime -
635            pContext->pEditSettings->pClipList[i]->uiBeginCutTime;
636        uiTotalClipDuration += uiClipDuration;
637    }
638
639    /* determine the clip whose thumbnail needs to be rendered*/
640    if (timeMs == 0) {
641        iCurrentClipIndex = 0;
642        i=0;
643    } else {
644        VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
645            "videoEditor_renderPreviewFrame() timeMs=%d", timeMs);
646
647        if (timeMs > uiTotalClipDuration) {
648            VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
649                "videoEditor_renderPreviewFrame() timeMs > uiTotalClipDuration");
650            pMessage = videoEditJava_getErrorName(M4ERR_PARAMETER);
651            jniThrowException(pEnv, "java/lang/IllegalArgumentException", pMessage);
652            return -1;
653        }
654
655        for (i = 0; i < uiNumberOfClipsInStoryBoard; i++) {
656            if (timeMs < (iIncrementedDuration +
657                          (pContext->pEditSettings->pClipList[i]->uiEndCutTime -
658                           pContext->pEditSettings->pClipList[i]->uiBeginCutTime)))
659            {
660                iCurrentClipIndex = i;
661                VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
662                    "videoEditor_renderPreviewFrame() iCurrentClipIndex=%d for timeMs=%d",
663                    iCurrentClipIndex, timeMs);
664                break;
665            }
666            else {
667                iIncrementedDuration = iIncrementedDuration +
668                    (pContext->pEditSettings->pClipList[i]->uiEndCutTime -
669                    pContext->pEditSettings->pClipList[i]->uiBeginCutTime);
670            }
671        }
672    }
673    /* If timestamp is beyond story board duration, return*/
674    if (i >= uiNumberOfClipsInStoryBoard) {
675        if (timeMs == iIncrementedDuration) {
676            iCurrentClipIndex = i-1;
677        } else {
678           return -1;
679        }
680    }
681
682    /*+ Handle the image files here */
683      if (pContext->pEditSettings->pClipList[iCurrentClipIndex]->FileType ==
684          /*M4VIDEOEDITING_kFileType_JPG*/ M4VIDEOEDITING_kFileType_ARGB8888 ) {
685          VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", " iCurrentClipIndex %d ", iCurrentClipIndex);
686          VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
687                "  Height = %d",
688                pContext->pEditSettings->pClipList[iCurrentClipIndex]->ClipProperties.uiVideoHeight);
689
690          VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
691                "  Width = %d",
692                pContext->pEditSettings->pClipList[iCurrentClipIndex]->ClipProperties.uiVideoWidth);
693
694          LvGetImageThumbNail((const char *)pContext->pEditSettings->\
695          pClipList[iCurrentClipIndex]->pFile,
696            pContext->pEditSettings->pClipList[iCurrentClipIndex]->ClipProperties.uiVideoHeight,
697            pContext->pEditSettings->pClipList[iCurrentClipIndex]->ClipProperties.uiVideoWidth,
698            (M4OSA_Void **)&frameStr.pBuffer);
699    } else {
700        /* Handle 3gp/mp4 Clips here */
701        /* get thumbnail*/
702        result = ThumbnailOpen(&tnContext,
703            (const M4OSA_Char*)pContext->pEditSettings->\
704            pClipList[iCurrentClipIndex]->pFile, M4OSA_TRUE);
705        if (result != M4NO_ERROR || tnContext  == M4OSA_NULL) {
706            return -1;
707        }
708
709        /* timeMs is relative to storyboard; in this api it shud be relative to this clip */
710        if ((i >= uiNumberOfClipsInStoryBoard) &&
711            (timeMs == iIncrementedDuration)) {
712            tnTimeMs = pContext->pEditSettings->\
713            pClipList[iCurrentClipIndex]->uiEndCutTime;
714        } else {
715            tnTimeMs = pContext->pEditSettings->\
716            pClipList[iCurrentClipIndex]->uiBeginCutTime
717            + (timeMs - iIncrementedDuration);
718        }
719
720        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
721            "video width = %d",pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
722            ClipProperties.uiVideoWidth);
723        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
724            "video height = %d",pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
725            ClipProperties.uiVideoHeight);
726        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
727            "current clip index = %d",iCurrentClipIndex);
728
729        M4OSA_UInt32 width = pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
730            ClipProperties.uiVideoWidth;
731        M4OSA_UInt32 height = pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
732            ClipProperties.uiVideoHeight;
733
734        framesizeYuv = width * height * 1.5;
735
736        pixelArray = (M4VIFI_UInt8 *)M4OSA_malloc(framesizeYuv, M4VS,
737            (M4OSA_Char*)"videoEditor pixelArray");
738        if (pixelArray == M4OSA_NULL) {
739            VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
740                "videoEditor_renderPreviewFrame() malloc error");
741            ThumbnailClose(tnContext);
742            pMessage = videoEditJava_getErrorName(M4ERR_ALLOC);
743            jniThrowException(pEnv, "java/lang/RuntimeException", pMessage);
744            return -1;
745        }
746
747        result = ThumbnailGetPixels16(tnContext, (M4OSA_Int16 *)pixelArray,
748            pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
749            ClipProperties.uiVideoWidth,
750            pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
751            ClipProperties.uiVideoHeight,
752            &tnTimeMs);
753        if (result != M4NO_ERROR) {
754            M4OSA_free((M4OSA_MemAddr32)pixelArray);
755            ThumbnailClose(tnContext);
756            return -1;
757        }
758
759        ThumbnailClose(tnContext);
760        tnContext = M4OSA_NULL;
761
762#ifdef DUMPTOFILE
763        {
764            M4OSA_Context fileContext;
765            M4OSA_Char* fileName = (M4OSA_Char*)"/mnt/sdcard/FirstRGB565.raw";
766            M4OSA_fileExtraDelete((const M4OSA_Char *)fileName);
767            M4OSA_fileWriteOpen(&fileContext, (M4OSA_Void*) fileName,\
768                M4OSA_kFileWrite|M4OSA_kFileCreate);
769            M4OSA_fileWriteData(fileContext, (M4OSA_MemAddr8) pixelArray,
770                framesizeYuv);
771            M4OSA_fileWriteClose(fileContext);
772        }
773#endif
774
775        /**
776        * Allocate output YUV planes
777        */
778        yuvPlane = (M4VIFI_ImagePlane*)M4OSA_malloc(3*sizeof(M4VIFI_ImagePlane), M4VS,
779            (M4OSA_Char*)"videoEditor_renderPreviewFrame Output plane YUV");
780        if (yuvPlane == M4OSA_NULL) {
781            VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
782                "videoEditor_renderPreviewFrame() malloc error for yuv plane");
783            M4OSA_free((M4OSA_MemAddr32)pixelArray);
784            pMessage = videoEditJava_getErrorName(M4ERR_ALLOC);
785            jniThrowException(pEnv, "java/lang/RuntimeException", pMessage);
786            return -1;
787        }
788
789        yuvPlane[0].u_width = width;
790        yuvPlane[0].u_height = height;
791        yuvPlane[0].u_topleft = 0;
792        yuvPlane[0].u_stride = width;
793        yuvPlane[0].pac_data = (M4VIFI_UInt8*)pixelArray;
794
795        yuvPlane[1].u_width = width>>1;
796        yuvPlane[1].u_height = height>>1;
797        yuvPlane[1].u_topleft = 0;
798        yuvPlane[1].u_stride = width>>1;
799        yuvPlane[1].pac_data = yuvPlane[0].pac_data
800                    + yuvPlane[0].u_width * yuvPlane[0].u_height;
801        yuvPlane[2].u_width = (width)>>1;
802        yuvPlane[2].u_height = (height)>>1;
803        yuvPlane[2].u_topleft = 0;
804        yuvPlane[2].u_stride = (width)>>1;
805        yuvPlane[2].pac_data = yuvPlane[1].pac_data
806                    + yuvPlane[1].u_width * yuvPlane[1].u_height;
807
808#ifdef DUMPTOFILE
809        {
810            M4OSA_Context fileContext;
811            M4OSA_Char* fileName = (M4OSA_Char*)"/mnt/sdcard/ConvertedYuv.yuv";
812            M4OSA_fileExtraDelete((const M4OSA_Char *)fileName);
813            M4OSA_fileWriteOpen(&fileContext, (M4OSA_Void*) fileName,\
814                M4OSA_kFileWrite|M4OSA_kFileCreate);
815            M4OSA_fileWriteData(fileContext,
816                (M4OSA_MemAddr8) yuvPlane[0].pac_data, framesizeYuv);
817            M4OSA_fileWriteClose(fileContext);
818        }
819#endif
820
821        /* Fill up the render structure*/
822        frameStr.pBuffer = (M4OSA_Void*)yuvPlane[0].pac_data;
823    }
824
825    frameStr.timeMs = timeMs;    /* timestamp on storyboard*/
826    frameStr.uiSurfaceWidth =
827        pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
828        ClipProperties.uiVideoWidth;
829    frameStr.uiSurfaceHeight =
830        pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
831        ClipProperties.uiVideoHeight;
832    frameStr.uiFrameWidth =
833        pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
834        ClipProperties.uiVideoWidth;
835    frameStr.uiFrameHeight =
836        pContext->pEditSettings->pClipList[iCurrentClipIndex]->\
837        ClipProperties.uiVideoHeight;
838    if (pContext->pEditSettings->nbEffects > 0) {
839        frameStr.bApplyEffect = M4OSA_TRUE;
840    } else {
841        frameStr.bApplyEffect = M4OSA_FALSE;
842    }
843    frameStr.clipBeginCutTime = iIncrementedDuration;
844    frameStr.clipEndCutTime =
845        iIncrementedDuration +
846        (pContext->pEditSettings->pClipList[iCurrentClipIndex]->uiEndCutTime -\
847        pContext->pEditSettings->pClipList[iCurrentClipIndex]->uiBeginCutTime);
848
849    pContext->mPreviewController->setPreviewFrameRenderingMode(
850        pContext->pEditSettings->\
851        pClipList[iCurrentClipIndex]->xVSS.MediaRendering,
852        pContext->pEditSettings->xVSS.outputVideoSize);
853    result = pContext->mPreviewController->renderPreviewFrame(previewSurface,
854                                                              &frameStr, &currEditInfo);
855
856    if (currEditInfo.overlaySettingsIndex != -1) {
857        char tmpOverlayFilename[100];
858        char *extPos = NULL;
859        jstring tmpOverlayString;
860        int tmpRenderingMode = 0;
861
862        strncpy (tmpOverlayFilename,
863                (const char*)pContext->pEditSettings->Effects[currEditInfo.overlaySettingsIndex].xVSS.pFramingFilePath, 99);
864
865        //Change the name to png file
866        extPos = strstr(tmpOverlayFilename, ".rgb");
867        if (extPos != NULL) {
868            *extPos = '\0';
869        } else {
870            LOGE("ERROR the overlay file is incorrect");
871        }
872
873        strcat(tmpOverlayFilename, ".png");
874
875        tmpRenderingMode = pContext->pEditSettings->pClipList[iCurrentClipIndex]->xVSS.MediaRendering;
876        tmpOverlayString = pEnv->NewStringUTF(tmpOverlayFilename);
877        pEnv->CallVoidMethod(pContext->engine,
878            pContext->previewFrameEditInfoId,
879            tmpOverlayString, tmpRenderingMode);
880
881    }
882
883    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
884            (M4NO_ERROR != result), result);
885
886    if (pContext->pEditSettings->pClipList[iCurrentClipIndex]->FileType ==\
887         /*M4VIDEOEDITING_kFileType_JPG */ M4VIDEOEDITING_kFileType_ARGB8888) {
888            M4OSA_free((M4OSA_MemAddr32)frameStr.pBuffer);
889    } else {
890        M4OSA_free((M4OSA_MemAddr32)yuvPlane[0].pac_data);
891        M4OSA_free((M4OSA_MemAddr32)yuvPlane);
892    }
893    return tnTimeMs;
894}
895
896static int videoEditor_renderMediaItemPreviewFrame(JNIEnv* pEnv,
897                                                    jobject thiz,
898                                                    jobject mSurface,
899                                                    jstring filePath,
900                                                    jint    frameWidth,
901                                                    jint    frameHeight,
902                                                    jint    surfaceWidth,
903                                                    jint    surfaceHeight,
904                                                    jlong   fromMs)
905{
906    bool needToBeLoaded = true;
907    M4OSA_ERR result = M4NO_ERROR;
908    M4OSA_UInt32 timeMs = (M4OSA_UInt32)fromMs;
909    M4OSA_UInt32 framesizeYuv =0;
910    M4VIFI_UInt8 *pixelArray = M4OSA_NULL;
911    VideoEditor_renderPreviewFrameStr frameStr;
912    M4OSA_Context tnContext = M4OSA_NULL;
913    const char* pMessage = NULL;
914    M4VIFI_ImagePlane yuvPlane[3], rgbPlane;
915
916    ManualEditContext* pContext = M4OSA_NULL;
917    // Get the context.
918    pContext =
919            (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded,
920                                                      pEnv, thiz);
921
922    // Make sure that the context was set.
923    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
924                                             (M4OSA_NULL == pContext),
925                                             "not initialized");
926
927    // Make sure that the context was set.
928    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
929                                 (M4OSA_NULL == pContext->mPreviewController),
930                                 "not initialized");
931
932    // Validate the mSurface parameter.
933    videoEditJava_checkAndThrowIllegalArgumentException(&needToBeLoaded, pEnv,
934                                                (NULL == mSurface),
935                                                "mSurface is null");
936    jclass surfaceClass = pEnv->FindClass("android/view/Surface");
937    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
938                                             (M4OSA_NULL == surfaceClass),
939                                             "not initialized");
940
941    jfieldID surface_native =
942            pEnv->GetFieldID(surfaceClass, ANDROID_VIEW_SURFACE_JNI_ID, "I");
943    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
944                                             (M4OSA_NULL == surface_native),
945                                             "not initialized");
946
947    Surface* const p = (Surface*)pEnv->GetIntField(mSurface, surface_native);
948    sp<Surface> previewSurface = sp<Surface>(p);
949
950
951    const char *pString = pEnv->GetStringUTFChars(filePath, NULL);
952    if (pString == M4OSA_NULL) {
953        if (pEnv != NULL) {
954            jniThrowException(pEnv, "java/lang/RuntimeException", "Input string null");
955        }
956    }
957    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
958        "videoEditor_renderMediaItemPreviewFrame() timeMs=%d", timeMs);
959    /* get thumbnail*/
960    result = ThumbnailOpen(&tnContext,(const M4OSA_Char*)pString, M4OSA_TRUE);
961    if (result != M4NO_ERROR || tnContext  == M4OSA_NULL) {
962        return timeMs;
963    }
964
965    framesizeYuv = ((frameWidth)*(frameHeight)*1.5);
966
967    pixelArray = (M4VIFI_UInt8 *)M4OSA_malloc(framesizeYuv, M4VS,\
968        (M4OSA_Char*)"videoEditor pixelArray");
969    if (pixelArray == M4OSA_NULL) {
970        VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
971            "videoEditor_renderPreviewFrame() malloc error");
972        ThumbnailClose(tnContext);
973        pMessage = videoEditJava_getErrorName(M4ERR_ALLOC);
974        jniThrowException(pEnv, "java/lang/RuntimeException", pMessage);
975        return timeMs;
976    }
977
978    result = ThumbnailGetPixels16(tnContext, (M4OSA_Int16 *)pixelArray,
979                                                frameWidth,
980                                                frameHeight, &timeMs);
981    if (result != M4NO_ERROR) {
982        M4OSA_free((M4OSA_MemAddr32)pixelArray);
983        ThumbnailClose(tnContext);
984        return fromMs;
985    }
986
987#ifdef DUMPTOFILESYSTEM
988    {
989        M4OSA_Context fileContext;
990        M4OSA_Char* fileName = (M4OSA_Char*)"/mnt/sdcard/FirstRGB565.rgb";
991        M4OSA_fileWriteOpen(&fileContext, (M4OSA_Void*) fileName,\
992            M4OSA_kFileWrite|M4OSA_kFileCreate);
993        M4OSA_fileWriteData(fileContext, (M4OSA_MemAddr8) pixelArray,
994                            framesizeRgb);
995        M4OSA_fileWriteClose(fileContext);
996    }
997#endif
998
999    yuvPlane[0].pac_data = (M4VIFI_UInt8*)pixelArray;
1000    yuvPlane[0].u_height = frameHeight;
1001    yuvPlane[0].u_width = frameWidth;
1002    yuvPlane[0].u_stride = yuvPlane[0].u_width;
1003    yuvPlane[0].u_topleft = 0;
1004
1005    yuvPlane[1].u_height = frameHeight/2;
1006    yuvPlane[1].u_width = frameWidth/2;
1007    yuvPlane[1].u_stride = yuvPlane[1].u_width;
1008    yuvPlane[1].u_topleft = 0;
1009    yuvPlane[1].pac_data = yuvPlane[0].pac_data
1010                + yuvPlane[0].u_width*yuvPlane[0].u_height;
1011
1012    yuvPlane[2].u_height = frameHeight/2;
1013    yuvPlane[2].u_width = frameWidth/2;
1014    yuvPlane[2].u_stride = yuvPlane[2].u_width;
1015    yuvPlane[2].u_topleft = 0;
1016    yuvPlane[2].pac_data = yuvPlane[0].pac_data
1017        + yuvPlane[0].u_width*yuvPlane[0].u_height + \
1018        (yuvPlane[0].u_width/2)*(yuvPlane[0].u_height/2);
1019#ifdef DUMPTOFILESYSTEM
1020    {
1021        M4OSA_Context fileContext;
1022        M4OSA_Char* fileName = (M4OSA_Char*)"/mnt/sdcard/ConvertedYuv.yuv";
1023        M4OSA_fileWriteOpen(&fileContext, (M4OSA_Void*) fileName,\
1024            M4OSA_kFileWrite|M4OSA_kFileCreate);
1025        M4OSA_fileWriteData(fileContext, (M4OSA_MemAddr8) yuvPlane[0].pac_data,
1026                            framesizeYuv);
1027        M4OSA_fileWriteClose(fileContext);
1028    }
1029#endif
1030
1031    /* Fill up the render structure*/
1032    frameStr.pBuffer = (M4OSA_Void*)yuvPlane[0].pac_data;
1033    frameStr.timeMs = timeMs;    /* timestamp on storyboard*/
1034    frameStr.uiSurfaceWidth = frameWidth;
1035    frameStr.uiSurfaceHeight = frameHeight;
1036    frameStr.uiFrameWidth = frameWidth;
1037    frameStr.uiFrameHeight = frameHeight;
1038    frameStr.bApplyEffect = M4OSA_FALSE;
1039    // clip begin cuttime and end cuttime set to 0
1040    // as its only required when effect needs to be applied while rendering
1041    frameStr.clipBeginCutTime = 0;
1042    frameStr.clipEndCutTime = 0;
1043
1044    /*  pContext->mPreviewController->setPreviewFrameRenderingMode(M4xVSS_kBlackBorders,
1045    (M4VIDEOEDITING_VideoFrameSize)(M4VIDEOEDITING_kHD960+1));*/
1046    result
1047    = pContext->mPreviewController->renderPreviewFrame(previewSurface,&frameStr, NULL);
1048    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1049                                                (M4NO_ERROR != result), result);
1050
1051    /* free the pixelArray and yuvPlane[0].pac_data */
1052    M4OSA_free((M4OSA_MemAddr32)yuvPlane[0].pac_data);
1053
1054    ThumbnailClose(tnContext);
1055
1056    return timeMs;
1057}
1058
1059int videoEditor_generateAudioRawFile(   JNIEnv*     pEnv,
1060                                        jobject     thiz,
1061                                        jstring     infilePath,
1062                                        jstring     pcmfilePath)
1063{
1064    M4OSA_ERR result = M4NO_ERROR;
1065    bool               loaded   = true;
1066    ManualEditContext* pContext = M4OSA_NULL;
1067
1068
1069
1070    const char *pInputFile = pEnv->GetStringUTFChars(infilePath, NULL);
1071    if (pInputFile == M4OSA_NULL) {
1072        if (pEnv != NULL) {
1073            jniThrowException(pEnv, "java/lang/RuntimeException", "Input string null");
1074        }
1075    }
1076
1077    const char *pStringOutPCMFilePath = pEnv->GetStringUTFChars(pcmfilePath, NULL);
1078    if (pStringOutPCMFilePath == M4OSA_NULL) {
1079        if (pEnv != NULL) {
1080            jniThrowException(pEnv, "java/lang/RuntimeException", "Input string null");
1081        }
1082    }
1083
1084    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO,
1085        "VIDEO_EDITOR", "videoEditor_generateAudioRawFile infilePath %s",
1086        pInputFile);
1087    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO,
1088        "VIDEO_EDITOR", "videoEditor_generateAudioRawFile pcmfilePath %s",
1089        pStringOutPCMFilePath);
1090    // Get the context.
1091    pContext = (ManualEditContext*)videoEditClasses_getContext(&loaded, pEnv, thiz);
1092
1093    result = videoEditor_generateAudio( pEnv, pContext, (M4OSA_Char*)pInputFile,
1094        (M4OSA_Char*)pStringOutPCMFilePath);
1095
1096    return result;
1097}
1098
1099M4OSA_ERR videoEditor_generateAudio(JNIEnv* pEnv,ManualEditContext* pContext,
1100                                    M4OSA_Char* infilePath,
1101                                    M4OSA_Char* pcmfilePath )
1102{
1103    bool                            needToBeLoaded = true;
1104    M4OSA_ERR                       result = M4NO_ERROR;
1105    M4MCS_Context                   mcsContext = M4OSA_NULL;
1106    M4OSA_Char*                     pInputFile = M4OSA_NULL;
1107    M4OSA_Char*                     pOutputFile = M4OSA_NULL;
1108    M4OSA_Char*                     pTempPath = M4OSA_NULL;
1109    M4MCS_OutputParams*             pOutputParams = M4OSA_NULL;
1110    M4MCS_EncodingParams*           pEncodingParams = M4OSA_NULL;
1111    M4OSA_Int32                     pInputFileType = 0;
1112    M4OSA_UInt8                     threadProgress = 0;
1113    M4OSA_Char*                     pTemp3gpFilePath = M4OSA_NULL;
1114
1115    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_generateAudio()");
1116
1117    videoEditJava_checkAndThrowIllegalArgumentException(&needToBeLoaded, pEnv,
1118        (NULL == pContext),
1119        "ManualEditContext is null");
1120
1121    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4MCS_init()");
1122
1123    pOutputParams = (M4MCS_OutputParams *)M4OSA_malloc(
1124        sizeof(M4MCS_OutputParams),0x00,
1125        (M4OSA_Char *)"M4MCS_OutputParams");
1126    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1127        (M4OSA_NULL == pOutputParams),
1128        "not initialized");
1129    if (needToBeLoaded == false) {
1130        return M4ERR_ALLOC;
1131    }
1132
1133    pEncodingParams = (M4MCS_EncodingParams *)M4OSA_malloc(
1134        sizeof(M4MCS_EncodingParams),0x00,
1135        (M4OSA_Char *)"M4MCS_EncodingParams");
1136    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1137        (M4OSA_NULL == pEncodingParams),
1138        "not initialized");
1139    if (needToBeLoaded == false) {
1140        M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1141        pEncodingParams = M4OSA_NULL;
1142        return M4ERR_ALLOC;
1143    }
1144
1145    // Initialize the MCS library.
1146    result = M4MCS_init(&mcsContext, pContext->initParams.pFileReadPtr,
1147        pContext->initParams.pFileWritePtr);
1148    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,\
1149        (M4NO_ERROR != result), result);
1150    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1151        (M4OSA_NULL == mcsContext),
1152        "not initialized");
1153     if(needToBeLoaded == false) {
1154         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1155         pOutputParams = M4OSA_NULL;
1156         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1157         pEncodingParams = M4OSA_NULL;
1158         return result;
1159     }
1160
1161    // generate the path for temp 3gp output file
1162    pTemp3gpFilePath = (M4OSA_Char*) M4OSA_malloc (
1163        (M4OSA_chrLength((M4OSA_Char*)pContext->initParams.pTempPath)
1164        + M4OSA_chrLength ((M4OSA_Char*)TEMP_MCS_OUT_FILE_PATH)) + 1 /* for null termination */ , 0x0,
1165        (M4OSA_Char*) "Malloc for temp 3gp file");
1166    if ( pTemp3gpFilePath != M4OSA_NULL )
1167    {
1168        M4OSA_memset(pTemp3gpFilePath  ,
1169            M4OSA_chrLength((M4OSA_Char*)pContext->initParams.pTempPath)
1170            + M4OSA_chrLength((M4OSA_Char*)TEMP_MCS_OUT_FILE_PATH) + 1, 0);
1171        M4OSA_chrNCat ( (M4OSA_Char*)pTemp3gpFilePath,
1172            (M4OSA_Char*)pContext->initParams.pTempPath  ,
1173            M4OSA_chrLength ((M4OSA_Char*)pContext->initParams.pTempPath));
1174        M4OSA_chrNCat ( pTemp3gpFilePath , (M4OSA_Char*)TEMP_MCS_OUT_FILE_PATH,
1175            M4OSA_chrLength ((M4OSA_Char*)TEMP_MCS_OUT_FILE_PATH));
1176    }
1177    else {
1178         M4MCS_abort(mcsContext);
1179         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1180         pOutputParams = M4OSA_NULL;
1181         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1182         pEncodingParams = M4OSA_NULL;
1183         return M4ERR_ALLOC;
1184    }
1185
1186    pInputFile = (M4OSA_Char *) infilePath; //pContext->mAudioSettings->pFile;
1187    //Delete this file later
1188    pOutputFile = (M4OSA_Char *) pTemp3gpFilePath;
1189    // Temp folder path for VSS use = ProjectPath
1190    pTempPath = (M4OSA_Char *) pContext->initParams.pTempPath;
1191    pInputFileType = (M4VIDEOEDITING_FileType)pContext->mAudioSettings->fileType;
1192
1193    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "TEMP_MCS_OUT_FILE_PATH len %d",
1194        M4OSA_chrLength ((M4OSA_Char*)TEMP_MCS_OUT_FILE_PATH));
1195    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "pTemp3gpFilePath %s",
1196        pOutputFile);
1197
1198    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4MCS_open()");
1199
1200    result = M4MCS_open(mcsContext, pInputFile,
1201        (M4VIDEOEDITING_FileType)pInputFileType,
1202        pOutputFile, pTempPath);
1203    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1204        (M4NO_ERROR != result), result);
1205    if(needToBeLoaded == false) {
1206         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
1207         pTemp3gpFilePath = M4OSA_NULL;
1208         M4MCS_abort(mcsContext);
1209         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1210         pOutputParams = M4OSA_NULL;
1211         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1212         pEncodingParams = M4OSA_NULL;
1213         return result;
1214    }
1215
1216    pOutputParams->OutputFileType
1217        = (M4VIDEOEDITING_FileType)M4VIDEOEDITING_kFileType_3GPP;
1218    // Set the video format.
1219    pOutputParams->OutputVideoFormat =
1220        (M4VIDEOEDITING_VideoFormat)M4VIDEOEDITING_kNoneVideo;//M4VIDEOEDITING_kNoneVideo;
1221    // Set the frame size.
1222    pOutputParams->OutputVideoFrameSize
1223        = (M4VIDEOEDITING_VideoFrameSize)M4VIDEOEDITING_kQCIF;
1224    // Set the frame rate.
1225    pOutputParams->OutputVideoFrameRate
1226        = (M4VIDEOEDITING_VideoFramerate)M4VIDEOEDITING_k5_FPS;
1227
1228    // Set the audio format.
1229    pOutputParams->OutputAudioFormat
1230        = (M4VIDEOEDITING_AudioFormat)M4VIDEOEDITING_kAAC;
1231    // Set the audio sampling frequency.
1232    pOutputParams->OutputAudioSamplingFrequency =
1233        (M4VIDEOEDITING_AudioSamplingFrequency)M4VIDEOEDITING_k32000_ASF;
1234    // Set the audio mono.
1235    pOutputParams->bAudioMono = false;
1236    // Set the pcm file; null for now.
1237    pOutputParams->pOutputPCMfile = (M4OSA_Char *)pcmfilePath;
1238    //(M4OSA_Char *)"/sdcard/Output/AudioPcm.pcm";
1239    // Set the audio sampling frequency.
1240    pOutputParams->MediaRendering = (M4MCS_MediaRendering)M4MCS_kCropping;
1241    // new params after integrating MCS 2.0
1242    // Set the number of audio effects; 0 for now.
1243    pOutputParams->nbEffects = 0;
1244    // Set the audio effect; null for now.
1245    pOutputParams->pEffects = NULL;
1246    // Set the audio effect; null for now.
1247    pOutputParams->bDiscardExif = M4OSA_FALSE;
1248    // Set the audio effect; null for now.
1249    pOutputParams->bAdjustOrientation = M4OSA_FALSE;
1250
1251    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4MCS_setOutputParams()");
1252    result = M4MCS_setOutputParams(mcsContext, pOutputParams);
1253    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1254                                        (M4NO_ERROR != result), result);
1255    if (needToBeLoaded == false) {
1256         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
1257         pTemp3gpFilePath = M4OSA_NULL;
1258         M4MCS_abort(mcsContext);
1259         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1260         pOutputParams = M4OSA_NULL;
1261         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1262         pEncodingParams = M4OSA_NULL;
1263        return result;
1264    }
1265    // Set the video bitrate.
1266    pEncodingParams->OutputVideoBitrate =
1267    (M4VIDEOEDITING_Bitrate)M4VIDEOEDITING_kUndefinedBitrate;
1268    // Set the audio bitrate.
1269    pEncodingParams->OutputAudioBitrate
1270        = (M4VIDEOEDITING_Bitrate)M4VIDEOEDITING_k128_KBPS;
1271    // Set the end cut time in milliseconds.
1272    pEncodingParams->BeginCutTime = 0;
1273    // Set the end cut time in milliseconds.
1274    pEncodingParams->EndCutTime = 0;
1275    // Set the output file size in bytes.
1276    pEncodingParams->OutputFileSize = 0;
1277    // Set video time scale.
1278    pEncodingParams->OutputVideoTimescale = 0;
1279
1280    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
1281                            "M4MCS_setEncodingParams()");
1282    result = M4MCS_setEncodingParams(mcsContext, pEncodingParams);
1283    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1284        (M4NO_ERROR != result), result);
1285    if (needToBeLoaded == false) {
1286         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
1287         pTemp3gpFilePath = M4OSA_NULL;
1288         M4MCS_abort(mcsContext);
1289         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1290         pOutputParams = M4OSA_NULL;
1291         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1292         pEncodingParams = M4OSA_NULL;
1293         return result;
1294    }
1295
1296    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
1297                            "M4MCS_checkParamsAndStart()");
1298    result = M4MCS_checkParamsAndStart(mcsContext);
1299    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1300        (M4NO_ERROR != result), result);
1301    if (needToBeLoaded == false) {
1302         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
1303         pTemp3gpFilePath = M4OSA_NULL;
1304         M4MCS_abort(mcsContext);
1305         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1306         pOutputParams = M4OSA_NULL;
1307         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1308         pEncodingParams = M4OSA_NULL;
1309        return result;
1310    }
1311
1312    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4MCS_step()");
1313
1314    /*+ PROGRESS CB */
1315    M4OSA_UInt8 curProgress = 0;
1316    int         lastProgress = 0;
1317
1318    LOGV("LVME_generateAudio Current progress is =%d", curProgress);
1319    pEnv->CallVoidMethod(pContext->engine,
1320            pContext->onProgressUpdateMethodId, 1/*task status*/,
1321            curProgress/*progress*/);
1322    do {
1323        result = M4MCS_step(mcsContext, &curProgress);
1324
1325        if (result != M4NO_ERROR) {
1326            LOGV("LVME_generateAudio M4MCS_step returned 0x%x",result);
1327
1328            if (result == M4MCS_WAR_TRANSCODING_DONE) {
1329                LOGV("LVME_generateAudio MCS process ended");
1330
1331                // Send a progress notification.
1332                curProgress = 100;
1333                pEnv->CallVoidMethod(pContext->engine,
1334                    pContext->onProgressUpdateMethodId, 1/*task status*/,
1335                    curProgress);
1336                LOGV("LVME_generateAudio Current progress is =%d", curProgress);
1337            }
1338        } else {
1339            // Send a progress notification if needed
1340            if (curProgress != lastProgress) {
1341                lastProgress = curProgress;
1342                pEnv->CallVoidMethod(pContext->engine,
1343                    pContext->onProgressUpdateMethodId, 0/*task status*/,
1344                    curProgress/*progress*/);
1345                LOGV("LVME_generateAudio Current progress is =%d",curProgress);
1346            }
1347        }
1348    } while (result == M4NO_ERROR);
1349    /*- PROGRESS CB */
1350
1351    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1352        (M4MCS_WAR_TRANSCODING_DONE != result), result);
1353    if (needToBeLoaded == false) {
1354         M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
1355         pTemp3gpFilePath = M4OSA_NULL;
1356         M4MCS_abort(mcsContext);
1357         M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1358         pOutputParams = M4OSA_NULL;
1359         M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1360         pEncodingParams = M4OSA_NULL;
1361        return result;
1362    }
1363
1364    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4MCS_abort()");
1365    result = M4MCS_abort(mcsContext);
1366    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1367        (M4NO_ERROR != result), result);
1368
1369    //pContext->mAudioSettings->pFile = pOutputParams->pOutputPCMfile;
1370    M4OSA_fileExtraDelete((const M4OSA_Char *) pTemp3gpFilePath);
1371    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_generateAudio() EXIT ");
1372
1373    if (pTemp3gpFilePath != M4OSA_NULL) {
1374        M4OSA_free((M4OSA_MemAddr32)pTemp3gpFilePath);
1375    }
1376    if (pOutputParams != M4OSA_NULL) {
1377       M4OSA_free((M4OSA_MemAddr32)pOutputParams);
1378    }
1379    if(pEncodingParams != M4OSA_NULL) {
1380       M4OSA_free((M4OSA_MemAddr32)pEncodingParams);
1381    }
1382    return result;
1383}
1384
1385static int removeAlphafromRGB8888 (
1386                        M4OSA_Char* pFramingFilePath,
1387                        M4xVSS_FramingStruct *pFramingCtx)
1388{
1389    M4OSA_UInt32 frameSize_argb = (pFramingCtx->width * pFramingCtx->height * 4); // aRGB data
1390    M4OSA_Context lImageFileFp  = M4OSA_NULL;
1391    M4OSA_ERR err = M4NO_ERROR;
1392
1393    LOGV("removeAlphafromRGB8888: width %d", pFramingCtx->width);
1394
1395    M4OSA_UInt8 *pTmpData = (M4OSA_UInt8*) M4OSA_malloc(frameSize_argb, M4VS, (M4OSA_Char*)"Image argb data");
1396    if (pTmpData == M4OSA_NULL) {
1397        LOGE("Failed to allocate memory for Image clip");
1398        return M4ERR_ALLOC;
1399    }
1400
1401       /** Read the argb data from the passed file. */
1402    M4OSA_ERR lerr = M4OSA_fileReadOpen(&lImageFileFp, (M4OSA_Void *) pFramingFilePath, M4OSA_kFileRead);
1403
1404
1405    if ((lerr != M4NO_ERROR) || (lImageFileFp == M4OSA_NULL))
1406    {
1407        LOGE("removeAlphafromRGB8888: Can not open the file ");
1408        M4OSA_free((M4OSA_MemAddr32)pTmpData);
1409        return M4ERR_FILE_NOT_FOUND;
1410    }
1411
1412
1413    lerr = M4OSA_fileReadData(lImageFileFp, (M4OSA_MemAddr8)pTmpData, &frameSize_argb);
1414    if (lerr != M4NO_ERROR)
1415    {
1416        LOGE("removeAlphafromRGB8888: can not read the data ");
1417        M4OSA_fileReadClose(lImageFileFp);
1418        M4OSA_free((M4OSA_MemAddr32)pTmpData);
1419        return lerr;
1420    }
1421    M4OSA_fileReadClose(lImageFileFp);
1422
1423    M4OSA_UInt32 frameSize = (pFramingCtx->width * pFramingCtx->height * 3); //Size of RGB 888 data.
1424
1425    pFramingCtx->FramingRgb = (M4VIFI_ImagePlane*)M4OSA_malloc(
1426             sizeof(M4VIFI_ImagePlane), M4VS, (M4OSA_Char*)"Image clip RGB888 data");
1427    pFramingCtx->FramingRgb->pac_data = (M4VIFI_UInt8*)M4OSA_malloc(
1428             frameSize, M4VS, (M4OSA_Char*)"Image clip RGB888 data");
1429
1430    if (pFramingCtx->FramingRgb == M4OSA_NULL)
1431    {
1432        LOGE("Failed to allocate memory for Image clip");
1433        M4OSA_free((M4OSA_MemAddr32)pTmpData);
1434        return M4ERR_ALLOC;
1435    }
1436
1437    /** Remove the alpha channel */
1438    for (size_t i = 0, j = 0; i < frameSize_argb; i++) {
1439        if ((i % 4) == 0) continue;
1440        pFramingCtx->FramingRgb->pac_data[j] = pTmpData[i];
1441        j++;
1442    }
1443    M4OSA_free((M4OSA_MemAddr32)pTmpData);
1444    return M4NO_ERROR;
1445}
1446
1447static void
1448videoEditor_populateSettings(
1449                JNIEnv*                 pEnv,
1450                jobject                 thiz,
1451                jobject                 settings,
1452                jobject                 object,
1453                jobject                 audioSettingObject)
1454{
1455    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
1456            "videoEditor_populateSettings()");
1457
1458    bool                needToBeLoaded  = true;
1459    ManualEditContext*  pContext        = M4OSA_NULL;
1460    M4OSA_ERR           result          = M4NO_ERROR;
1461    jstring             str             = M4OSA_NULL;
1462    jobjectArray        propertiesClipsArray           = M4OSA_NULL;
1463    jobject             properties      = M4OSA_NULL;
1464    jint*               bitmapArray     =  M4OSA_NULL;
1465    jobjectArray        effectSettingsArray = M4OSA_NULL;
1466    jobject             effectSettings  = M4OSA_NULL;
1467    jintArray           pixelArray      = M4OSA_NULL;
1468    int width = 0;
1469    int height = 0;
1470    int nbOverlays = 0;
1471    int i,j = 0;
1472    int *pOverlayIndex = M4OSA_NULL;
1473
1474    // Add a code marker (the condition must always be true).
1475    ADD_CODE_MARKER_FUN(NULL != pEnv)
1476
1477    // Validate the settings parameter.
1478    videoEditJava_checkAndThrowIllegalArgumentException(&needToBeLoaded, pEnv,
1479                                                (NULL == settings),
1480                                                "settings is null");
1481    // Get the context.
1482    pContext =
1483            (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded, pEnv, thiz);
1484
1485    // Make sure that the context was set.
1486    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1487                                             (M4OSA_NULL == pContext),
1488                                             "not initialized");
1489    // Make sure that the context was set.
1490    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1491                                 (M4OSA_NULL == pContext->mPreviewController),
1492                                 "not initialized");
1493    jclass mPreviewClipPropClazz = pEnv->FindClass(PREVIEW_PROPERTIES_CLASS_NAME);
1494    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1495                                     (M4OSA_NULL == mPreviewClipPropClazz),
1496                                     "not initialized");
1497
1498    jfieldID fid = pEnv->GetFieldID(mPreviewClipPropClazz,"clipProperties",
1499            "[L"PROPERTIES_CLASS_NAME";"  );
1500    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1501                                     (M4OSA_NULL == fid),
1502                                     "not initialized");
1503
1504    propertiesClipsArray = (jobjectArray)pEnv->GetObjectField(object, fid);
1505    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1506                                     (M4OSA_NULL == propertiesClipsArray),
1507                                     "not initialized");
1508
1509    jclass engineClass = pEnv->FindClass(MANUAL_EDIT_ENGINE_CLASS_NAME);
1510    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1511                                     (M4OSA_NULL == engineClass),
1512                                     "not initialized");
1513
1514    pContext->onPreviewProgressUpdateMethodId = pEnv->GetMethodID(engineClass,
1515            "onPreviewProgressUpdate",     "(IZZLjava/lang/String;I)V");
1516    // Check if the context is valid (required because the context is dereferenced).
1517    if (needToBeLoaded) {
1518        // Make sure that we are in a correct state.
1519        videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1520                             (pContext->state != ManualEditState_INITIALIZED),
1521                             "settings already loaded");
1522        if (needToBeLoaded) {
1523            // Retrieve the edit settings.
1524            if (pContext->pEditSettings != M4OSA_NULL) {
1525                videoEditClasses_freeEditSettings(&pContext->pEditSettings);
1526                pContext->pEditSettings = M4OSA_NULL;
1527            }
1528            videoEditClasses_getEditSettings(&needToBeLoaded, pEnv,
1529                settings, &pContext->pEditSettings,false);
1530        }
1531    }
1532
1533    if (needToBeLoaded == false) {
1534        j = 0;
1535        while (j < pContext->pEditSettings->nbEffects)
1536        {
1537            if (pContext->pEditSettings->Effects[j].xVSS.pFramingFilePath != M4OSA_NULL) {
1538                if (pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer != M4OSA_NULL) {
1539                    M4OSA_free((M4OSA_MemAddr32)pContext->pEditSettings->\
1540                    Effects[j].xVSS.pFramingBuffer);
1541                    pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer = M4OSA_NULL;
1542                }
1543            }
1544          j++;
1545        }
1546        return;
1547    }
1548
1549    M4OSA_TRACE1_0("videoEditorC_getEditSettings done");
1550
1551    pContext->previewFrameEditInfoId = pEnv->GetMethodID(engineClass,
1552        "previewFrameEditInfo", "(Ljava/lang/String;I)V");
1553
1554    if ( pContext->pEditSettings != NULL )
1555    {
1556        // Check if the edit settings could be retrieved.
1557        jclass mEditClazz = pEnv->FindClass(EDIT_SETTINGS_CLASS_NAME);
1558        if(mEditClazz == M4OSA_NULL)
1559        {
1560            M4OSA_TRACE1_0("cannot find object field for mEditClazz");
1561            goto videoEditor_populateSettings_cleanup;
1562        }
1563        jclass mEffectsClazz = pEnv->FindClass(EFFECT_SETTINGS_CLASS_NAME);
1564        if(mEffectsClazz == M4OSA_NULL)
1565        {
1566            M4OSA_TRACE1_0("cannot find object field for mEffectsClazz");
1567            goto videoEditor_populateSettings_cleanup;
1568        }
1569        fid = pEnv->GetFieldID(mEditClazz,"effectSettingsArray", "[L"EFFECT_SETTINGS_CLASS_NAME";"  );
1570        if(fid == M4OSA_NULL)
1571        {
1572            M4OSA_TRACE1_0("cannot find field for effectSettingsArray Array");
1573            goto videoEditor_populateSettings_cleanup;
1574        }
1575        effectSettingsArray = (jobjectArray)pEnv->GetObjectField(settings, fid);
1576        if(effectSettingsArray == M4OSA_NULL)
1577        {
1578            M4OSA_TRACE1_0("cannot find object field for effectSettingsArray");
1579            goto videoEditor_populateSettings_cleanup;
1580        }
1581
1582        //int overlayIndex[pContext->pEditSettings->nbEffects];
1583        if (pContext->pEditSettings->nbEffects > 0)
1584        {
1585            pOverlayIndex
1586            = (int*) M4OSA_malloc(pContext->pEditSettings->nbEffects * sizeof(int), 0,
1587                (M4OSA_Char*)"pOverlayIndex");
1588            if (pOverlayIndex == M4OSA_NULL) {
1589                videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1590                    M4OSA_TRUE, M4ERR_ALLOC);
1591                goto videoEditor_populateSettings_cleanup;
1592            }
1593        }
1594
1595        i = 0;
1596        j = 0;
1597        M4OSA_TRACE1_1("no of effects = %d",pContext->pEditSettings->nbEffects);
1598        while (j < pContext->pEditSettings->nbEffects)
1599        {
1600            if (pContext->pEditSettings->Effects[j].xVSS.pFramingFilePath != M4OSA_NULL)
1601            {
1602                pOverlayIndex[nbOverlays] = j;
1603
1604                M4xVSS_FramingStruct *aFramingCtx = M4OSA_NULL;
1605                aFramingCtx
1606                = (M4xVSS_FramingStruct*)M4OSA_malloc(sizeof(M4xVSS_FramingStruct), M4VS,
1607                  (M4OSA_Char*)"M4xVSS_internalDecodeGIF: Context of the framing effect");
1608                if (aFramingCtx == M4OSA_NULL)
1609                {
1610                    M4OSA_TRACE1_0("Allocation error in videoEditor_populateSettings");
1611                    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1612                        M4OSA_TRUE, M4ERR_ALLOC);
1613                    goto videoEditor_populateSettings_cleanup;
1614                }
1615
1616                aFramingCtx->pCurrent = M4OSA_NULL; /* Only used by the first element of the chain */
1617                aFramingCtx->previousClipTime = -1;
1618                aFramingCtx->FramingYuv = M4OSA_NULL;
1619                aFramingCtx->FramingRgb = M4OSA_NULL;
1620                aFramingCtx->topleft_x
1621                    = pContext->pEditSettings->Effects[j].xVSS.topleft_x;
1622                aFramingCtx->topleft_y
1623                    = pContext->pEditSettings->Effects[j].xVSS.topleft_y;
1624
1625
1626                 VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "OF u_width %d",
1627                                        pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_width);
1628                 VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "OF u_height() %d",
1629                                        pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_height);
1630                 VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "OF rgbType() %d",
1631                                        pContext->pEditSettings->Effects[j].xVSS.rgbType);
1632
1633                 aFramingCtx->width = pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_width;
1634                 aFramingCtx->height = pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_height;
1635
1636                result = M4xVSS_internalConvertARGB888toYUV420_FrammingEffect(pContext->engineContext,
1637                    &(pContext->pEditSettings->Effects[j]),aFramingCtx,
1638                pContext->pEditSettings->Effects[j].xVSS.framingScaledSize);
1639                videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1640                                            (M4NO_ERROR != result), result);
1641                if (needToBeLoaded == false) {
1642                    M4OSA_TRACE1_1("M4xVSS_internalConvertARGB888toYUV420_FrammingEffect returned 0x%x", result);
1643                    if (aFramingCtx != M4OSA_NULL) {
1644                        M4OSA_free((M4OSA_MemAddr32)aFramingCtx);
1645                        aFramingCtx = M4OSA_NULL;
1646                    }
1647                    goto videoEditor_populateSettings_cleanup;
1648                }
1649
1650                //framing buffers are resized to fit the output video resolution.
1651                pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_width =
1652                    aFramingCtx->FramingRgb->u_width;
1653                pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_height =
1654                    aFramingCtx->FramingRgb->u_height;
1655
1656                VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "A framing Context aFramingCtx->width = %d",
1657                    aFramingCtx->FramingRgb->u_width);
1658
1659                VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "A framing Context aFramingCtx->height = %d",
1660                    aFramingCtx->FramingRgb->u_height);
1661
1662
1663                width = pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_width;
1664                height = pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_height;
1665
1666                //RGB 565
1667                pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_stride = width * 2;
1668
1669                //for RGB565
1670                pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->u_topleft = 0;
1671                pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->pac_data =
1672                            (M4VIFI_UInt8 *)M4OSA_malloc(width*height*2,
1673                            0x00,(M4OSA_Char *)"pac_data buffer");
1674
1675                if (pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer->pac_data == M4OSA_NULL) {
1676                    M4OSA_TRACE1_0("Failed to allocate memory for framing buffer");
1677                    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1678                                            M4OSA_TRUE, M4ERR_ALLOC);
1679                    goto videoEditor_populateSettings_cleanup;
1680                }
1681
1682                M4OSA_memcpy((M4OSA_Int8 *)&pContext->pEditSettings->\
1683                    Effects[j].xVSS.pFramingBuffer->\
1684                    pac_data[0],(M4OSA_Int8 *)&aFramingCtx->FramingRgb->pac_data[0],(width*height*2));
1685
1686                //As of now rgb type is 565
1687                pContext->pEditSettings->Effects[j].xVSS.rgbType =
1688                    (M4VSS3GPP_RGBType) M4VSS3GPP_kRGB565;
1689
1690                if (aFramingCtx->FramingYuv != M4OSA_NULL )
1691                {
1692                    if (aFramingCtx->FramingYuv->pac_data != M4OSA_NULL) {
1693                        M4OSA_free((M4OSA_MemAddr32)aFramingCtx->FramingYuv->pac_data);
1694                        aFramingCtx->FramingYuv->pac_data = M4OSA_NULL;
1695                    }
1696                }
1697                if (aFramingCtx->FramingYuv != M4OSA_NULL) {
1698                    M4OSA_free((M4OSA_MemAddr32)aFramingCtx->FramingYuv);
1699                    aFramingCtx->FramingYuv = M4OSA_NULL;
1700                }
1701                if (aFramingCtx->FramingRgb->pac_data != M4OSA_NULL) {
1702                    M4OSA_free((M4OSA_MemAddr32)aFramingCtx->FramingRgb->pac_data);
1703                    aFramingCtx->FramingRgb->pac_data = M4OSA_NULL;
1704                }
1705                if (aFramingCtx->FramingRgb != M4OSA_NULL) {
1706                    M4OSA_free((M4OSA_MemAddr32)aFramingCtx->FramingRgb);
1707                    aFramingCtx->FramingRgb = M4OSA_NULL;
1708                }
1709                if (aFramingCtx != M4OSA_NULL) {
1710                    M4OSA_free((M4OSA_MemAddr32)aFramingCtx);
1711                    aFramingCtx = M4OSA_NULL;
1712                }
1713                nbOverlays++;
1714            }
1715            j++;
1716        }
1717
1718        // Check if the edit settings could be retrieved.
1719        M4OSA_TRACE1_1("total clips are = %d",pContext->pEditSettings->uiClipNumber);
1720        for (i = 0; i < pContext->pEditSettings->uiClipNumber; i++) {
1721            M4OSA_TRACE1_1("clip no = %d",i);
1722            properties = pEnv->GetObjectArrayElement(propertiesClipsArray, i);
1723            videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1724                (M4OSA_NULL == properties),
1725                "not initialized");
1726            if (needToBeLoaded) {
1727                getClipSetting(pEnv,properties, pContext->pEditSettings->pClipList[i]);
1728            } else {
1729                goto videoEditor_populateSettings_cleanup;
1730            }
1731        }
1732
1733        if (needToBeLoaded) {
1734            // Log the edit settings.
1735            VIDEOEDIT_LOG_EDIT_SETTINGS(pContext->pEditSettings);
1736        }
1737    }
1738
1739    if (audioSettingObject != M4OSA_NULL) {
1740        jclass audioSettingClazz = pEnv->FindClass(AUDIO_SETTINGS_CLASS_NAME);
1741        videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1742                                         (M4OSA_NULL == audioSettingClazz),
1743                                         "not initialized");
1744
1745        videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1746                                     (M4OSA_NULL == pContext->mAudioSettings),
1747                                     "not initialized");
1748
1749        if (needToBeLoaded == false) {
1750            goto videoEditor_populateSettings_cleanup;
1751        }
1752
1753        fid = pEnv->GetFieldID(audioSettingClazz,"bRemoveOriginal","Z");
1754        pContext->mAudioSettings->bRemoveOriginal = pEnv->GetIntField(audioSettingObject,fid);
1755        M4OSA_TRACE1_1("bRemoveOriginal = %d",pContext->mAudioSettings->bRemoveOriginal);
1756
1757        fid = pEnv->GetFieldID(audioSettingClazz,"channels","I");
1758        pContext->mAudioSettings->uiNbChannels = pEnv->GetIntField(audioSettingObject,fid);
1759        M4OSA_TRACE1_1("uiNbChannels = %d",pContext->mAudioSettings->uiNbChannels);
1760
1761        fid = pEnv->GetFieldID(audioSettingClazz,"Fs","I");
1762        pContext->mAudioSettings->uiSamplingFrequency = pEnv->GetIntField(audioSettingObject,fid);
1763        M4OSA_TRACE1_1("uiSamplingFrequency = %d",pContext->mAudioSettings->uiSamplingFrequency);
1764
1765        fid = pEnv->GetFieldID(audioSettingClazz,"ExtendedFs","I");
1766        pContext->mAudioSettings->uiExtendedSamplingFrequency =
1767         pEnv->GetIntField(audioSettingObject,fid);
1768        M4OSA_TRACE1_1("uiExtendedSamplingFrequency = %d",
1769        pContext->mAudioSettings->uiExtendedSamplingFrequency);
1770
1771        fid = pEnv->GetFieldID(audioSettingClazz,"startMs","J");
1772        pContext->mAudioSettings->uiAddCts
1773            = pEnv->GetIntField(audioSettingObject,fid);
1774        M4OSA_TRACE1_1("uiAddCts = %d",pContext->mAudioSettings->uiAddCts);
1775
1776        fid = pEnv->GetFieldID(audioSettingClazz,"volume","I");
1777        pContext->mAudioSettings->uiAddVolume
1778            = pEnv->GetIntField(audioSettingObject,fid);
1779        M4OSA_TRACE1_1("uiAddVolume = %d",pContext->mAudioSettings->uiAddVolume);
1780
1781        fid = pEnv->GetFieldID(audioSettingClazz,"loop","Z");
1782        pContext->mAudioSettings->bLoop
1783            = pEnv->GetIntField(audioSettingObject,fid);
1784        M4OSA_TRACE1_1("bLoop = %d",pContext->mAudioSettings->bLoop);
1785
1786        fid = pEnv->GetFieldID(audioSettingClazz,"beginCutTime","J");
1787        pContext->mAudioSettings->beginCutMs
1788            = pEnv->GetIntField(audioSettingObject,fid);
1789        M4OSA_TRACE1_1("begin cut time = %d",pContext->mAudioSettings->beginCutMs);
1790
1791        fid = pEnv->GetFieldID(audioSettingClazz,"endCutTime","J");
1792        pContext->mAudioSettings->endCutMs
1793            = pEnv->GetIntField(audioSettingObject,fid);
1794        M4OSA_TRACE1_1("end cut time = %d",pContext->mAudioSettings->endCutMs);
1795
1796        fid = pEnv->GetFieldID(audioSettingClazz,"fileType","I");
1797        pContext->mAudioSettings->fileType
1798            = pEnv->GetIntField(audioSettingObject,fid);
1799        M4OSA_TRACE1_1("fileType = %d",pContext->mAudioSettings->fileType);
1800        fid = pEnv->GetFieldID(audioSettingClazz,"pFile","Ljava/lang/String;");
1801        str = (jstring)pEnv->GetObjectField(audioSettingObject,fid);
1802        pContext->mAudioSettings->pFile
1803                = (M4OSA_Char*)pEnv->GetStringUTFChars(str, M4OSA_NULL);
1804        M4OSA_TRACE1_1("file name = %s",pContext->mAudioSettings->pFile);
1805        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEOEDITOR", "regenerateAudio() file name = %s",\
1806        pContext->mAudioSettings->pFile);
1807
1808        fid = pEnv->GetFieldID(audioSettingClazz,"pcmFilePath","Ljava/lang/String;");
1809        str = (jstring)pEnv->GetObjectField(audioSettingObject,fid);
1810
1811        pContext->mAudioSettings->pPCMFilePath =
1812        (M4OSA_Char*)pEnv->GetStringUTFChars(str, M4OSA_NULL);
1813
1814        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEOEDITOR", "pPCMFilePath -- %s ",\
1815        pContext->mAudioSettings->pPCMFilePath);
1816
1817        fid = pEnv->GetFieldID(engineClass,"mRegenerateAudio","Z");
1818        bool regenerateAudio = pEnv->GetBooleanField(thiz,fid);
1819
1820        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEOEDITOR", "regenerateAudio -- %d ",\
1821        regenerateAudio);
1822
1823        if (regenerateAudio) {
1824            M4OSA_TRACE1_0("Calling Generate Audio now");
1825            result = videoEditor_generateAudio(pEnv,
1826                        pContext,
1827                        (M4OSA_Char*)pContext->mAudioSettings->pFile,
1828                        (M4OSA_Char*)pContext->mAudioSettings->pPCMFilePath);
1829
1830            videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1831                (M4NO_ERROR != result), result);
1832            if (needToBeLoaded == false) {
1833                goto videoEditor_populateSettings_cleanup;
1834            }
1835
1836            regenerateAudio = false;
1837            pEnv->SetBooleanField(thiz,fid,regenerateAudio);
1838        }
1839
1840        /* Audio mix and duck */
1841        fid = pEnv->GetFieldID(audioSettingClazz,"ducking_threshold","I");
1842        pContext->mAudioSettings->uiInDucking_threshold
1843            = pEnv->GetIntField(audioSettingObject,fid);
1844
1845        M4OSA_TRACE1_1("ducking threshold = %d",
1846            pContext->mAudioSettings->uiInDucking_threshold);
1847
1848        fid = pEnv->GetFieldID(audioSettingClazz,"ducking_lowVolume","I");
1849        pContext->mAudioSettings->uiInDucking_lowVolume
1850            = pEnv->GetIntField(audioSettingObject,fid);
1851
1852        M4OSA_TRACE1_1("ducking lowVolume = %d",
1853            pContext->mAudioSettings->uiInDucking_lowVolume);
1854
1855        fid = pEnv->GetFieldID(audioSettingClazz,"bInDucking_enable","Z");
1856        pContext->mAudioSettings->bInDucking_enable
1857            = pEnv->GetBooleanField(audioSettingObject,fid);
1858        M4OSA_TRACE1_1("ducking lowVolume = %d",
1859            pContext->mAudioSettings->bInDucking_enable);
1860
1861    } else {
1862        if (pContext->mAudioSettings != M4OSA_NULL) {
1863            pContext->mAudioSettings->pFile = M4OSA_NULL;
1864            pContext->mAudioSettings->bRemoveOriginal = 0;
1865            pContext->mAudioSettings->uiNbChannels = 0;
1866            pContext->mAudioSettings->uiSamplingFrequency = 0;
1867            pContext->mAudioSettings->uiExtendedSamplingFrequency = 0;
1868            pContext->mAudioSettings->uiAddCts = 0;
1869            pContext->mAudioSettings->uiAddVolume = 0;
1870            pContext->mAudioSettings->beginCutMs = 0;
1871            pContext->mAudioSettings->endCutMs = 0;
1872               pContext->mAudioSettings->fileType = 0;
1873            pContext->mAudioSettings->bLoop = 0;
1874            pContext->mAudioSettings->uiInDucking_lowVolume  = 0;
1875            pContext->mAudioSettings->bInDucking_enable  = 0;
1876            pContext->mAudioSettings->uiBTChannelCount  = 0;
1877            pContext->mAudioSettings->uiInDucking_threshold = 0;
1878
1879            fid = pEnv->GetFieldID(engineClass,"mRegenerateAudio","Z");
1880            bool regenerateAudio = pEnv->GetBooleanField(thiz,fid);
1881            if (!regenerateAudio) {
1882                regenerateAudio = true;
1883                pEnv->SetBooleanField(thiz,fid,regenerateAudio);
1884            }
1885        }
1886    }
1887
1888    if (pContext->pEditSettings != NULL)
1889    {
1890        result = pContext->mPreviewController->loadEditSettings(pContext->pEditSettings,
1891            pContext->mAudioSettings);
1892        videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1893                                            (M4NO_ERROR != result), result);
1894
1895        if (needToBeLoaded) {
1896            pContext->mPreviewController->setJniCallback((void*)pContext,
1897            (jni_progress_callback_fct)jniPreviewProgressCallback);
1898        }
1899    }
1900
1901videoEditor_populateSettings_cleanup:
1902        j = 0;
1903        while (j < nbOverlays)
1904        {
1905            if (pContext->pEditSettings->Effects[pOverlayIndex[j]].xVSS.pFramingBuffer->pac_data != \
1906                M4OSA_NULL) {
1907                M4OSA_free((M4OSA_MemAddr32)pContext->pEditSettings->\
1908                Effects[pOverlayIndex[j]].xVSS.pFramingBuffer->pac_data);
1909                pContext->pEditSettings->\
1910                Effects[pOverlayIndex[j]].xVSS.pFramingBuffer->pac_data = M4OSA_NULL;
1911            }
1912            j++;
1913        }
1914
1915        j = 0;
1916        while (j < pContext->pEditSettings->nbEffects)
1917        {
1918            if (pContext->pEditSettings->Effects[j].xVSS.pFramingFilePath != M4OSA_NULL) {
1919                if (pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer != M4OSA_NULL) {
1920                    M4OSA_free((M4OSA_MemAddr32)pContext->pEditSettings->\
1921                    Effects[j].xVSS.pFramingBuffer);
1922                    pContext->pEditSettings->Effects[j].xVSS.pFramingBuffer = M4OSA_NULL;
1923                }
1924            }
1925          j++;
1926        }
1927
1928    if (pOverlayIndex != M4OSA_NULL)
1929    {
1930        M4OSA_free((M4OSA_MemAddr32)pOverlayIndex);
1931        pOverlayIndex = M4OSA_NULL;
1932    }
1933    return;
1934}
1935
1936static void
1937videoEditor_startPreview(
1938                JNIEnv*                 pEnv,
1939                jobject                 thiz,
1940                jobject                 mSurface,
1941                jlong                   fromMs,
1942                jlong                   toMs,
1943                jint                    callbackInterval,
1944                jboolean                loop)
1945{
1946    bool needToBeLoaded = true;
1947    M4OSA_ERR result = M4NO_ERROR;
1948    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_startPreview()");
1949
1950    ManualEditContext* pContext = M4OSA_NULL;
1951    // Get the context.
1952    pContext = (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded, pEnv, thiz);
1953
1954    // Make sure that the context was set.
1955    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1956                                             (M4OSA_NULL == pContext),
1957                                             "not initialized");
1958
1959    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1960                                     (M4OSA_NULL == pContext->mAudioSettings),
1961                                     "not initialized");
1962    // Make sure that the context was set.
1963    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1964                                 (M4OSA_NULL == pContext->mPreviewController),
1965                                 "not initialized");
1966
1967    // Validate the mSurface parameter.
1968    videoEditJava_checkAndThrowIllegalArgumentException(&needToBeLoaded, pEnv,
1969                                                (NULL == mSurface),
1970                                                "mSurface is null");
1971
1972    jclass surfaceClass = pEnv->FindClass("android/view/Surface");
1973    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1974                                             (M4OSA_NULL == surfaceClass),
1975                                             "not initialized");
1976    //jfieldID surface_native = pEnv->GetFieldID(surfaceClass, "mSurface", "I");
1977    jfieldID surface_native
1978        = pEnv->GetFieldID(surfaceClass, ANDROID_VIEW_SURFACE_JNI_ID, "I");
1979
1980    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
1981                                             (M4OSA_NULL == surface_native),
1982                                             "not initialized");
1983
1984    Surface* const p = (Surface*)pEnv->GetIntField(mSurface, surface_native);
1985
1986    sp<Surface> previewSurface = sp<Surface>(p);
1987
1988    result =  pContext->mPreviewController->setSurface(previewSurface);
1989    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv,
1990        (M4NO_ERROR != result), result);
1991    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "fromMs=%ld, toMs=%ld",
1992        (M4OSA_UInt32)fromMs, (M4OSA_Int32)toMs);
1993
1994    result = pContext->mPreviewController->startPreview((M4OSA_UInt32)fromMs,
1995                                                (M4OSA_Int32)toMs,
1996                                                (M4OSA_UInt16)callbackInterval,
1997                                                (M4OSA_Bool)loop);
1998    videoEditJava_checkAndThrowRuntimeException(&needToBeLoaded, pEnv, (M4NO_ERROR != result), result);
1999}
2000
2001
2002static jobject
2003videoEditor_getProperties(
2004                JNIEnv*                             pEnv,
2005                jobject                             thiz,
2006                jstring                             file)
2007{
2008    jobject object = M4OSA_NULL;
2009    object = videoEditProp_getProperties(pEnv,thiz,file);
2010
2011    return object;
2012
2013}
2014static int videoEditor_getPixels(
2015                    JNIEnv*                     env,
2016                    jobject                     thiz,
2017                    jstring                     path,
2018                    jintArray                   pixelArray,
2019                    M4OSA_UInt32                width,
2020                    M4OSA_UInt32                height,
2021                    M4OSA_UInt32                timeMS)
2022{
2023
2024    M4OSA_ERR       err = M4NO_ERROR;
2025    M4OSA_Context   mContext = M4OSA_NULL;
2026    jint*           m_dst32 = M4OSA_NULL;
2027
2028
2029    // Add a text marker (the condition must always be true).
2030    ADD_TEXT_MARKER_FUN(NULL != env)
2031
2032    const char *pString = env->GetStringUTFChars(path, NULL);
2033    if (pString == M4OSA_NULL) {
2034        if (env != NULL) {
2035            jniThrowException(env, "java/lang/RuntimeException", "Input string null");
2036        }
2037        return M4ERR_ALLOC;
2038    }
2039
2040    err = ThumbnailOpen(&mContext,(const M4OSA_Char*)pString, M4OSA_FALSE);
2041    if (err != M4NO_ERROR || mContext == M4OSA_NULL) {
2042        if (pString != NULL) {
2043            env->ReleaseStringUTFChars(path, pString);
2044        }
2045        if (env != NULL) {
2046            jniThrowException(env, "java/lang/RuntimeException", "ThumbnailOpen failed");
2047        }
2048    }
2049
2050    m_dst32 = env->GetIntArrayElements(pixelArray, NULL);
2051
2052    err = ThumbnailGetPixels32(mContext, (M4OSA_Int32 *)m_dst32, width,height,&timeMS);
2053    if (err != M4NO_ERROR ) {
2054        if (env != NULL) {
2055            jniThrowException(env, "java/lang/RuntimeException",\
2056                "ThumbnailGetPixels32 failed");
2057        }
2058    }
2059    env->ReleaseIntArrayElements(pixelArray, m_dst32, 0);
2060
2061    ThumbnailClose(mContext);
2062    if (pString != NULL) {
2063        env->ReleaseStringUTFChars(path, pString);
2064    }
2065
2066    return timeMS;
2067}
2068
2069static int videoEditor_getPixelsList(
2070                JNIEnv*                     env,
2071                jobject                     thiz,
2072                jstring                     path,
2073                jintArray                 pixelArray,
2074                M4OSA_UInt32             width,
2075                M4OSA_UInt32             height,
2076                M4OSA_UInt32             deltatimeMS,
2077                M4OSA_UInt32            noOfThumbnails,
2078                M4OSA_UInt32                startTime,
2079                M4OSA_UInt32                endTime)
2080{
2081
2082    M4OSA_ERR           err;
2083    M4OSA_Context       mContext = M4OSA_NULL;
2084    jint*               m_dst32;
2085    M4OSA_UInt32        timeMS = startTime;
2086    int                 arrayOffset = 0;
2087
2088
2089
2090    // Add a text marker (the condition must always be true).
2091    ADD_TEXT_MARKER_FUN(NULL != env)
2092
2093    const char *pString = env->GetStringUTFChars(path, NULL);
2094    if (pString == M4OSA_NULL) {
2095        if (env != NULL) {
2096            jniThrowException(env, "java/lang/RuntimeException", "Input string null");
2097        }
2098        return M4ERR_ALLOC;
2099    }
2100
2101    err = ThumbnailOpen(&mContext,(const M4OSA_Char*)pString, M4OSA_FALSE);
2102    if (err != M4NO_ERROR || mContext == M4OSA_NULL) {
2103        if (env != NULL) {
2104            jniThrowException(env, "java/lang/RuntimeException", "ThumbnailOpen failed");
2105        }
2106        if (pString != NULL) {
2107            env->ReleaseStringUTFChars(path, pString);
2108        }
2109        return err;
2110    }
2111
2112    m_dst32 = env->GetIntArrayElements(pixelArray, NULL);
2113
2114    do {
2115        err = ThumbnailGetPixels32(mContext, ((M4OSA_Int32 *)m_dst32 + arrayOffset),
2116            width,height,&timeMS);
2117        if (err != M4NO_ERROR ) {
2118            if (env != NULL) {
2119                jniThrowException(env, "java/lang/RuntimeException",\
2120                    "ThumbnailGetPixels32 failed");
2121            }
2122            return err;
2123        }
2124        timeMS += deltatimeMS;
2125        arrayOffset += (width * height * 4);
2126        noOfThumbnails--;
2127    } while(noOfThumbnails > 0);
2128
2129    env->ReleaseIntArrayElements(pixelArray, m_dst32, 0);
2130
2131    ThumbnailClose(mContext);
2132    if (pString != NULL) {
2133        env->ReleaseStringUTFChars(path, pString);
2134    }
2135
2136    return err;
2137
2138}
2139
2140static M4OSA_ERR
2141videoEditor_toUTF8Fct(
2142                M4OSA_Void*                         pBufferIn,
2143                M4OSA_UInt8*                        pBufferOut,
2144                M4OSA_UInt32*                       bufferOutSize)
2145{
2146    M4OSA_ERR    result = M4NO_ERROR;
2147    M4OSA_UInt32 length = 0;
2148
2149    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_toUTF8Fct()");
2150
2151    // Determine the length of the input buffer.
2152    if (M4OSA_NULL != pBufferIn)
2153    {
2154        length = M4OSA_chrLength((M4OSA_Char *)pBufferIn);
2155    }
2156
2157    // Check if the output buffer is large enough to hold the input buffer.
2158    if ((*bufferOutSize) > length)
2159    {
2160        // Check if the input buffer is not M4OSA_NULL.
2161        if (M4OSA_NULL != pBufferIn)
2162        {
2163            // Copy the temp path, ignore the result.
2164            M4OSA_chrNCopy((M4OSA_Char *)pBufferOut, (M4OSA_Char *)pBufferIn, length);
2165        }
2166        else
2167        {
2168            // Set the output buffer to an empty string.
2169            (*(M4OSA_Char *)pBufferOut) = 0;
2170        }
2171    }
2172    else
2173    {
2174        // The buffer is too small.
2175        result = M4xVSSWAR_BUFFER_OUT_TOO_SMALL;
2176    }
2177
2178    // Return the buffer output size.
2179    (*bufferOutSize) = length + 1;
2180
2181    // Return the result.
2182    return(result);
2183}
2184
2185static M4OSA_ERR
2186videoEditor_fromUTF8Fct(
2187                M4OSA_UInt8*                        pBufferIn,
2188                M4OSA_Void*                         pBufferOut,
2189                M4OSA_UInt32*                       bufferOutSize)
2190{
2191    M4OSA_ERR    result = M4NO_ERROR;
2192    M4OSA_UInt32 length = 0;
2193
2194    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_fromUTF8Fct()");
2195
2196    // Determine the length of the input buffer.
2197    if (M4OSA_NULL != pBufferIn)
2198    {
2199        length = M4OSA_chrLength((M4OSA_Char *)pBufferIn);
2200    }
2201
2202    // Check if the output buffer is large enough to hold the input buffer.
2203    if ((*bufferOutSize) > length)
2204    {
2205        // Check if the input buffer is not M4OSA_NULL.
2206        if (M4OSA_NULL != pBufferIn)
2207        {
2208            // Copy the temp path, ignore the result.
2209            M4OSA_chrNCopy((M4OSA_Char *)pBufferOut, (M4OSA_Char *)pBufferIn, length);
2210        }
2211        else
2212        {
2213            // Set the output buffer to an empty string.
2214            (*(M4OSA_Char *)pBufferOut) = 0;
2215        }
2216    }
2217    else
2218    {
2219        // The buffer is too small.
2220        result = M4xVSSWAR_BUFFER_OUT_TOO_SMALL;
2221    }
2222
2223    // Return the buffer output size.
2224    (*bufferOutSize) = length + 1;
2225
2226    // Return the result.
2227    return(result);
2228}
2229
2230static M4OSA_ERR
2231videoEditor_getTextRgbBufferFct(
2232                M4OSA_Void*                         pRenderingData,
2233                M4OSA_Void*                         pTextBuffer,
2234                M4OSA_UInt32                        textBufferSize,
2235                M4VIFI_ImagePlane**                 pOutputPlane)
2236{
2237    M4OSA_ERR result = M4NO_ERROR;
2238
2239    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_getTextRgbBufferFct()");
2240
2241    // Return the result.
2242    return(result);
2243}
2244
2245static void
2246videoEditor_callOnProgressUpdate(
2247                ManualEditContext*                  pContext,
2248                int                                 task,
2249                int                                 progress)
2250{
2251    JNIEnv* pEnv = NULL;
2252
2253
2254    // Attach the current thread.
2255    pContext->pVM->AttachCurrentThread(&pEnv, NULL);
2256
2257
2258    // Call the on completion callback.
2259    pEnv->CallVoidMethod(pContext->engine, pContext->onProgressUpdateMethodId,
2260     videoEditJava_getEngineCToJava(task), progress);
2261
2262
2263    // Detach the current thread.
2264    pContext->pVM->DetachCurrentThread();
2265}
2266
2267static void
2268videoEditor_freeContext(
2269                JNIEnv*                             pEnv,
2270                ManualEditContext**                 ppContext)
2271{
2272    ManualEditContext* pContext = M4OSA_NULL;
2273
2274    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_freeContext");
2275
2276    // Set the context pointer.
2277    pContext = (*ppContext);
2278
2279    // Check if the context was set.
2280    if (M4OSA_NULL != pContext)
2281    {
2282        // Check if a global reference to the engine object was set.
2283        if (NULL != pContext->engine)
2284        {
2285            // Free the global reference.
2286            pEnv->DeleteGlobalRef(pContext->engine);
2287            pContext->engine = NULL;
2288        }
2289
2290        // Check if the temp path was set.
2291        if (M4OSA_NULL != pContext->initParams.pTempPath)
2292        {
2293            // Free the memory allocated for the temp path.
2294            videoEditOsal_free(pContext->initParams.pTempPath);
2295            pContext->initParams.pTempPath = M4OSA_NULL;
2296        }
2297
2298        // Check if the file writer was set.
2299        if (M4OSA_NULL != pContext->initParams.pFileWritePtr)
2300        {
2301            // Free the memory allocated for the file writer.
2302            videoEditOsal_free(pContext->initParams.pFileWritePtr);
2303            pContext->initParams.pFileWritePtr = M4OSA_NULL;
2304        }
2305
2306        // Check if the file reader was set.
2307        if (M4OSA_NULL != pContext->initParams.pFileReadPtr)
2308        {
2309            // Free the memory allocated for the file reader.
2310            videoEditOsal_free(pContext->initParams.pFileReadPtr);
2311            pContext->initParams.pFileReadPtr = M4OSA_NULL;
2312        }
2313
2314        // Free the memory allocated for the context.
2315        videoEditOsal_free(pContext);
2316        pContext = M4OSA_NULL;
2317
2318        // Reset the context pointer.
2319        (*ppContext) = M4OSA_NULL;
2320    }
2321}
2322
2323static jobject
2324videoEditor_getVersion(
2325                JNIEnv*                             pEnv,
2326                jobject                             thiz)
2327{
2328    bool           isSuccessful          = true;
2329    jobject        version         = NULL;
2330    M4_VersionInfo versionInfo     = {0, 0, 0, 0};
2331    M4OSA_ERR      result          = M4NO_ERROR;
2332
2333    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_getVersion()");
2334
2335    versionInfo.m_structSize = sizeof(versionInfo);
2336    versionInfo.m_major = VIDEOEDITOR_VERSION_MAJOR;
2337    versionInfo.m_minor = VIDEOEDITOR_VERSION_MINOR;
2338    versionInfo.m_revision = VIDEOEDITOR_VERSION_REVISION;
2339
2340    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_getVersion() major %d,\
2341     minor %d, revision %d", versionInfo.m_major, versionInfo.m_minor, versionInfo.m_revision);
2342
2343    // Create a version object.
2344    videoEditClasses_createVersion(&isSuccessful, pEnv, &versionInfo, &version);
2345
2346    // Return the version object.
2347    return(version);
2348}
2349
2350static void
2351videoEditor_init(
2352                JNIEnv*                             pEnv,
2353                jobject                             thiz,
2354                jstring                             tempPath,
2355                jstring                             libraryPath)
2356{
2357    bool                  initialized            = true;
2358    ManualEditContext*    pContext               = M4OSA_NULL;
2359    VideoEditJava_EngineMethodIds methodIds              = {NULL};
2360    M4OSA_Char*           pLibraryPath           = M4OSA_NULL;
2361    M4OSA_Char*           pTextRendererPath      = M4OSA_NULL;
2362    M4OSA_UInt32          textRendererPathLength = 0;
2363    M4OSA_ERR             result                 = M4NO_ERROR;
2364
2365    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_init()");
2366
2367    // Add a text marker (the condition must always be true).
2368    ADD_TEXT_MARKER_FUN(NULL != pEnv)
2369
2370    // Get the context.
2371    pContext = (ManualEditContext*)videoEditClasses_getContext(&initialized, pEnv, thiz);
2372
2373    // Get the engine method ids.
2374    videoEditJava_getEngineMethodIds(&initialized, pEnv, &methodIds);
2375
2376    // Validate the tempPath parameter.
2377    videoEditJava_checkAndThrowIllegalArgumentException(&initialized, pEnv,
2378                                                (NULL == tempPath),
2379                                                "tempPath is null");
2380
2381    // Make sure that the context was not set already.
2382    videoEditJava_checkAndThrowIllegalStateException(&initialized, pEnv,
2383                                             (M4OSA_NULL != pContext),
2384                                             "already initialized");
2385
2386    // Check if the initialization succeeded (required because of dereferencing of psContext,
2387    // and freeing when initialization fails).
2388    if (initialized)
2389    {
2390        // Allocate a new context.
2391        pContext = new ManualEditContext;
2392
2393        // Check if the initialization succeeded (required because of dereferencing of psContext).
2394        //if (initialized)
2395        if (pContext != NULL)
2396        {
2397            // Set the state to not initialized.
2398            pContext->state = ManualEditState_NOT_INITIALIZED;
2399
2400            // Allocate a file read pointer structure.
2401            pContext->initParams.pFileReadPtr =
2402             (M4OSA_FileReadPointer*)videoEditOsal_alloc(&initialized, pEnv,
2403              sizeof(M4OSA_FileReadPointer), "FileReadPointer");
2404
2405            // Allocate a file write pointer structure.
2406            pContext->initParams.pFileWritePtr =
2407             (M4OSA_FileWriterPointer*)videoEditOsal_alloc(&initialized, pEnv,
2408              sizeof(M4OSA_FileWriterPointer), "FileWriterPointer");
2409
2410            // Get the temp path.
2411            M4OSA_Char* tmpString =
2412                (M4OSA_Char *)videoEditJava_getString(&initialized, pEnv, tempPath,
2413                NULL, M4OSA_NULL);
2414            pContext->initParams.pTempPath = (M4OSA_Char *)
2415                 M4OSA_malloc(M4OSA_chrLength(tmpString) + 1, 0x0,
2416                                                 (M4OSA_Char *)"tempPath");
2417            //initialize the first char. so that strcat works.
2418            M4OSA_Char *ptmpChar = (M4OSA_Char*)pContext->initParams.pTempPath;
2419            ptmpChar[0] = 0x00;
2420            M4OSA_chrNCat((M4OSA_Char*)pContext->initParams.pTempPath, tmpString, M4OSA_chrLength(tmpString));
2421            M4OSA_chrNCat((M4OSA_Char*)pContext->initParams.pTempPath, (M4OSA_Char*)"/", 1);
2422            M4OSA_free((M4OSA_MemAddr32)tmpString);
2423            pContext->mIsUpdateOverlay = false;
2424            pContext->mOverlayFileName = NULL;
2425        }
2426
2427        // Check if the initialization succeeded
2428        // (required because of dereferencing of pContext, pFileReadPtr and pFileWritePtr).
2429        if (initialized)
2430        {
2431
2432            // Initialize the OSAL file system function pointers.
2433            videoEditOsal_getFilePointers(pContext->initParams.pFileReadPtr ,
2434                                          pContext->initParams.pFileWritePtr);
2435
2436            // Set the UTF8 conversion functions.
2437            pContext->initParams.pConvToUTF8Fct   = videoEditor_toUTF8Fct;
2438            pContext->initParams.pConvFromUTF8Fct = videoEditor_fromUTF8Fct;
2439
2440            // Set the callback method ids.
2441            pContext->onProgressUpdateMethodId = methodIds.onProgressUpdate;
2442
2443            // Set the virtual machine.
2444            pEnv->GetJavaVM(&(pContext->pVM));
2445
2446            // Create a global reference to the engine object.
2447            pContext->engine = pEnv->NewGlobalRef(thiz);
2448
2449            // Check if the global reference could be created.
2450            videoEditJava_checkAndThrowRuntimeException(&initialized, pEnv,
2451             (NULL == pContext->engine), M4NO_ERROR);
2452        }
2453
2454        // Check if the initialization succeeded (required because of dereferencing of pContext).
2455        if (initialized)
2456        {
2457            // Log the API call.
2458            VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "M4xVSS_Init()");
2459
2460            // Initialize the visual studio library.
2461            result = M4xVSS_Init(&pContext->engineContext, &pContext->initParams);
2462
2463            // Log the result.
2464            VIDEOEDIT_LOG_RESULT(ANDROID_LOG_INFO, "VIDEO_EDITOR",
2465             videoEditOsal_getResultString(result));
2466
2467            // Check if the library could be initialized.
2468            videoEditJava_checkAndThrowRuntimeException(&initialized, pEnv,
2469             (M4NO_ERROR != result), result);
2470        }
2471
2472        if(initialized)
2473        {
2474            pContext->mPreviewController = new VideoEditorPreviewController();
2475            videoEditJava_checkAndThrowIllegalStateException(&initialized, pEnv,
2476                                 (M4OSA_NULL == pContext->mPreviewController),
2477                                 "not initialized");
2478            pContext->mAudioSettings =
2479             (M4xVSS_AudioMixingSettings *)
2480             M4OSA_malloc(sizeof(M4xVSS_AudioMixingSettings),0x0,
2481             (M4OSA_Char *)"mAudioSettings");
2482            videoEditJava_checkAndThrowIllegalStateException(&initialized, pEnv,
2483                                     (M4OSA_NULL == pContext->mAudioSettings),
2484                                     "not initialized");
2485            pContext->mAudioSettings->pFile = M4OSA_NULL;
2486            pContext->mAudioSettings->bRemoveOriginal = 0;
2487            pContext->mAudioSettings->uiNbChannels = 0;
2488            pContext->mAudioSettings->uiSamplingFrequency = 0;
2489            pContext->mAudioSettings->uiExtendedSamplingFrequency = 0;
2490            pContext->mAudioSettings->uiAddCts = 0;
2491            pContext->mAudioSettings->uiAddVolume = 0;
2492            pContext->mAudioSettings->beginCutMs = 0;
2493            pContext->mAudioSettings->endCutMs = 0;
2494            pContext->mAudioSettings->fileType = 0;
2495            pContext->mAudioSettings->bLoop = 0;
2496            pContext->mAudioSettings->uiInDucking_lowVolume  = 0;
2497            pContext->mAudioSettings->bInDucking_enable  = 0;
2498            pContext->mAudioSettings->uiBTChannelCount  = 0;
2499            pContext->mAudioSettings->uiInDucking_threshold = 0;
2500        }
2501        // Check if the library could be initialized.
2502        if (initialized)
2503        {
2504            // Set the state to initialized.
2505            pContext->state = ManualEditState_INITIALIZED;
2506        }
2507
2508        // Set the context.
2509        videoEditClasses_setContext(&initialized, pEnv, thiz, (void* )pContext);
2510        pLibraryPath = M4OSA_NULL;
2511
2512        pContext->pEditSettings = M4OSA_NULL;
2513        // Cleanup if anything went wrong during initialization.
2514        if (!initialized)
2515        {
2516            // Free the context.
2517            videoEditor_freeContext(pEnv, &pContext);
2518        }
2519    }
2520}
2521
2522/*+ PROGRESS CB */
2523static
2524M4OSA_ERR videoEditor_processClip(
2525                            JNIEnv*  pEnv,
2526                            jobject  thiz,
2527                            int      unuseditemID) {
2528
2529    bool               loaded           = true;
2530    ManualEditContext* pContext         = NULL;
2531    M4OSA_UInt8        progress         = 0;
2532    M4OSA_UInt8        progressBase     = 0;
2533    M4OSA_UInt8        lastProgress     = 0;
2534    M4OSA_ERR          result           = M4NO_ERROR;
2535
2536    // Get the context.
2537    pContext = (ManualEditContext*)videoEditClasses_getContext(&loaded, pEnv, thiz);
2538
2539    // Make sure that the context was set.
2540    videoEditJava_checkAndThrowIllegalStateException(&loaded, pEnv,
2541                                             (M4OSA_NULL == pContext),
2542                                             "not initialized");
2543
2544    // We start in Analyzing state
2545    pContext->state = ManualEditState_INITIALIZED;
2546    M4OSA_ERR          completionResult = M4VSS3GPP_WAR_ANALYZING_DONE;
2547    ManualEditState    completionState  = ManualEditState_OPENED;
2548    ManualEditState    errorState       = ManualEditState_ANALYZING_ERROR;
2549
2550    // While analyzing progress goes from 0 to 50
2551    progressBase     = 0;
2552
2553    // Set the text rendering function.
2554    if (M4OSA_NULL != pContext->pTextRendererFunction)
2555    {
2556        // Use the text renderer function in the library.
2557        pContext->pEditSettings->xVSS.pTextRenderingFct = pContext->pTextRendererFunction;
2558    }
2559    else
2560    {
2561        // Use the internal text renderer function.
2562        pContext->pEditSettings->xVSS.pTextRenderingFct = videoEditor_getTextRgbBufferFct;
2563    }
2564
2565    // Send the command.
2566    LOGV("videoEditor_processClip ITEM %d Calling M4xVSS_SendCommand()", unuseditemID);
2567    result = M4xVSS_SendCommand(pContext->engineContext, pContext->pEditSettings);
2568    LOGV("videoEditor_processClip ITEM %d M4xVSS_SendCommand() returned 0x%x",
2569        unuseditemID, (unsigned int) result);
2570
2571    // Remove warnings indications (we only care about errors here)
2572    if ((result == M4VSS3GPP_WAR_TRANSCODING_NECESSARY)
2573        || (result == M4VSS3GPP_WAR_OUTPUTFILESIZE_EXCEED)) {
2574        result = M4NO_ERROR;
2575    }
2576
2577    // Send the first progress indication (=0)
2578    LOGV("VERY FIRST PROGRESS videoEditor_processClip ITEM %d Progress indication %d",
2579        unuseditemID, progress);
2580    pEnv->CallVoidMethod(pContext->engine, pContext->onProgressUpdateMethodId,
2581        unuseditemID, progress);
2582
2583    // Check if a task is being performed.
2584    // ??? ADD STOPPING MECHANISM
2585    LOGV("videoEditor_processClip Entering processing loop");
2586    while((result == M4NO_ERROR)
2587        &&(pContext->state!=ManualEditState_SAVED)
2588        &&(pContext->state!=ManualEditState_STOPPING)) {
2589
2590            // Perform the next processing step.
2591            //LOGV("LVME_processClip Entering M4xVSS_Step()");
2592            result = M4xVSS_Step(pContext->engineContext, &progress);
2593            //LOGV("LVME_processClip M4xVSS_Step() returned 0x%x", (unsigned int)result);
2594
2595            // Log the the 1 % .. 100 % progress after processing.
2596            progress = progressBase + progress/2;
2597            if (progress != lastProgress)
2598            {
2599                // Send a progress notification.
2600                LOGV("videoEditor_processClip ITEM %d Progress indication %d",
2601                    unuseditemID, progress);
2602                pEnv->CallVoidMethod(pContext->engine,
2603                    pContext->onProgressUpdateMethodId,
2604                    unuseditemID, progress);
2605                lastProgress = progress;
2606            }
2607
2608            // Check if processing has been completed.
2609            if (result == completionResult)
2610            {
2611                // Set the state to the completions state.
2612                pContext->state = completionState;
2613                LOGV("videoEditor_processClip ITEM %d STATE changed to %d",
2614                    unuseditemID, pContext->state);
2615
2616                // Reset progress indication, as we switch to next state
2617                lastProgress = 0;
2618
2619                // Reset error code, as we start a new round of processing
2620                result = M4NO_ERROR;
2621
2622                // Check if we are analyzing input
2623                if (pContext->state == ManualEditState_OPENED) {
2624                    // File is opened, we must start saving it
2625                    LOGV("videoEditor_processClip Calling M4xVSS_SaveStart()");
2626                    result = M4xVSS_SaveStart(pContext->engineContext,
2627                        (M4OSA_Char*)pContext->pEditSettings->pOutputFile,
2628                        (M4OSA_UInt32)pContext->pEditSettings->uiOutputPathSize);
2629                    LOGV("videoEditor_processClip ITEM %d SaveStart() returned 0x%x",
2630                        unuseditemID, (unsigned int) result);
2631
2632                    // Set the state to saving.
2633                    pContext->state  = ManualEditState_SAVING;
2634                    completionState  = ManualEditState_SAVED;
2635                    completionResult = M4VSS3GPP_WAR_SAVING_DONE;
2636                    errorState       = ManualEditState_SAVING_ERROR;
2637
2638                    // While saving progress goes from 50 to 100
2639                    progressBase     = 50;
2640                }
2641                // Check if we encoding is ongoing
2642                else if (pContext->state == ManualEditState_SAVED) {
2643                    if (progress != 100) {
2644                        // Send a progress notification.
2645                        progress = 100;
2646                        LOGI("videoEditor_processClip ITEM %d Last progress indication %d",
2647                            unuseditemID, progress);
2648                        pEnv->CallVoidMethod(pContext->engine,
2649                            pContext->onProgressUpdateMethodId,
2650                            unuseditemID, progress);
2651                    }
2652
2653                    // Stop the encoding.
2654                    LOGV("videoEditor_processClip Calling M4xVSS_SaveStop()");
2655                    result = M4xVSS_SaveStop(pContext->engineContext);
2656                    LOGV("videoEditor_processClip M4xVSS_SaveStop() returned 0x%x", result);
2657                }
2658                // Other states are unexpected
2659                else {
2660                    result = M4ERR_STATE;
2661                    LOGE("videoEditor_processClip ITEM %d State ERROR 0x%x",
2662                        unuseditemID, (unsigned int) result);
2663                }
2664            }
2665
2666            // Check if an error occurred.
2667            if (result != M4NO_ERROR)
2668            {
2669                // Set the state to the error state.
2670                pContext->state = errorState;
2671
2672                // Log the result.
2673                LOGE("videoEditor_processClip ITEM %d Processing ERROR 0x%x",
2674                    unuseditemID, (unsigned int) result);
2675            }
2676    }
2677
2678    // Return the error result
2679    LOGE("videoEditor_processClip ITEM %d END 0x%x", unuseditemID, (unsigned int) result);
2680    return result;
2681}
2682/*+ PROGRESS CB */
2683
2684static int
2685videoEditor_generateClip(
2686                JNIEnv*                             pEnv,
2687                jobject                             thiz,
2688                jobject                             settings) {
2689    bool               loaded   = true;
2690    ManualEditContext* pContext = M4OSA_NULL;
2691    M4OSA_ERR          result   = M4NO_ERROR;
2692
2693    LOGV("videoEditor_generateClip START");
2694
2695    // Get the context.
2696    pContext = (ManualEditContext*)videoEditClasses_getContext(&loaded, pEnv, thiz);
2697
2698    Mutex::Autolock autoLock(pContext->mLock);
2699
2700    // Validate the settings parameter.
2701    videoEditJava_checkAndThrowIllegalArgumentException(&loaded, pEnv,
2702                                                (NULL == settings),
2703                                                "settings is null");
2704
2705    // Make sure that the context was set.
2706    videoEditJava_checkAndThrowIllegalStateException(&loaded, pEnv,
2707                                             (M4OSA_NULL == pContext),
2708                                             "not initialized");
2709
2710    // Load the clip settings
2711    LOGV("videoEditor_generateClip Calling videoEditor_loadSettings");
2712    videoEditor_loadSettings(pEnv, thiz, settings);
2713    LOGV("videoEditor_generateClip videoEditor_loadSettings returned");
2714
2715    // Generate the clip
2716    LOGV("videoEditor_generateClip Calling LVME_processClip");
2717    result = videoEditor_processClip(pEnv, thiz, 0 /*item id is unused*/);
2718    LOGV("videoEditor_generateClip videoEditor_processClip returned 0x%x", result);
2719
2720    if (pContext->state != ManualEditState_INITIALIZED) {
2721        // Free up memory (whatever the result)
2722        videoEditor_unloadSettings(pEnv, thiz);
2723    }
2724
2725    LOGV("videoEditor_generateClip END 0x%x", (unsigned int) result);
2726    return result;
2727}
2728
2729static void
2730videoEditor_loadSettings(
2731                JNIEnv*                             pEnv,
2732                jobject                             thiz,
2733                jobject                             settings)
2734{
2735    bool               needToBeLoaded   = true;
2736    ManualEditContext* pContext = M4OSA_NULL;
2737
2738    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_loadSettings()");
2739
2740    // Add a code marker (the condition must always be true).
2741    ADD_CODE_MARKER_FUN(NULL != pEnv)
2742
2743    // Get the context.
2744    pContext = (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded,
2745                                                                pEnv, thiz);
2746
2747    // Validate the settings parameter.
2748    videoEditJava_checkAndThrowIllegalArgumentException(&needToBeLoaded, pEnv,
2749                                                (NULL == settings),
2750                                                "settings is null");
2751
2752    // Make sure that the context was set.
2753    videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
2754                                             (M4OSA_NULL == pContext),
2755                                             "not initialized");
2756
2757    // Check if the context is valid (required because the context is dereferenced).
2758    if (needToBeLoaded)
2759    {
2760        // Make sure that we are in a correct state.
2761        videoEditJava_checkAndThrowIllegalStateException(&needToBeLoaded, pEnv,
2762                             (pContext->state != ManualEditState_INITIALIZED),
2763                             "settings already loaded");
2764
2765        // Retrieve the edit settings.
2766        if(pContext->pEditSettings != M4OSA_NULL) {
2767            videoEditClasses_freeEditSettings(&pContext->pEditSettings);
2768            pContext->pEditSettings = M4OSA_NULL;
2769        }
2770        videoEditClasses_getEditSettings(&needToBeLoaded, pEnv, settings,
2771            &pContext->pEditSettings,true);
2772    }
2773
2774    // Check if the edit settings could be retrieved.
2775    if (needToBeLoaded)
2776    {
2777        // Log the edit settings.
2778        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "inside load settings");
2779        VIDEOEDIT_LOG_EDIT_SETTINGS(pContext->pEditSettings);
2780    }
2781    LOGV("videoEditor_loadSettings END");
2782}
2783
2784
2785
2786static void
2787videoEditor_unloadSettings(
2788                JNIEnv*                             pEnv,
2789                jobject                             thiz)
2790{
2791    bool               needToBeUnLoaded = true;
2792    ManualEditContext* pContext = M4OSA_NULL;
2793    M4OSA_ERR          result   = M4NO_ERROR;
2794
2795    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_unloadSettings()");
2796
2797    // Get the context.
2798    pContext = (ManualEditContext*)videoEditClasses_getContext(&needToBeUnLoaded, pEnv, thiz);
2799
2800    // Make sure that the context was set.
2801    videoEditJava_checkAndThrowIllegalStateException(&needToBeUnLoaded, pEnv,
2802                                             (M4OSA_NULL == pContext),
2803                                             "not initialized");
2804
2805    // Check if the context is valid (required because the context is dereferenced).
2806    if (needToBeUnLoaded)
2807    {
2808        LOGV("videoEditor_unloadSettings state %d", pContext->state);
2809        // Make sure that we are in a correct state.
2810        videoEditJava_checkAndThrowIllegalStateException(&needToBeUnLoaded, pEnv,
2811                     ((pContext->state != ManualEditState_ANALYZING      ) &&
2812                      (pContext->state != ManualEditState_ANALYZING_ERROR) &&
2813                      (pContext->state != ManualEditState_OPENED         ) &&
2814                      (pContext->state != ManualEditState_SAVING_ERROR   ) &&
2815                      (pContext->state != ManualEditState_SAVED          ) &&
2816                      (pContext->state != ManualEditState_STOPPING       ) ),
2817                     "videoEditor_unloadSettings no load settings in progress");
2818    }
2819
2820    // Check if we are in a correct state.
2821    if (needToBeUnLoaded)
2822    {
2823        // Check if the thread could be stopped.
2824        if (needToBeUnLoaded)
2825        {
2826            // Close the command.
2827            LOGV("videoEditor_unloadSettings Calling M4xVSS_CloseCommand()");
2828            result = M4xVSS_CloseCommand(pContext->engineContext);
2829            LOGV("videoEditor_unloadSettings M4xVSS_CloseCommand() returned 0x%x",
2830                (unsigned int)result);
2831
2832            // Check if the command could be closed.
2833            videoEditJava_checkAndThrowRuntimeException(&needToBeUnLoaded, pEnv,
2834             (M4NO_ERROR != result), result);
2835        }
2836
2837        // Check if the command could be closed.
2838        if (needToBeUnLoaded)
2839        {
2840            // Free the edit settings.
2841            //videoEditClasses_freeEditSettings(&pContext->pEditSettings);
2842
2843            // Reset the thread result.
2844            pContext->threadResult = M4NO_ERROR;
2845
2846            // Reset the thread progress.
2847            pContext->threadProgress = 0;
2848
2849            // Set the state to initialized.
2850            pContext->state = ManualEditState_INITIALIZED;
2851        }
2852    }
2853}
2854
2855static void
2856videoEditor_stopEncoding(
2857                JNIEnv*                             pEnv,
2858                jobject                             thiz)
2859{
2860    bool               stopped  = true;
2861    ManualEditContext* pContext = M4OSA_NULL;
2862    M4OSA_ERR          result   = M4NO_ERROR;
2863
2864    LOGV("videoEditor_stopEncoding START");
2865
2866    // Get the context.
2867    pContext = (ManualEditContext*)videoEditClasses_getContext(&stopped, pEnv, thiz);
2868
2869    // Change state and get Lock
2870    // This will ensure the generateClip function exits
2871    pContext->state = ManualEditState_STOPPING;
2872    Mutex::Autolock autoLock(pContext->mLock);
2873
2874    // Make sure that the context was set.
2875    videoEditJava_checkAndThrowIllegalStateException(&stopped, pEnv,
2876                                             (M4OSA_NULL == pContext),
2877                                             "not initialized");
2878
2879    if (stopped) {
2880
2881        // Check if the command should be closed.
2882        if (pContext->state != ManualEditState_INITIALIZED)
2883        {
2884            // Close the command.
2885            LOGV("videoEditor_stopEncoding Calling M4xVSS_CloseCommand()");
2886            result = M4xVSS_CloseCommand(pContext->engineContext);
2887            LOGV("videoEditor_stopEncoding M4xVSS_CloseCommand() returned 0x%x",
2888                (unsigned int)result);
2889        }
2890
2891        // Check if the command could be closed.
2892        videoEditJava_checkAndThrowRuntimeException(&stopped, pEnv,
2893            (M4NO_ERROR != result), result);
2894
2895        // Free the edit settings.
2896        videoEditClasses_freeEditSettings(&pContext->pEditSettings);
2897
2898        // Set the state to initialized.
2899        pContext->state = ManualEditState_INITIALIZED;
2900    }
2901
2902}
2903
2904static void
2905videoEditor_release(
2906                JNIEnv*                             pEnv,
2907                jobject                             thiz)
2908{
2909    bool               released = true;
2910    ManualEditContext* pContext = M4OSA_NULL;
2911    M4OSA_ERR          result   = M4NO_ERROR;
2912
2913    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "videoEditor_release()");
2914
2915    // Add a text marker (the condition must always be true).
2916    ADD_TEXT_MARKER_FUN(NULL != pEnv)
2917
2918    // Get the context.
2919    pContext = (ManualEditContext*)videoEditClasses_getContext(&released, pEnv, thiz);
2920
2921    // If context is not set, return (we consider release already happened)
2922    if (pContext == NULL) {
2923        LOGV("videoEditor_release Nothing to do, context is aleady NULL");
2924        return;
2925    }
2926
2927
2928    // Check if the context is valid (required because the context is dereferenced).
2929    if (released)
2930    {
2931        if (pContext->state != ManualEditState_INITIALIZED)
2932        {
2933            // Change state and get Lock
2934            // This will ensure the generateClip function exits if it is running
2935            pContext->state = ManualEditState_STOPPING;
2936            Mutex::Autolock autoLock(pContext->mLock);
2937        }
2938
2939        // Reset the context.
2940        videoEditClasses_setContext(&released, pEnv, thiz, (void *)M4OSA_NULL);
2941
2942        // Check if the command should be closed.
2943        if (pContext->state != ManualEditState_INITIALIZED)
2944        {
2945            // Close the command.
2946            LOGV("videoEditor_release Calling M4xVSS_CloseCommand() state =%d",
2947                pContext->state);
2948            result = M4xVSS_CloseCommand(pContext->engineContext);
2949            LOGV("videoEditor_release M4xVSS_CloseCommand() returned 0x%x",
2950                (unsigned int)result);
2951
2952            // Check if the command could be closed.
2953            videoEditJava_checkAndThrowRuntimeException(&released, pEnv,
2954                (M4NO_ERROR != result), result);
2955        }
2956
2957        // Cleanup the engine.
2958        LOGV("videoEditor_release Calling M4xVSS_CleanUp()");
2959        result = M4xVSS_CleanUp(pContext->engineContext);
2960        LOGV("videoEditor_release M4xVSS_CleanUp() returned 0x%x", (unsigned int)result);
2961
2962        // Check if the cleanup succeeded.
2963        videoEditJava_checkAndThrowRuntimeException(&released, pEnv,
2964            (M4NO_ERROR != result), result);
2965
2966        // Free the edit settings.
2967        videoEditClasses_freeEditSettings(&pContext->pEditSettings);
2968        pContext->pEditSettings = M4OSA_NULL;
2969
2970
2971        if(pContext->mPreviewController != M4OSA_NULL)
2972        {
2973            delete pContext->mPreviewController;
2974            pContext->mPreviewController = M4OSA_NULL;
2975        }
2976
2977        // Free the context.
2978        if(pContext->mAudioSettings != M4OSA_NULL)
2979        {
2980            M4OSA_free((M4OSA_MemAddr32)pContext->mAudioSettings);
2981            pContext->mAudioSettings = M4OSA_NULL;
2982        }
2983        videoEditor_freeContext(pEnv, &pContext);
2984    }
2985}
2986
2987static int
2988videoEditor_registerManualEditMethods(
2989                JNIEnv*                             pEnv)
2990{
2991    int result = -1;
2992
2993    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
2994     "videoEditor_registerManualEditMethods()");
2995
2996    // Look up the engine class
2997    jclass engineClazz = pEnv->FindClass(MANUAL_EDIT_ENGINE_CLASS_NAME);
2998
2999    // Clear any resulting exceptions.
3000    pEnv->ExceptionClear();
3001
3002    // Check if the engine class was found.
3003    if (NULL != engineClazz)
3004    {
3005        // Register all the methods.
3006        if (pEnv->RegisterNatives(engineClazz, gManualEditMethods,
3007                sizeof(gManualEditMethods) / sizeof(gManualEditMethods[0])) == JNI_OK)
3008        {
3009            // Success.
3010            result = 0;
3011        }
3012    }
3013
3014    // Return the result.
3015    return(result);
3016}
3017
3018/*******Audio Graph*******/
3019
3020static M4OSA_UInt32 getDecibelSound(M4OSA_UInt32 value)
3021{
3022    int dbSound = 1;
3023
3024    if (value == 0) return 0;
3025
3026    if (value > 0x4000 && value <= 0x8000) // 32768
3027        dbSound = 90;
3028    else if (value > 0x2000 && value <= 0x4000) // 16384
3029        dbSound = 84;
3030    else if (value > 0x1000 && value <= 0x2000) // 8192
3031        dbSound = 78;
3032    else if (value > 0x0800 && value <= 0x1000) // 4028
3033        dbSound = 72;
3034    else if (value > 0x0400 && value <= 0x0800) // 2048
3035        dbSound = 66;
3036    else if (value > 0x0200 && value <= 0x0400) // 1024
3037        dbSound = 60;
3038    else if (value > 0x0100 && value <= 0x0200) // 512
3039        dbSound = 54;
3040    else if (value > 0x0080 && value <= 0x0100) // 256
3041        dbSound = 48;
3042    else if (value > 0x0040 && value <= 0x0080) // 128
3043        dbSound = 42;
3044    else if (value > 0x0020 && value <= 0x0040) // 64
3045        dbSound = 36;
3046    else if (value > 0x0010 && value <= 0x0020) // 32
3047        dbSound = 30;
3048    else if (value > 0x0008 && value <= 0x0010) //16
3049        dbSound = 24;
3050    else if (value > 0x0007 && value <= 0x0008) //8
3051        dbSound = 24;
3052    else if (value > 0x0003 && value <= 0x0007) // 4
3053        dbSound = 18;
3054    else if (value > 0x0001 && value <= 0x0003) //2
3055        dbSound = 12;
3056    else if (value > 0x000 && value == 0x0001) // 1
3057        dbSound = 6;
3058    else
3059        dbSound = 0;
3060
3061    return dbSound;
3062}
3063
3064typedef struct
3065{
3066    M4OSA_UInt8      *m_dataAddress;
3067    M4OSA_UInt32    m_bufferSize;
3068} M4AM_Buffer;
3069
3070
3071M4OSA_UInt8 logLookUp[256] = {
30720,120,137,146,154,159,163,167,171,173,176,178,181,182,184,186,188,189,190,192,193,
3073194,195,196,198,199,199,200,201,202,203,204,205,205,206,207,207,208,209,209,210,
3074211,211,212,212,213,213,214,215,215,216,216,216,217,217,218,218,219,219,220,220,
3075220,221,221,222,222,222,223,223,223,224,224,224,225,225,225,226,226,226,227,227,
3076227,228,228,228,229,229,229,229,230,230,230,230,231,231,231,232,232,232,232,233,
3077233,233,233,233,234,234,234,234,235,235,235,235,236,236,236,236,236,237,237,237,
3078237,237,238,238,238,238,238,239,239,239,239,239,240,240,240,240,240,240,241,241,
3079241,241,241,241,242,242,242,242,242,242,243,243,243,243,243,243,244,244,244,244,
3080244,244,245,245,245,245,245,245,245,246,246,246,246,246,246,246,247,247,247,247,
3081247,247,247,247,248,248,248,248,248,248,248,249,249,249,249,249,249,249,249,250,
3082250,250,250,250,250,250,250,250,251,251,251,251,251,251,251,251,252,252,252,252,
3083252,252,252,252,252,253,253,253,253,253,253,253,253,253,253,254,254,254,254,254,
3084254,254,254,254,255,255,255,255,255,255,255,255,255,255,255};
3085
3086M4OSA_ERR M4MA_generateAudioGraphFile(JNIEnv* pEnv, M4OSA_Char* pInputFileURL,
3087                     M4OSA_Char* pOutFileURL,
3088                     M4OSA_UInt32 samplesPerValue,
3089                     M4OSA_UInt32 channels,
3090                     M4OSA_UInt32 frameDuration,
3091                     ManualEditContext* pContext)
3092{
3093    M4OSA_ERR           err;
3094    M4OSA_Context       outFileHandle = M4OSA_NULL;
3095    M4OSA_Context       inputFileHandle = M4OSA_NULL;
3096    M4AM_Buffer         bufferIn = {0, 0};
3097    M4OSA_UInt32        peakVolumeDbValue = 0;
3098    M4OSA_UInt32        samplesCountInBytes= 0 , numBytesToRead = 0, index = 0;
3099    M4OSA_UInt32        writeCount = 0, samplesCountBigEndian = 0, volumeValuesCount = 0;
3100    M4OSA_Int32         seekPos = 0;
3101    M4OSA_UInt32        fileSize = 0;
3102    M4OSA_UInt32        totalBytesRead = 0;
3103    M4OSA_UInt32        prevProgress = 0;
3104    bool                threadStarted = true;
3105
3106    int dbValue = 0;
3107    M4OSA_Int16 *ptr16 ;
3108
3109    jclass engineClass = pEnv->FindClass(MANUAL_EDIT_ENGINE_CLASS_NAME);
3110    videoEditJava_checkAndThrowIllegalStateException(&threadStarted, pEnv,
3111                                             (M4OSA_NULL == engineClass),
3112                                             "not initialized");
3113
3114    /* register the call back function pointer */
3115    pContext->onAudioGraphProgressUpdateMethodId =
3116            pEnv->GetMethodID(engineClass, "onAudioGraphExtractProgressUpdate", "(IZ)V");
3117
3118
3119    /* ENTER */
3120    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "ENTER - M4MA_generateAudioGraphFile");
3121    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3122            "Audio Graph samplesPerValue %d channels %d", samplesPerValue, channels);
3123
3124    /******************************************************************************
3125        OPEN INPUT AND OUTPUT FILES
3126    *******************************************************************************/
3127    err = M4OSA_fileReadOpen (&inputFileHandle, pInputFileURL, M4OSA_kFileRead);
3128    if (inputFileHandle == M4OSA_NULL) {
3129        VIDEOEDIT_LOG_ERROR(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3130            "M4MA_generateAudioGraphFile: Cannot open input file 0x%lx", err);
3131        return err;
3132    }
3133
3134    /* get the file size for progress */
3135    err = M4OSA_fileReadGetOption(inputFileHandle, M4OSA_kFileReadGetFileSize,
3136                                (M4OSA_Void**)&fileSize);
3137    if ( err != M4NO_ERROR) {
3138        //LVMEL_LOG_ERROR("M4MA_generateAudioGraphFile : File write failed \n");
3139        jniThrowException(pEnv, "java/lang/IOException", "file size get option failed");
3140        //return -1;
3141    }
3142
3143    err = M4OSA_fileWriteOpen (&outFileHandle,(M4OSA_Char*) pOutFileURL,
3144        M4OSA_kFileCreate | M4OSA_kFileWrite);
3145    if (outFileHandle == M4OSA_NULL) {
3146        if (inputFileHandle != NULL)
3147        {
3148            M4OSA_fileReadClose(inputFileHandle);
3149        }
3150        return err;
3151    }
3152
3153    /******************************************************************************
3154        PROCESS THE SAMPLES
3155    *******************************************************************************/
3156    samplesCountInBytes = (samplesPerValue * sizeof(M4OSA_UInt16) * channels);
3157
3158    bufferIn.m_dataAddress = (M4OSA_UInt8*)M4OSA_malloc(samplesCountInBytes*sizeof(M4OSA_UInt16), 0,
3159    (M4OSA_Char*)"AudioGraph" );
3160    if ( bufferIn.m_dataAddress != M4OSA_NULL) {
3161        bufferIn.m_bufferSize = samplesCountInBytes*sizeof(M4OSA_UInt16);
3162    } else {
3163        VIDEOEDIT_LOG_ERROR(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3164            "M4MA_generateAudioGraphFile: Malloc failed for bufferIn.m_dataAddress 0x%lx",
3165            M4ERR_ALLOC);
3166        return M4ERR_ALLOC;
3167    }
3168    /* sample to be converted to BIG endian ; store the frame duration */
3169    samplesCountBigEndian = ((frameDuration>>24)&0xff) | // move byte 3 to byte 0
3170                    ((frameDuration<<8)&0xff0000) | // move byte 1 to byte 2
3171                    ((frameDuration>>8)&0xff00) | // move byte 2 to byte 1
3172                    ((frameDuration<<24)&0xff000000); // byte 0 to byte 3
3173
3174    /* write the samples per value supplied to out file */
3175    err = M4OSA_fileWriteData (outFileHandle, (M4OSA_MemAddr8)&samplesCountBigEndian,
3176        sizeof(M4OSA_UInt32) );
3177    if (err != M4NO_ERROR) {
3178        jniThrowException(pEnv, "java/lang/IOException", "file write failed");
3179    }
3180
3181
3182    /* write UIn32 value 0 for no of values as place holder */
3183    samplesCountBigEndian = 0; /* reusing local var */
3184    err = M4OSA_fileWriteData (outFileHandle, (M4OSA_MemAddr8)&samplesCountBigEndian,
3185        sizeof(M4OSA_UInt32) );
3186    if (err != M4NO_ERROR) {
3187        jniThrowException(pEnv, "java/lang/IOException", "file write failed");
3188    }
3189
3190    /* loop until EOF */
3191    do
3192    {
3193        M4OSA_memset((M4OSA_MemAddr8)bufferIn.m_dataAddress,bufferIn.m_bufferSize, 0);
3194
3195        numBytesToRead = samplesCountInBytes;
3196
3197        err =  M4OSA_fileReadData(  inputFileHandle,
3198                                    (M4OSA_MemAddr8)bufferIn.m_dataAddress,
3199                                    &numBytesToRead );
3200
3201        if (err != M4NO_ERROR) {
3202            // if out value of bytes-read is 0, break
3203            if ( numBytesToRead == 0) {
3204                VIDEOEDIT_LOG_ERROR(ANDROID_LOG_INFO, "VIDEO_EDITOR", "numBytesToRead 0x%lx",
3205                numBytesToRead);
3206                break; /* stop if file is empty or EOF */
3207            }
3208        }
3209
3210        ptr16 = (M4OSA_Int16*)bufferIn.m_dataAddress;
3211
3212        peakVolumeDbValue = 0;
3213        index = 0;
3214
3215        // loop through half the lenght frame bytes read 'cause its 16 bits samples
3216        while (index < (numBytesToRead / 2)) {
3217            /* absolute values of 16 bit sample */
3218            if (ptr16[index] < 0) {
3219                ptr16[index] = -(ptr16[index]);
3220            }
3221            peakVolumeDbValue = (peakVolumeDbValue > (M4OSA_UInt32)ptr16[index] ?\
3222             peakVolumeDbValue : (M4OSA_UInt32)ptr16[index]);
3223            index++;
3224        }
3225
3226        // move 7 bits , ignore sign bit
3227        dbValue = (peakVolumeDbValue >> 7);
3228        dbValue = logLookUp[(M4OSA_UInt8)dbValue];
3229
3230        err = M4OSA_fileWriteData (outFileHandle, (M4OSA_MemAddr8)&dbValue, sizeof(M4OSA_UInt8) );
3231        if (err != M4NO_ERROR) {
3232            VIDEOEDIT_LOG_ERROR(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3233             "M4MA_generateAudioGraphFile : File write failed");
3234            break;
3235        }
3236
3237        volumeValuesCount ++;
3238        totalBytesRead += numBytesToRead;
3239
3240        if ((((totalBytesRead*100)/fileSize)) != prevProgress) {
3241            if ( (pContext->threadProgress != prevProgress) && (prevProgress != 0 )) {
3242                //pContext->threadProgress = prevProgress;
3243                //onWveformProgressUpdateMethodId(prevProgress, 0);
3244                //LVME_callAudioGraphOnProgressUpdate(pContext, 0, prevProgress);
3245            pEnv->CallVoidMethod(pContext->engine,
3246                                 pContext->onAudioGraphProgressUpdateMethodId,
3247                                 prevProgress, 0);
3248            VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "pContext->threadProgress %d",
3249                             prevProgress);
3250            }
3251        }
3252        prevProgress = (((totalBytesRead*100)/fileSize));
3253
3254    } while (numBytesToRead != 0);
3255
3256    VIDEOEDIT_LOG_ERROR(ANDROID_LOG_INFO, "VIDEO_EDITOR", "loop 0x%lx", volumeValuesCount);
3257
3258    /* if some error occured in fwrite */
3259    if (numBytesToRead != 0) {
3260        //err = -1;
3261        jniThrowException(pEnv, "java/lang/IOException", "numBytesToRead != 0 ; file write failed");
3262    }
3263
3264    /* write the count in place holder after seek */
3265    seekPos = sizeof(M4OSA_UInt32);
3266    err = M4OSA_fileWriteSeek(outFileHandle, M4OSA_kFileSeekBeginning,
3267            &seekPos /* after samples per value */);
3268    if ( err != M4NO_ERROR) {
3269        jniThrowException(pEnv, "java/lang/IOException", "file seek failed");
3270    } else {
3271        volumeValuesCount = ((volumeValuesCount>>24)&0xff) | // move byte 3 to byte 0
3272                    ((volumeValuesCount<<8)&0xff0000) | // move byte 1 to byte 2
3273                    ((volumeValuesCount>>8)&0xff00) |  // move byte 2 to byte 1
3274                    ((volumeValuesCount<<24)&0xff000000); // byte 0 to byte 3
3275
3276        err = M4OSA_fileWriteData (outFileHandle, (M4OSA_MemAddr8)&volumeValuesCount,
3277                                    sizeof(M4OSA_UInt32) );
3278        if ( err != M4NO_ERROR) {
3279            jniThrowException(pEnv, "java/lang/IOException", "file write failed");
3280        }
3281    }
3282
3283    /******************************************************************************
3284    CLOSE AND FREE ALLOCATIONS
3285    *******************************************************************************/
3286    M4OSA_free((M4OSA_MemAddr32)bufferIn.m_dataAddress);
3287    M4OSA_fileReadClose(inputFileHandle);
3288    M4OSA_fileWriteClose(outFileHandle);
3289    /* final finish callback */
3290    pEnv->CallVoidMethod(pContext->engine, pContext->onAudioGraphProgressUpdateMethodId, 100, 0);
3291
3292    /* EXIT */
3293    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR", "EXIT - M4MA_generateAudioGraphFile");
3294
3295    return err;
3296}
3297
3298static int videoEditor_generateAudioWaveFormSync (JNIEnv*  pEnv, jobject thiz,
3299                                                  jstring pcmfilePath,
3300                                                  jstring outGraphfilePath,
3301                                                  jint frameDuration, jint channels,
3302                                                  jint samplesCount)
3303{
3304    M4OSA_ERR result = M4NO_ERROR;
3305    ManualEditContext* pContext = M4OSA_NULL;
3306    bool needToBeLoaded = true;
3307
3308    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3309        "videoEditor_generateAudioWaveFormSync() ");
3310
3311    /* Get the context. */
3312    pContext = (ManualEditContext*)videoEditClasses_getContext(&needToBeLoaded, pEnv, thiz);
3313    if (pContext == M4OSA_NULL) {
3314        VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3315            "videoEditor_generateAudioWaveFormSync() - pContext is NULL ");
3316    }
3317
3318    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3319        "videoEditor_generateAudioWaveFormSync Retrieving pStringOutAudioGraphFile");
3320
3321    const char *pPCMFilePath = pEnv->GetStringUTFChars(pcmfilePath, NULL);
3322    if (pPCMFilePath == M4OSA_NULL) {
3323        if (pEnv != NULL) {
3324            jniThrowException(pEnv, "java/lang/RuntimeException",
3325                "Input string PCMFilePath is null");
3326        }
3327    }
3328
3329    const char *pStringOutAudioGraphFile = pEnv->GetStringUTFChars(outGraphfilePath, NULL);
3330    if (pStringOutAudioGraphFile == M4OSA_NULL) {
3331        if (pEnv != NULL) {
3332            jniThrowException(pEnv, "java/lang/RuntimeException",
3333                "Input string outGraphfilePath is null");
3334        }
3335    }
3336
3337    VIDEOEDIT_LOG_API(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3338        "videoEditor_generateAudioWaveFormSync Generate the waveform data %s %d %d %d",
3339        pStringOutAudioGraphFile, frameDuration, channels, samplesCount);
3340
3341    /* Generate the waveform */
3342    result = M4MA_generateAudioGraphFile(pEnv, (M4OSA_Char*) pPCMFilePath,
3343        (M4OSA_Char*) pStringOutAudioGraphFile,
3344        (M4OSA_UInt32) samplesCount,
3345        (M4OSA_UInt32) channels,
3346        (M4OSA_UInt32)frameDuration,
3347        pContext);
3348
3349    if (pStringOutAudioGraphFile != NULL) {
3350        pEnv->ReleaseStringUTFChars(outGraphfilePath, pStringOutAudioGraphFile);
3351    }
3352
3353    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR",
3354        "videoEditor_generateAudioWaveFormSync pContext->bSkipState ");
3355
3356    return result;
3357}
3358
3359/******** End Audio Graph *******/
3360jint JNI_OnLoad(
3361                JavaVM*                             pVm,
3362                void*                               pReserved)
3363{
3364    void* pEnv         = NULL;
3365    bool  needToBeInitialized = true;
3366    jint  result      = -1;
3367
3368    VIDEOEDIT_LOG_FUNCTION(ANDROID_LOG_INFO, "VIDEO_EDITOR", "JNI_OnLoad()");
3369
3370    // Add a text marker (the condition must always be true).
3371    ADD_TEXT_MARKER_FUN(NULL != pVm)
3372
3373    // Check the JNI version.
3374    if (pVm->GetEnv(&pEnv, JNI_VERSION_1_4) == JNI_OK)
3375    {
3376        // Add a code marker (the condition must always be true).
3377        ADD_CODE_MARKER_FUN(NULL != pEnv)
3378
3379        // Register the manual edit JNI methods.
3380        if (videoEditor_registerManualEditMethods((JNIEnv*)pEnv) == 0)
3381        {
3382            // Initialize the classes.
3383            videoEditClasses_init(&needToBeInitialized, (JNIEnv*)pEnv);
3384            if (needToBeInitialized)
3385            {
3386                // Success, return valid version number.
3387                result = JNI_VERSION_1_4;
3388            }
3389        }
3390    }
3391
3392    // Return the result.
3393    return(result);
3394}
3395
3396