VideoDecoder.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. package videodecode;
  19. import android.content.res.AssetFileDescriptor;
  20. import android.media.MediaCodec;
  21. import android.media.MediaCodec.BufferInfo;
  22. import android.media.MediaExtractor;
  23. import android.media.MediaFormat;
  24. import android.content.Context;
  25. import android.util.Log;
  26. import java.nio.ByteBuffer;
  27. /**
  28. * Hardware-accelerated video decoder using Android MediaCodec.
  29. *
  30. * Decodes video files (H.264/AVC, etc.) and extracts YUV frames for processing.
  31. * Handles different YUV color formats (planar and semi-planar) across devices.
  32. *
  33. * Usage:
  34. * <pre>
  35. * VideoDecoder decoder = new VideoDecoder();
  36. * decoder.setContext(context);
  37. * decoder.init("video.mp4");
  38. * int frameCount = decoder.decodeAll();
  39. * </pre>
  40. */
  41. public class VideoDecoder {
  42. private static final boolean DEBUG = false;
  43. /** YUV420 planar format (YV12/I420) - separate Y, U, V planes */
  44. private static final int COLOR_FORMATYUV420_PLANAR = 19;
  45. /** YUV420 semi-planar format (NV21) - Y plane + interleaved UV plane */
  46. private static final int COLOR_FORMATYUV420_SEMIPLANAR = 21;
  47. private MediaCodec decoder;
  48. private MediaExtractor extractor;
  49. private int width;
  50. private int height;
  51. private int decoderId;
  52. private int outputColorFormat = -1;
  53. private Context context;
  54. /** Conditional logging based on DEBUG flag */
  55. private void log(String fstr, Object... args) {
  56. if (!DEBUG) return;
  57. Log.d("darkfi", String.format(fstr, args));
  58. }
  59. /** Native callback invoked when a frame is decoded and YUV data is extracted */
  60. native void onFrameDecoded(int decoderId, byte[] yData, byte[] uData, byte[] vData, int width, int height);
  61. /** Sets the decoder ID for native callbacks */
  62. public void setDecoderId(int id) {
  63. this.decoderId = id;
  64. }
  65. /** Sets the Android context for asset loading */
  66. public void setContext(Context ctx) {
  67. this.context = ctx;
  68. }
  69. /**
  70. * Initializes the video decoder for a given asset path.
  71. *
  72. * Attempts to load from app assets first, falls back to file path.
  73. * Finds the video track, extracts dimensions, and configures MediaCodec.
  74. *
  75. * @param assetPath Path to video file (asset name or absolute path)
  76. * @return true if initialization succeeded, false otherwise
  77. */
  78. public boolean init(String assetPath) {
  79. try {
  80. log("init(%s)", assetPath);
  81. extractor = new MediaExtractor();
  82. try {
  83. AssetFileDescriptor afd = context.getAssets().openFd(assetPath);
  84. extractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
  85. } catch (Exception e) {
  86. extractor.setDataSource(assetPath);
  87. }
  88. MediaFormat format = null;
  89. for (int i = 0; i < extractor.getTrackCount(); i++) {
  90. format = extractor.getTrackFormat(i);
  91. String mime = format.getString(MediaFormat.KEY_MIME);
  92. if (mime != null && mime.startsWith("video/")) {
  93. extractor.selectTrack(i);
  94. break;
  95. }
  96. format = null;
  97. }
  98. if (format == null) {
  99. Log.e("darkfi", "No video track found in: " + assetPath);
  100. return false;
  101. }
  102. width = format.getInteger(MediaFormat.KEY_WIDTH);
  103. height = format.getInteger(MediaFormat.KEY_HEIGHT);
  104. decoder = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME));
  105. decoder.configure(format, null, null, 0);
  106. log("Initialized decoder: %dx%d mime=%s", width, height, format.getString(MediaFormat.KEY_MIME));
  107. return true;
  108. } catch (Exception e) {
  109. Log.e("darkfi", "Failed to initialize video decoder: " + e.getMessage(), e);
  110. return false;
  111. }
  112. }
  113. /**
  114. * Decodes all frames from the video.
  115. *
  116. * Processes the entire video, extracting YUV data from each frame
  117. * and invoking the native callback. Handles format changes during decoding.
  118. *
  119. * @return Number of frames decoded, or -1 on error
  120. */
  121. public int decodeAll() {
  122. if (decoder == null || extractor == null) {
  123. Log.e("darkfi", "Decoder not initialized");
  124. return -1;
  125. }
  126. decoder.start();
  127. MediaFormat outputFormat = decoder.getOutputFormat();
  128. if (outputFormat != null && outputFormat.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
  129. outputColorFormat = outputFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
  130. }
  131. log("decodeAll() colorFormat=%d", outputColorFormat);
  132. int frameIndex = 0;
  133. boolean inputEOS = false;
  134. boolean outputEOS = false;
  135. BufferInfo bufferInfo = new BufferInfo();
  136. try {
  137. while (!outputEOS) {
  138. if (!inputEOS) {
  139. inputEOS = processInput();
  140. }
  141. int result = processOutput(bufferInfo);
  142. if (result >= 0) {
  143. frameIndex += result;
  144. }
  145. if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
  146. outputEOS = true;
  147. }
  148. }
  149. } finally {
  150. decoder.stop();
  151. decoder.release();
  152. extractor.release();
  153. }
  154. log("Decoding complete: %d frames", frameIndex);
  155. return frameIndex;
  156. }
  157. /**
  158. * Feeds compressed video data from the extractor to the decoder.
  159. *
  160. * @return true if end of stream was reached, false otherwise
  161. */
  162. private boolean processInput() {
  163. // Try to read some data
  164. int inputBufferId = decoder.dequeueInputBuffer(10000);
  165. // Not yet available
  166. if (inputBufferId < 0)
  167. return false;
  168. ByteBuffer inputBuffer = decoder.getInputBuffer(inputBufferId);
  169. int sampleSize = extractor.readSampleData(inputBuffer, 0);
  170. // Negative sampleSize means extractor reached end of file
  171. if (sampleSize < 0) {
  172. decoder.queueInputBuffer(inputBufferId, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
  173. return true;
  174. }
  175. // Success
  176. decoder.queueInputBuffer(inputBufferId, 0, sampleSize, extractor.getSampleTime(), 0);
  177. extractor.advance();
  178. return false;
  179. }
  180. /**
  181. * Retrieves and processes decoded frames from the decoder.
  182. *
  183. * @param bufferInfo BufferInfo object to populate with frame metadata
  184. * @return Number of frames processed (0 or 1), or negative value for info events
  185. */
  186. private int processOutput(BufferInfo bufferInfo) {
  187. int outputBufferId = decoder.dequeueOutputBuffer(bufferInfo, 10000);
  188. if (outputBufferId >= 0) {
  189. // New frame to read
  190. ByteBuffer outputBuffer = decoder.getOutputBuffer(outputBufferId);
  191. if (outputBuffer != null) {
  192. processOutputBuffer(outputBuffer, bufferInfo.offset, bufferInfo.size);
  193. }
  194. decoder.releaseOutputBuffer(outputBufferId, false);
  195. return 1;
  196. } else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
  197. // Ready to read the output format
  198. MediaFormat newFormat = decoder.getOutputFormat();
  199. // We are interested in the color format
  200. if (newFormat.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
  201. outputColorFormat = newFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
  202. log("Format changed: colorFormat=%d", outputColorFormat);
  203. }
  204. }
  205. return 0;
  206. }
  207. /**
  208. * Processes a decoded video frame buffer and extracts YUV data.
  209. *
  210. * Handles different color formats:
  211. * - Semi-planar (NV21): De-interleaves UV data
  212. * - Planar (YV12/I420): Reads U and V planes directly
  213. *
  214. * @param outputBuffer Raw decoded frame data from MediaCodec
  215. * @param offset Offset to valid data in buffer
  216. * @param size Size of valid data in bytes
  217. */
  218. private void processOutputBuffer(ByteBuffer outputBuffer, int offset, int size) {
  219. outputBuffer.position(offset);
  220. outputBuffer.limit(offset + size);
  221. int ySize = width * height;
  222. int uvSize = (width / 2) * (height / 2);
  223. byte[] yData = new byte[ySize];
  224. byte[] uData = new byte[uvSize];
  225. byte[] vData = new byte[uvSize];
  226. outputBuffer.get(yData, 0, ySize);
  227. if (outputColorFormat == COLOR_FORMATYUV420_PLANAR) {
  228. outputBuffer.get(uData, 0, uvSize);
  229. outputBuffer.get(vData, 0, uvSize);
  230. } else {
  231. if (outputColorFormat != COLOR_FORMATYUV420_SEMIPLANAR) {
  232. Log.w("darkfi", String.format("Unknown color format %d, assuming semi-planar", outputColorFormat));
  233. }
  234. deinterleaveUV(outputBuffer, uData, vData, uvSize);
  235. }
  236. onFrameDecoded(decoderId, yData, uData, vData, width, height);
  237. outputBuffer.clear();
  238. }
  239. /**
  240. * De-interleaves UV data from semi-planar YUV format (NV21).
  241. *
  242. * @param outputBuffer Buffer containing interleaved UVUV... data
  243. * @param uData Output array for U component
  244. * @param vData Output array for V component
  245. * @param uvSize Number of UV pairs to de-interleave
  246. */
  247. private void deinterleaveUV(ByteBuffer outputBuffer, byte[] uData, byte[] vData, int uvSize) {
  248. byte[] uvInterleaved = new byte[uvSize * 2];
  249. outputBuffer.get(uvInterleaved);
  250. for (int i = 0; i < uvSize; i++) {
  251. uData[i] = uvInterleaved[i * 2];
  252. vData[i] = uvInterleaved[i * 2 + 1];
  253. }
  254. }
  255. }