-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSdkEditorModule.kt
420 lines (377 loc) · 16.8 KB
/
SdkEditorModule.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package com.vesdkreactnativecliintegrationsample
import android.app.Activity
import android.content.Intent
import android.content.res.AssetManager
import android.net.Uri
import android.util.Log
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import com.banuba.sdk.cameraui.data.PipConfig
import com.banuba.sdk.core.data.TrackData
import com.banuba.sdk.export.data.ExportResult
import com.banuba.sdk.export.utils.EXTRA_EXPORTED_SUCCESS
import com.banuba.sdk.core.license.BanubaVideoEditor
import com.banuba.sdk.core.license.LicenseStateCallback
import com.banuba.sdk.ve.flow.VideoCreationActivity
import com.banuba.sdk.pe.BanubaPhotoEditor
import com.facebook.react.bridge.*
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import java.io.*
import java.util.*
import com.banuba.sdk.pe.PhotoCreationActivity
import com.banuba.sdk.pe.PhotoExportResultContract
import com.banuba.sdk.core.EditorUtilityManager
import com.banuba.sdk.ve.ext.VideoEditorUtils.getKoin
import org.koin.core.context.stopKoin
import org.koin.core.error.InstanceCreationException
class SdkEditorModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
companion object {
const val TAG = "SdkEditorModule"
// For Video Editor
private const val OPEN_VIDEO_EDITOR_REQUEST_CODE = 1111
// For Photo Editor
private const val OPEN_PHOTO_EDITOR_REQUEST_CODE = 2222
// Error codes
private const val ERR_CODE_NOT_INITIALIZED = "ERR_SDK_NOT_INITIALIZED"
private const val ERR_CODE_LICENSE_REVOKED = "ERR_SDK_EDITOR_LICENSE_REVOKED"
private const val ERR_CODE_NO_HOST_CONTROLLER = "ERR_CODE_NO_HOST_CONTROLLER"
}
private var resultPromise: Promise? = null
private var videoEditorSDK: BanubaVideoEditor? = null
private var photoEditorSDK: BanubaPhotoEditor? = null
private var integrationModule: VideoEditorIntegrationModule? = null
private val videoEditorResultListener = object : ActivityEventListener {
override fun onActivityResult(
activity: Activity?, requestCode: Int, resultCode: Int, data: Intent?
) {
if (requestCode == OPEN_VIDEO_EDITOR_REQUEST_CODE) {
when {
resultCode == Activity.RESULT_OK -> {
val exportResult = data?.getParcelableExtra<ExportResult.Success>(
EXTRA_EXPORTED_SUCCESS
)
val videoUri = exportResult?.videoList?.firstOrNull()?.sourceUri
val previewUri = exportResult?.preview
if (videoUri == null) {
resultPromise?.reject("ERR_MISSING_EXPORT_RESULT", "")
} else {
// Send video export results to React
val arguments: WritableMap = Arguments.createMap()
arguments.putString("videoUri", videoUri.toString())
arguments.putString("previewUri", previewUri?.toString())
Log.d(TAG, "Send video export results to React")
resultPromise?.resolve(arguments)
/*
NOT REQUIRED FOR INTEGRATION
Added for demonstrating exported video file
*/
demoPlayExportedVideo(activity, videoUri)
}
}
resultCode == Activity.RESULT_CANCELED -> resultPromise?.reject("ERR_VIDEO_EXPORT_CANCEL", "")
}
resultPromise = null
} else if (requestCode == OPEN_PHOTO_EDITOR_REQUEST_CODE) {
when {
resultCode == Activity.RESULT_OK -> {
val photoUri = data?.getParcelableExtra(PhotoCreationActivity.EXTRA_EXPORTED) as? Uri
if (photoUri == null) {
resultPromise?.reject("ERR_MISSING_EXPORT_RESULT", "")
} else {
// Send photo export results to React
val arguments: WritableMap = Arguments.createMap()
arguments.putString("photoUri", photoUri.toString())
Log.d(TAG, "Send photo export results to React")
resultPromise?.resolve(arguments)
}
}
resultCode == Activity.RESULT_CANCELED -> resultPromise?.reject("ERR_PHOTO_EXPORT_CANCEL", "")
}
resultPromise = null
}
}
override fun onNewIntent(intent: Intent?) {}
}
init {
reactApplicationContext.addActivityEventListener(videoEditorResultListener)
}
override fun getName(): String = "SdkEditorModule"
@ReactMethod
fun initVideoEditorSDK(licenseToken: String, promise: Promise) {
videoEditorSDK = BanubaVideoEditor.initialize(licenseToken)
if (videoEditorSDK == null) {
// Token you provided is not correct - empty or truncated
Log.e(TAG, "SDK is not initialized!")
promise.reject(ERR_CODE_NOT_INITIALIZED, "")
} else {
if (integrationModule == null) {
// Initialize video editor sdk dependencies
integrationModule = VideoEditorIntegrationModule().apply {
initialize(reactApplicationContext.applicationContext)
}
}
promise.resolve(null)
}
}
@ReactMethod
fun initPhotoEditorSDK(licenseToken: String, promise: Promise) {
photoEditorSDK = BanubaPhotoEditor.initialize(licenseToken)
if (photoEditorSDK == null) {
// Token you provided is not correct - empty or truncated
Log.e(TAG, "SDK is not initialized!")
promise.reject(ERR_CODE_NOT_INITIALIZED, "")
} else {
promise.resolve(null)
}
}
/**
* Open Video Editor SDK
*/
@ReactMethod
fun openVideoEditor(promise: Promise) {
checkLicenseVideoEditor(callback = { isValid ->
if (isValid) {
// ✅ The license is active
val hostActivity = currentActivity
if (hostActivity == null) {
promise.reject(ERR_CODE_NO_HOST_CONTROLLER)
} else {
this.resultPromise = promise
val intent = VideoCreationActivity.startFromCamera(
hostActivity,
PipConfig(video = Uri.EMPTY, openPipSettings = false),
null,
null
)
hostActivity.startActivityForResult(intent, OPEN_VIDEO_EDITOR_REQUEST_CODE)
}
} else {
// ❌ Use of SDK is restricted: the license is revoked or expired
promise.reject(ERR_CODE_LICENSE_REVOKED, "")
}
}, onError = { promise.reject(ERR_CODE_NOT_INITIALIZED, "") })
}
/**
* Open Video Editor SDK
*/
@ReactMethod
fun openPhotoEditor(promise: Promise) {
if (photoEditorSDK == null) {
Log.e(TAG, "Cannot check license state. Please initialize Photo Editor SDK")
promise.reject(ERR_CODE_LICENSE_REVOKED, "")
} else {
val hostActivity = currentActivity
if (hostActivity == null) {
promise.reject(ERR_CODE_NO_HOST_CONTROLLER, "")
} else {
this.resultPromise = promise
hostActivity.startActivityForResult(
PhotoCreationActivity.startFromGallery(hostActivity.applicationContext), OPEN_PHOTO_EDITOR_REQUEST_CODE
)
}
}
}
@ReactMethod
fun openVideoEditorPIP(promise: Promise) {
checkLicenseVideoEditor(callback = { isValid ->
if (isValid) {
// ✅ The license is active
val hostActivity = currentActivity
if (hostActivity == null) {
promise.reject(ERR_CODE_NO_HOST_CONTROLLER, "")
} else {
// sample_video.mp4 file is hardcoded for demonstrating how to open video editor sdk in the simplest case.
// Please provide valid video URL to open Video Editor in PIP.
val sampleVideoFileName = "sample_video.mp4"
val filesStorage: File = hostActivity.applicationContext.filesDir
val assets: AssetManager = hostActivity.applicationContext.assets
val sampleVideoFile = prepareMediaFile(assets, filesStorage, sampleVideoFileName)
this.resultPromise = promise
val intent = VideoCreationActivity.startFromCamera(
hostActivity,
PipConfig(video = sampleVideoFile.toUri(), openPipSettings = false),
null,
null
)
hostActivity.startActivityForResult(intent, OPEN_VIDEO_EDITOR_REQUEST_CODE)
}
} else {
// ❌ Use of SDK is restricted: the license is revoked or expired
promise.reject(ERR_CODE_LICENSE_REVOKED, "")
}
}, onError = { promise.reject(ERR_CODE_NOT_INITIALIZED, "") })
}
@ReactMethod
fun openVideoEditorTrimmer(promise: Promise) {
checkLicenseVideoEditor(callback = { isValid ->
if (isValid) {
// ✅ The license is active
val hostActivity = currentActivity
if (hostActivity == null) {
promise.reject(ERR_CODE_NO_HOST_CONTROLLER, "")
} else {
// sample_video.mp4 file is hardcoded for demonstrating how to open video editor sdk in the simplest case.
// Please provide valid video URL to open Video Editor in trimmer.
val sampleVideoFileName = "sample_video.mp4"
val filesStorage: File = hostActivity.applicationContext.filesDir
val assets: AssetManager = hostActivity.applicationContext.assets
val sampleVideoFile = prepareMediaFile(assets, filesStorage, sampleVideoFileName)
this.resultPromise = promise
val intent = VideoCreationActivity.startFromTrimmer(
hostActivity,
arrayOf(sampleVideoFile.toUri()),
null,
null
)
hostActivity.startActivityForResult(intent, OPEN_VIDEO_EDITOR_REQUEST_CODE)
}
} else {
// ❌ Use of SDK is restricted: the license is revoked or expired
promise.reject(ERR_CODE_LICENSE_REVOKED, "")
}
}, onError = { promise.reject(ERR_CODE_NOT_INITIALIZED, "") })
}
@ReactMethod
fun releaseVideoEditor(promise: Promise) {
Log.d(TAG, "Release Video Editor SDK")
if (integrationModule != null) {
val utilityManager = try {
// EditorUtilityManager is NULL when the token is expired or revoked.
// This dependency is not explicitly created in DI.
getKoin().getOrNull<EditorUtilityManager>()
} catch (e: InstanceCreationException) {
Log.w(TAG, "EditorUtilityManager was not initialized!", e)
promise.reject("EditorUtilityManager was not initialized!", e)
null
}
utilityManager?.release()
stopKoin()
integrationModule = null
}
videoEditorSDK = null
promise.resolve(null)
}
/**
* Applies selected audio on custom Audio Browser in Video Editor SDK.
*
* This implementation demonstrates how to play audio stored in Android assets in Video Editor SDK.
*
* Since audio browsing and downloading logic can be implemented using React Native on JS side
* you can pass specific audio params in this method to build TrackData
* and use it in "AudioBrowserActivity.applyAudioTrack".
*/
@ReactMethod
fun applyAudioTrack(promise: Promise) {
val hostActivity = currentActivity
// Check if host Activity is a your specific Android Activity responsible for
// passing audio to Video Editor SDK i.e. AudioBrowserActivity.
if (hostActivity is AudioBrowserActivity) {
// Sample audio file used to demonstrate how to pass and play audio file
// in Video Editor SDK
val sampleAudioFileName = "sample_audio.mp3"
val filesStorage: File = hostActivity.applicationContext.filesDir
val assets: AssetManager = hostActivity.applicationContext.assets
val audioTrack: TrackData? = try {
// Video Editor SDK can play ONLY audio file stored on device.
// Make sure that you store audio file on a device before trying to play it.
val sampleAudioFile = prepareMediaFile(assets, filesStorage, sampleAudioFileName)
// TrackData is required in Video Editor SDK for playing audio.
TrackData(
UUID.randomUUID(), "Set title", Uri.fromFile(sampleAudioFile), "Set artist"
)
} catch (e: IOException) {
Log.w(TAG, "Cannot prepare sample audio file", e)
// You can pass null as TrackData to cancel playing last used audio in Video Editor SDK
null
}
Log.d(TAG, "Apply audio track = $audioTrack")
hostActivity.applyAudioTrack(audioTrack)
}
}
@ReactMethod
fun discardAudioTrack(promise: Promise) {
val hostActivity = currentActivity
if (hostActivity is AudioBrowserActivity) {
hostActivity.discardAudioTrack()
promise.resolve(null)
} else {
promise.reject(ERR_CODE_NO_HOST_CONTROLLER, "")
}
}
@ReactMethod
fun closeAudioBrowser(promise: Promise) {
val hostActivity = currentActivity
if (hostActivity is AudioBrowserActivity) {
hostActivity.close()
promise.resolve(null)
} else {
promise.reject(ERR_CODE_NO_HOST_CONTROLLER, "")
}
}
private fun checkLicenseVideoEditor(callback: LicenseStateCallback, onError: () -> Unit) {
if (videoEditorSDK == null) {
Log.e(TAG, "Cannot check license state. Please initialize Video Editor SDK")
onError()
} else {
// Checking the license might take around 1 sec in the worst case.
// Please optimize use if this method in your application for the best user experience
videoEditorSDK?.getLicenseState(callback)
}
}
/**
* Utils methods used to prepare sample audio track for playing in Video Editor SDK.
* NOT REQUIRED IN YOUR APP.
*/
@Throws(IOException::class)
private fun prepareMediaFile(
assets: AssetManager, filesStorage: File, mediaFileName: String
): File {
val sampleAudioFile = File(filesStorage, mediaFileName)
var outputStream: OutputStream? = null
try {
assets.open(mediaFileName).use { inputStream ->
outputStream = FileOutputStream(sampleAudioFile)
val size = copyStream(inputStream, requireNotNull(outputStream))
Log.d(TAG, "Media file has been copied. Size = $size")
}
} catch (e: IOException) {
throw e
} finally {
outputStream?.flush()
outputStream?.close()
}
return sampleAudioFile
}
@Throws(IOException::class)
private fun copyStream(
inStream: InputStream, outStream: OutputStream
): Long {
var size = 0L
val buffer = ByteArray(8192)
var bytes = inStream.read(buffer)
while (bytes >= 0) {
outStream.write(buffer, 0, bytes)
size += bytes.toLong()
bytes = inStream.read(buffer)
}
return size
}
/*
NOT REQUIRED FOR INTEGRATION
Added for playing exported video file.
*/
private fun demoPlayExportedVideo(
activity: Activity?, videoUri: Uri
) {
activity ?: return
val intent = Intent(Intent.ACTION_VIEW).apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val uri = FileProvider.getUriForFile(
activity.applicationContext, "${activity.packageName}.provider", File(videoUri.encodedPath)
)
setDataAndType(uri, "video/mp4")
}
activity?.startActivity(intent)
}
}