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
| internal object VideoUtils {
fun getMediaCodecList(): IntArray? { val numCodecs = MediaCodecList.REGULAR_CODECS var codecInfo: MediaCodecInfo? = null var i = 0 while (i < numCodecs && codecInfo == null) { val info = MediaCodecList.getCodecInfoAt(i) if (!info.isEncoder) { i++ continue } val types = info.supportedTypes var found = false var j = 0 while (j < types.size && !found) { if (types[j] == "video/avc") { found = true } j++ } if (!found) { i++ continue } codecInfo = info i++ } Log.i("ErrorRecodeVideoUtils", "found " + codecInfo?.name + " supporting video/avc") val capabilities = codecInfo?.getCapabilitiesForType("video/avc") return capabilities?.colorFormats }
fun createMediaFormat(activity: Activity): MediaFormat? { val decorView = activity.window?.decorView ?: return null val rect = Rect() decorView.getWindowVisibleDisplayFrame(rect) val display = activity.windowManager.defaultDisplay val width = display.width val height = display.height
val mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height); mediaFormat.setInteger( MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible ) mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, width * height) mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 10) mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5) return mediaFormat }
fun store(context: Context, dataList: ArrayList<String?>) { val activity = ActivityLifecycle.getCurrentActivity() Log.i("ErrorRecodeVideoUtils", "store ThreadName:${Thread.currentThread().name}") if (activity != null) { getMediaCodecList() val mediaFormat = createMediaFormat(activity) if (mediaFormat != null) { val file = createVideoFile(activity) try { writeVideo(mediaFormat, dataList, file) } catch (e: Throwable) { file.delete() } } } dataList.forEach { path -> if (path != null) File(path).delete() } }
private fun createVideoFile(activity: Activity): File { var file = activity.getExternalFilesDir("error_recode") if (file == null) file = activity.cacheDir!! file = File(file, "error_aac")
if (!file.exists() || file.isFile) file.mkdirs() return File(file, "${System.currentTimeMillis()}.mp4") }
private fun writeVideo(mediaFormat: MediaFormat, dataList: ArrayList<String?>, file: File) { try { val mediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC); val mediaMuxer = MediaMuxer(file.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) mediaCodec.start()
writeVideoFrame(dataList, mediaCodec, mediaMuxer, mediaFormat)
mediaCodec.stop() mediaCodec.release()
mediaMuxer.stop() mediaMuxer.release() } catch (e: Exception) { e.printStackTrace() } }
private fun writeVideoFrame( dataList: ArrayList<String?>, mediaCodec: MediaCodec, mediaMuxer: MediaMuxer, mediaFormat: MediaFormat ) { val mediaCodecBufferInfo = MediaCodec.BufferInfo()
var generateIndex = 0 dataList.forEach { path -> if (path != null) { val inputBufferIndex: Int = mediaCodec.dequeueInputBuffer(10000) if (inputBufferIndex > 0) { val bitmap = readBitmap(path) ?: return@forEach val ptsUsec = 132L + generateIndex * 1000000 / mediaFormat.getInteger(MediaFormat.KEY_FRAME_RATE) val yuvArray = covertBitmap(bitmap) val inputBuffer = mediaCodec.getInputBuffer(inputBufferIndex) inputBuffer?.clear() inputBuffer?.put(yuvArray) mediaCodec.queueInputBuffer(inputBufferIndex, 0, yuvArray.size, ptsUsec, 0) bitmap.recycle() drainEncoder(false, mediaCodecBufferInfo, mediaCodec, mediaMuxer) generateIndex++ } } }
val inputBufferIndex = mediaCodec.dequeueInputBuffer(10000) if (inputBufferIndex >= 0) { val ptsUsec = 132L + generateIndex * 1000000 / mediaFormat.getInteger(MediaFormat.KEY_FRAME_RATE) mediaCodec.queueInputBuffer( inputBufferIndex, 0, 0, ptsUsec, MediaCodec.BUFFER_FLAG_END_OF_STREAM ) drainEncoder(true, mediaCodecBufferInfo, mediaCodec, mediaMuxer) } }
private var mMuxerStarted = false private var mTrackIndex = 0
private fun drainEncoder( isEnd: Boolean, mediaCodecBufferInfo: MediaCodec.BufferInfo, mediaCodec: MediaCodec, mediaMuxer: MediaMuxer ) { if (isEnd) { try { mediaCodec.signalEndOfInputStream() } catch (e: Exception) { } }
while (true) { val encoderStatus = mediaCodec.dequeueOutputBuffer(mediaCodecBufferInfo, 10000L) if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { if (!isEnd) { break } else { Log.i( "ErrorRecodeVideoUtils", "no output available, spinning to await EOS" ) } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { if (mMuxerStarted) { throw RuntimeException("format changed twice") } val mediaFormat = mediaCodec.outputFormat mTrackIndex = mediaMuxer.addTrack(mediaFormat) mediaMuxer.start() mMuxerStarted = true } else if (encoderStatus < 0) { Log.i( "ErrorRecodeVideoUtils", "unexpected result from encoder.dequeueOutputBuffer: $encoderStatus" ) } else { val outputBuffer = mediaCodec.getOutputBuffer(encoderStatus) ?: throw java.lang.RuntimeException( "encoderOutputBuffer " + encoderStatus + " was null" ) if ((mediaCodecBufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { Log.d( "ErrorRecodeVideoUtils", "ignoring BUFFER_FLAG_CODEC_CONFIG" ) mediaCodecBufferInfo.size = 0 } if (mediaCodecBufferInfo.size != 0) { if (!mMuxerStarted) { throw java.lang.RuntimeException("muxer hasn't started") }
outputBuffer.position(mediaCodecBufferInfo.offset) outputBuffer.limit(mediaCodecBufferInfo.offset + mediaCodecBufferInfo.size) Log.d( "ErrorRecodeVideoUtils", ("BufferInfo: " + mediaCodecBufferInfo.offset + "," + mediaCodecBufferInfo.size + "," + mediaCodecBufferInfo.presentationTimeUs) ) try { mediaMuxer.writeSampleData(mTrackIndex, outputBuffer, mediaCodecBufferInfo) } catch (e: java.lang.Exception) { Log.i("ErrorRecodeVideoUtils", "Too many frames") } } mediaCodec.releaseOutputBuffer(encoderStatus, false) if ((mediaCodecBufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { if (!isEnd) { Log.i( "ErrorRecodeVideoUtils", "reached end of stream unexpectedly" ) } else { Log.i("ErrorRecodeVideoUtils", "end of stream reached") } break } } } }
private fun covertBitmap(bitmap: Bitmap): ByteArray {
val inputWidth = bitmap.width / 4 * 4 val inputHeight = bitmap.height / 4 * 4 val argb = IntArray(inputWidth * inputHeight)
bitmap.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight)
val yuv = ByteArray(inputWidth * inputHeight * 3 / 2)
encodeYUV420SP(yuv, argb, inputWidth, inputHeight)
return yuv }
private fun encodeYUV420SP(yuv420sp: ByteArray, argb: IntArray, width: Int, height: Int) { val frameSize = width * height var yIndex = 0 var uvIndex = frameSize var a: Int var R: Int var G: Int var B: Int var Y: Int var U: Int var V: Int var index = 0 for (j in 0 until height) { for (i in 0 until width) { a = argb[index] and -0x1000000 shr 24 R = argb[index] and 0xff0000 shr 16 G = argb[index] and 0xff00 shr 8 B = argb[index] and 0xff shr 0 Y = (66 * R + 129 * G + 25 * B + 128 shr 8) + 16 V = (-38 * R - 74 * G + 112 * B + 128 shr 8) + 128 U = (112 * R - 94 * G - 18 * B + 128 shr 8) + 128 yuv420sp[yIndex++] = (if (Y < 0) 0 else if (Y > 255) 255 else Y).toByte() if (j % 2 == 0 && index % 2 == 0) { yuv420sp[uvIndex++] = (if (V < 0) 0 else if (V > 255) 255 else V).toByte() yuv420sp[uvIndex++] = (if (U < 0) 0 else if (U > 255) 255 else U).toByte() } index++ } } }
private fun readBitmap(path: String): Bitmap? { var fis: FileInputStream? = null var baos: ByteArrayOutputStream? = null try { fis = FileInputStream(path) baos = ByteArrayOutputStream()
val fileBuffer = ByteArray(2048) var len: Int while (fis.read(fileBuffer).also { len = it } >= 0) { for (i in 0 until len) { fileBuffer[i] = fileBuffer[i].xor(0xF) } baos.write(fileBuffer, 0, len) } baos.flush() val imageBuffer = baos.toByteArray() val bitmap = BitmapFactory.decodeByteArray(imageBuffer, 0, imageBuffer.size) Log.i("ErrorRecodeVideoUtils", "bitmap:$bitmap") return bitmap } catch (e: Exception) {
} finally { try { fis?.close() } catch (e: Exception) {
} try { baos?.close() } catch (e: Exception) {
} } return null } }
|