Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set bitrate and FPS in Media3 Transformer

I want to compress videos for sharing in my Android app. These are my preferred settings:

Resolution: 1280x720
Container: MP4
Video codec: H.264
Video bitrate: 3 Mbit/s
Video FPS: 30
Audio codec: AAC
Audio sampling rate: 44100
Audio bitrate: 128 kbit/s
Move Moov atom to the start to enable streaming (optional)

I do not want to use FFmpeg as it uses software encoders and is very slow. I am getting about 0.7x encoding speed when converting an H.265, 1080p, 120 fps, 40 Mbit/s video to the above settings. Also I want to avoid the hassle of managing an NDK library.

So I eventually settled on Jetpack Media3 Transformer for my use case. And I have this code working perfectly:

val transformationRequest = TransformationRequest.Builder()
    .setVideoMimeType(MimeTypes.VIDEO_H264)
    .setAudioMimeType(MimeTypes.AUDIO_AAC)
    .setResolution(1280)
    .build()

val inputMediaItem = MediaItem.fromUri(uri)
val outputFile = MediaUtils.createTempFile(c,MediaType.VIDEO)

// Create a Transformer
val transformer = Transformer.Builder(c)
    .setTransformationRequest(transformationRequest) // Pass in TransformationRequest
    .addListener(object: Transformer.Listener {
        override fun onTransformationCompleted(inputMediaItem: MediaItem, transformationResult: TransformationResult) {
            super.onTransformationCompleted(inputMediaItem, transformationResult)
            Log.d("ENCODE", "Encoding Complete")
            Log.d("ENCODE", "Output Size: ${MediaUtils.getFileSize(outputFile)}")
        }
    }) // transformerListener is an implementation of Transformer.Listener
    .build()
withContext(Dispatchers.Main) {
    // Start the transformation
    transformer.startTransformation(inputMediaItem, outputFile.absolutePath)
}

This encode completes at 4-5x speed. But I don’t see a way to set anything except the codecs and resolution. The Transformer Documentation does say this:

video encoding works with default settings, but you can also pass custom video encoder settings or replace the encoder factory to get complete control over how encoders are used

But I cannot find any documentation on how to set the video fps and video/audio bitrate.

like image 509
ShahiM Avatar asked Dec 05 '25 23:12

ShahiM


1 Answers

In Transformer you can use DefaultEncoderFactory to set your desired bitrate:

transformerBuilder.setEncoderFactory(
    new DefaultEncoderFactory.Builder( /* context= */ this)
    .setRequestedVideoEncoderSettings(
        new VideoEncoderSettings.Builder()
        .setBitrate(BITRATE_VALUE)
        .build())
    .build());
like image 77
mulan Avatar answered Dec 07 '25 16:12

mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!