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