/
MediaRecorder.kt
514 lines (439 loc) · 17.7 KB
/
MediaRecorder.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package com.xuggle.xuggler.record
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaCodec
import android.media.MediaRecorder
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.util.Log
import android.view.Surface
import com.xuggle.ferry.IBuffer
import com.xuggle.xuggler.*
import com.xuggle.xuggler.io.XugglerIO
import java.io.File
import java.io.OutputStream
import java.lang.NullPointerException
import java.lang.RuntimeException
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean
data class AudioConfig(
internal var audioCodec: ICodec.ID = ICodec.ID.AV_CODEC_ID_AAC,
internal val audioFormat: IAudioSamples.Format = IAudioSamples.Format.FMT_FLTP,
internal val sampleRate: Int = 44100,
internal val bitRate: Int = 192000
)
data class VideoConfig(
internal val height: Int = 1280,
internal val width: Int = 720,
internal var bitRate: Int = 8192000,
internal val videoCodec: ICodec.ID = ICodec.ID.AV_CODEC_ID_H264
)
/**
* A media recorder class. This class records audio and video streams. It uses dedicated threads for each stream.
* To improve performances an input surface is used as input for video encoder (see [MediaCodec.createInputSurface] for more information).
* The audio stream is composed of the sound captured via [AudioRecord].
* Never forget to call [release] to properly release recording and encoding material resources.
*
* @author Olivier Ayache
*
*/
@SuppressLint("MissingPermission")
class MediaRecorder(
val audioConfig: AudioConfig = AudioConfig(),
val videoConfig: VideoConfig = VideoConfig()
) {
private val finputBuffer: ByteBuffer = ByteBuffer.allocateDirect(2048 + 64)
private val buffer = IBuffer.make(null, finputBuffer, 0, 2048 + 64)
private val samples = IAudioSamples.make(buffer, 1, IAudioSamples.Format.FMT_S16)
private val audioRecord: AudioRecord
private var started = AtomicBoolean(false)
private val containerFormat = IContainerFormat.make()
private val container = IContainer.make()
private var containerStarted = AtomicBoolean(false)
private var videoEncoder: IStreamCoder
private var audioEncoder: IStreamCoder
@Volatile
private var csdWritten = false
@Volatile
private var headerWritten = false
private val videoPicture: IVideoPicture
private var pts: Long = 0
private var globalPts = -1L
private var aGlobalPts = -1L
private var aGlobalDts = -1L
private var startUTCPts = 0L
private val readyToWritePacketQueue = ConcurrentLinkedQueue<IPacket>()
private lateinit var surface: Surface
private var outputUrl: Uri? = null
companion object {
private const val TAG = "MediaRecorder"
private val EXECUTOR: CompletionService<Void> =
ExecutorCompletionService(Executors.newSingleThreadExecutor { r ->
Thread(r).apply {
name = "recorder-thread"
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO)
}
})
private lateinit var CONTAINER_THREAD: Thread
private val CEXECUTOR: CompletionService<Void> =
ExecutorCompletionService(Executors.newSingleThreadExecutor { r ->
CONTAINER_THREAD = Thread(r).apply {
name = "container-thread"
Process.setThreadPriority(Process.THREAD_PRIORITY_MORE_FAVORABLE)
}
CONTAINER_THREAD
})
private val PACKET_QUEUE = ConcurrentLinkedQueue(List<IPacket>(2000) { IPacket.make() })
}
init {
val minBufferSize = AudioRecord.getMinBufferSize(
audioConfig.sampleRate,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
)
videoPicture = IVideoPicture.make(IPixelFormat.Type.YUV420P, videoConfig.width, videoConfig.height)
audioRecord = AudioRecord(
MediaRecorder.AudioSource.MIC, audioConfig.sampleRate, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize
)
audioEncoder = IStreamCoder.make(IStreamCoder.Direction.ENCODING, audioConfig.audioCodec)
videoEncoder = IStreamCoder.make(
IStreamCoder.Direction.ENCODING,
ICodec.findEncodingCodec(videoConfig.videoCodec, IPixelFormat.Type.MEDIACODEC)
)
}
fun setOutput(outputStream: OutputStream) {
outputUrl = Uri.parse(XugglerIO.map(outputStream))
}
fun setOutput(outputUri: Uri) {
outputUrl = outputUri
}
fun openOutput(
context: Context,
onContainerOpened: ((success: Boolean) -> Unit) = {}
): Uri {
var sampleFormat = audioConfig.audioFormat
var groupOfPictures = 60
outputUrl = outputUrl ?: getOutputMediaFile(context)
outputUrl?.let {
if (ContentResolver.SCHEME_CONTENT != it.scheme &&
ContentResolver.SCHEME_FILE != it.scheme &&
XugglerIO.DEFAULT_PROTOCOL != it.scheme
) {
containerFormat.setOutputFormat("mpegts", null, null)
audioConfig.audioCodec = ICodec.ID.AV_CODEC_ID_AAC
sampleFormat = IAudioSamples.Format.FMT_FLTP
videoConfig.bitRate = 1024000
} else {
containerFormat.setOutputFormat("mp4", null, null)
}
}
audioEncoder = IStreamCoder.make(IStreamCoder.Direction.ENCODING, audioConfig.audioCodec)
videoEncoder = IStreamCoder.make(
IStreamCoder.Direction.ENCODING,
ICodec.findEncodingCodec(videoConfig.videoCodec, IPixelFormat.Type.MEDIACODEC)
)
CEXECUTOR.submit({
val options = IMetaData.make().apply {
//setValue("transtype", "0")
//setValue("pkt_size", "1316")
}
if (container.open(
outputUrl.toString(),
IContainer.Type.WRITE,
containerFormat,
false,
false,
options,
null
) < 0
) {
onContainerOpened(false)
return@submit
}
container.standardsCompliance = IStreamCoder.CodecStandardsCompliance.COMPLIANCE_EXPERIMENTAL
container.setProperty("mpegts_copyts", true)
//container.setProperty("frag_size", 500);
container.setProperty("movflags", "frag_keyframe+delay_moov")
//stream.metaData = IMetaData.make().apply {
//setValue("rotate", value.toString())
//}
container.addNewStream(audioEncoder)
audioEncoder.sampleFormat = sampleFormat
audioEncoder.bitRate = audioConfig.bitRate
audioEncoder.sampleRate = audioRecord.sampleRate
audioEncoder.timeBase = IRational.make(1, 1000000)
audioEncoder.channels = audioRecord.channelCount
audioEncoder.setProperty("ch_mode", "indep")
container.addNewStream(videoEncoder)
videoEncoder.frameRate = IRational.make(30, 1)
videoEncoder.timeBase = IRational.make(1, 1000000)
videoEncoder.bitRate = videoConfig.bitRate
videoEncoder.width = videoConfig.width
videoEncoder.height = videoConfig.height
videoEncoder.numPicturesInGroupOfPictures = groupOfPictures
videoEncoder.pixelType = IPixelFormat.Type.MEDIACODEC
if (audioEncoder.open() < 0 || videoEncoder.open() < 0) {
onContainerOpened(false)
return@submit
}
surface = videoEncoder.hardwareSurface as Surface
containerStarted.set(true)
onContainerOpened(true)
while (containerStarted.get()) {
if (csdWritten && !headerWritten) {
if (container.writeHeader() < 0) {
throw RuntimeException("Container fails to write header")
}
headerWritten = true
}
if (headerWritten) {
readyToWritePacketQueue.poll()?.let { packet ->
container.writePacket(packet) // TODO: throws error on negative result
PACKET_QUEUE.offer(packet)
}
}
}
if (!Thread.currentThread().isInterrupted && container.isHeaderWritten) {
container.writeTrailer()
}
PACKET_QUEUE.addAll(readyToWritePacketQueue)
readyToWritePacketQueue.clear()
}, null)
return outputUrl!!
}
/**
* Resets the global state of the media recorder
*/
private fun reset() {
globalPts = -1L
aGlobalPts = -1L
aGlobalDts = -1L
pts = 0
csdWritten = false
headerWritten = false
}
/**
* Starts the audio recording.
*/
fun startAudioRecording() {
if (started.get()) {
return
}
audioRecord.startRecording()
}
/**
* Starts the media recorder.
* This call starts the audio and video workers in dedicated threads using [ExecutorCompletionService]
*/
fun start() {
if (started.getAndSet(true)) {
return
}
EXECUTOR.submit({
try {
while (started.get()) {
processVideo()
processAudio()
}
audioRecord.stop()
var read = processAudio()
while (read > 0) {
read = processAudio()
}
flushEncoder(audioEncoder)
flushEncoder(videoEncoder)
containerStarted.set(false)
surface.release()
reset()
} catch (t: Throwable) {
t.printStackTrace()
}
}, null)
}
fun cancelConnection() {
CONTAINER_THREAD.interrupt()
}
/**
* Stops audio and video recording, mixing and encoding
*/
fun stop() {
if (started.compareAndSet(true, false)) {
EXECUTOR.take()
CEXECUTOR.poll(200, TimeUnit.MILLISECONDS)
cancelConnection()
audioEncoder.close()
videoEncoder.close()
container.close(true)
}
}
/**
* Releases all recording en encoding resources. After this call the media recorder must not be used again
*/
fun release() {
audioRecord.release()
container.delete()
audioEncoder.delete()
videoEncoder.delete()
}
/**
* Returns the [Surface] created by the video encoder.
* This surface has been created by [MediaCodec.createInputSurface].
* It will be invalid after call to stop.
* To get a new valid surface again a fresh call to [reset] must be done.
*
* @return the [MediaCodec] input surface to encode video
*/
fun getInputSurface(): Surface {
return surface
}
/**
* Process recorded audio and encode it.
*/
private fun processAudio(): Int {
finputBuffer.rewind()
val read = audioRecord.read(finputBuffer, 2048)
if (read > 0) {
samples.setComplete(
true,
read / (2 * audioRecord.channelCount),
audioRecord.sampleRate,
audioRecord.channelCount,
IAudioSamples.Format.FMT_S16,
pts
)
pts += (read * 1000000L / (2 * audioRecord.channelCount)) / audioRecord.sampleRate
val samplesToEncode = samples
if (samplesToEncode.isComplete) {
val remaining = samplesToEncode.numSamples
var consumed = 0
while (consumed < remaining) {
val audioPacket = PACKET_QUEUE.poll() ?: let {
Log.w(TAG, "Packet buffer empty, data will be lost")
readyToWritePacketQueue.poll()
}
consumed += audioEncoder.encodeAudio(audioPacket, samplesToEncode, consumed)
if (audioPacket.isComplete) {
if (aGlobalPts == -1L && audioPacket.pts >= 0) {
aGlobalPts = audioPacket.pts
aGlobalDts = audioPacket.dts
Log.w(
TAG,
"Audio GlobalPts set to $aGlobalPts"
)
}
audioPacket.pts = audioPacket.pts - aGlobalPts + startUTCPts
audioPacket.dts = audioPacket.dts - aGlobalDts + startUTCPts
readyToWritePacketQueue.offer(audioPacket)
} else {
PACKET_QUEUE.offer(audioPacket)
}
}
}
}
return read
}
/**
* Process video captured by the camera via a [Surface] and encode it.
*/
private fun processVideo() {
val videoPacket = PACKET_QUEUE.poll() ?: let {
Log.w(TAG, "Packet buffer empty, data will be lost")
readyToWritePacketQueue.poll()
}
videoEncoder.encodeVideo(videoPacket, null, videoPicture.size)
if (!csdWritten && videoPacket.isComplete) {
videoPacket.pts = 0
videoPacket.dts = videoPacket.pts
videoEncoder.setExtraData(videoPacket.data, 0, videoPacket.size, true)
csdWritten = true
PACKET_QUEUE.offer(videoPacket)
} else if (videoPacket.isComplete) {
if (globalPts == -1L && videoPacket.pts > 0) {
globalPts = videoPacket.pts
Log.w(TAG, "GlobalPts setted to " + globalPts)
if (startUTCPts == 0L && "mpegts" == containerFormat.outputFormatShortName) {
//startUTCPts = videoPacket.timeBase.rescale(System.currentTimeMillis() - startUTCPtsOffset, IRational.make(1, 1000))
}
}
videoPacket.pts = videoPacket.pts - globalPts + startUTCPts
videoPacket.dts = videoPacket.pts
readyToWritePacketQueue.offer(videoPacket)
} else {
PACKET_QUEUE.offer(videoPacket)
}
}
/**
* Flush an encoder.
* Asks the encoder to encode the last audio frame/pictures in their buffers and encode them.
*
* @param encoder the encoder to flush
*/
private fun flushEncoder(encoder: IStreamCoder) {
Log.w(TAG, "Flusing encoder $encoder")
if (encoder.codecType == ICodec.Type.CODEC_TYPE_AUDIO) {
val audioPacket = PACKET_QUEUE.poll() ?: let {
Log.w(TAG, "Packet buffer empty, data will be lost")
readyToWritePacketQueue.poll()
}
audioEncoder.encodeAudio(audioPacket, null, 0)
if (audioPacket.isComplete) {
audioPacket.pts = audioPacket.pts - aGlobalPts + startUTCPts
audioPacket.dts = audioPacket.dts - aGlobalDts + startUTCPts
readyToWritePacketQueue.offer(audioPacket)
flushEncoder(audioEncoder)
}
} else {
val videoPacket = PACKET_QUEUE.poll() ?: let {
Log.w(TAG, "Packet buffer empty, data will be lost")
readyToWritePacketQueue.poll()
}
videoEncoder.encodeVideo(videoPacket, null, videoPicture.size)
if (videoPacket.isComplete) {
videoPacket.pts = videoPacket.pts - globalPts + startUTCPts
videoPacket.dts = videoPacket.pts
readyToWritePacketQueue.offer(videoPacket)
flushEncoder(videoEncoder)
}
}
}
/** Create a File for saving an image or video */
private fun getOutputMediaFile(context: Context): Uri {
val uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
// Create a media file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
// Create a media file name
val cv = ContentValues().apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Video.VideoColumns.RELATIVE_PATH, Environment.DIRECTORY_MOVIES + "/mix-recorder")
} else {
val mediaStorageDir = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),
"mix-recorder"
)
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
mediaStorageDir.apply {
if (!exists()) {
if (!mkdirs()) {
Log.d("mix-recorder", "failed to create directory")
throw NullPointerException("failed to create directory")
}
}
}
put(MediaStore.Video.VideoColumns.DATA, "${mediaStorageDir.path}${File.separator}VID_$timeStamp.mp4")
}
put(MediaStore.Video.VideoColumns.MIME_TYPE, "video/avc")
put(MediaStore.Video.VideoColumns.DISPLAY_NAME, "VID_$timeStamp.mp4")
}
return Objects.requireNonNull(context.contentResolver.insert(uri, cv))!!
}
}