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