Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
2.9 kB
1
Indexable
Never
import android.media.MediaExtractor;
import android.media.MediaFormat;
import java.nio.ByteBuffer;

public class VideoMerger {

    // Phương pháp để xác định kích thước bộ đệm dựa trên độ phân giải video
    private int determineBufferSize(MediaExtractor extractor, int trackIndex) {
        MediaFormat format = extractor.getTrackFormat(trackIndex);
        int width = format.getInteger(MediaFormat.KEY_WIDTH);
        int height = format.getInteger(MediaFormat.KEY_HEIGHT);
        int pixelCount = width * height;
        int bufferSize = 0;

        // Đặt kích thước bộ đệm dựa trên số lượng pixel
        if (pixelCount <= 1280 * 720) { // 720p
            bufferSize = 256 * 1024; // 256 KB
        } else if (pixelCount <= 1920 * 1080) { // 1080p
            bufferSize = 512 * 1024; // 512 KB
        } else if (pixelCount <= 3840 * 2160) { // 4K
            bufferSize = 1024 * 1024; // 1 MB
        } else {
            bufferSize = 2048 * 1024; // 2 MB cho các video có độ phân giải cao hơn
        }

        return bufferSize;
    }

    private void writeSampleData(MediaExtractor extractor, MediaMuxer muxer, int videoTrackIndex, int audioTrackIndex) {
        int bufferSize = determineBufferSize(extractor, videoTrackIndex);
        ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();

        while (true) {
            bufferInfo.offset = 0;
            bufferInfo.size = extractor.readSampleData(buffer, 0);
            if (bufferInfo.size < 0) {
                Log.d(TAG, "No more samples to read");
                bufferInfo.size = 0;
                break;
            }
            bufferInfo.presentationTimeUs = extractor.getSampleTime();
            bufferInfo.flags = mapExtractorFlagsToCodecFlags(extractor.getSampleFlags());

            int trackIndex = extractor.getSampleTrackIndex();
            if (trackIndex == videoTrackIndex) {
                muxer.writeSampleData(videoTrackIndex, buffer, bufferInfo);
            } else if (trackIndex == audioTrackIndex && audioTrackIndex >= 0) {
                muxer.writeSampleData(audioTrackIndex, buffer, bufferInfo);
            }
            extractor.advance();
        }
    }

    private int mapExtractorFlagsToCodecFlags(int extractorFlags) {
        int codecFlags = 0;
        if ((extractorFlags & MediaExtractor.SAMPLE_FLAG_SYNC) != 0) {
            codecFlags |= MediaCodec.BUFFER_FLAG_SYNC_FRAME;
        }
        if ((extractorFlags & MediaExtractor.SAMPLE_FLAG_PARTIAL_FRAME) != 0) {
            codecFlags |= MediaCodec.BUFFER_FLAG_PARTIAL_FRAME;
        }
        if ((extractorFlags & MediaExtractor.SAMPLE_FLAG_ENCRYPTED) != 0) {
            codecFlags |= MediaCodec.BUFFER_FLAG_CODEC_CONFIG; // Best guess for encrypted
        }
        return codecFlags;
    }
}
Leave a Comment