Java Code Examples for android.media.MediaFormat#containsKey()

The following examples show how to use android.media.MediaFormat#containsKey() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MediaExtractor.java    From MediaPlayer-Extended with Apache License 2.0 6 votes vote down vote up
/**
 * Get the track format at the specified index.
 * More detail on the representation can be found at {@link android.media.MediaCodec}
 */
public MediaFormat getTrackFormat(int index) {
    MediaFormat mediaFormat = mApiExtractor.getTrackFormat(index);
    String mime = mediaFormat.getString(MediaFormat.KEY_MIME);

    // Set the default DAR
    //
    // We need to check the existence of the width/height fields because some platforms
    // return unsupported tracks as "video/unknown" mime type without the required fields to
    // calculate the DAR.
    //
    // Example:
    // Samsung Galaxy S5 Android 6.0.1 with thumbnail tracks (jpeg image)
    // MediaFormat{error-type=-1002, mime=video/unknown, isDMCMMExtractor=1, durationUs=323323000}
    if(mime.startsWith("video/")
            && mediaFormat.containsKey(MediaFormat.KEY_WIDTH)
            && mediaFormat.containsKey(MediaFormat.KEY_HEIGHT)) {
        mediaFormat.setFloat(MEDIA_FORMAT_EXTENSION_KEY_DAR,
                (float)mediaFormat.getInteger(MediaFormat.KEY_WIDTH)
                        / mediaFormat.getInteger(MediaFormat.KEY_HEIGHT));
    }

    return mediaFormat;
}
 
Example 2
Source File: Video.java    From Camera-Roll-Android-App with Apache License 2.0 6 votes vote down vote up
public int retrieveFrameRate() {
    MediaExtractor extractor = new MediaExtractor();
    int frameRate = -1;
    try {
        //Adjust data source as per the requirement if file, URI, etc.
        extractor.setDataSource(getPath());
        int numTracks = extractor.getTrackCount();
        for (int i = 0; i < numTracks; i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            if (format.containsKey(MediaFormat.KEY_FRAME_RATE)) {
                frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //Release stuff
        extractor.release();
    }
    return frameRate;
}
 
Example 3
Source File: TrackMetadataUtil.java    From LiTr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@NonNull
private static String printImageMetadata(@NonNull Context context, @Nullable MediaFormat mediaFormat) {
    if (mediaFormat == null) {
        return "\n";
    }
    StringBuilder stringBuilder = new StringBuilder();
    if (mediaFormat.containsKey(MediaFormat.KEY_MIME)) {
        stringBuilder.append(context.getString(R.string.stats_mime_type, mediaFormat.getString(MediaFormat.KEY_MIME)));
    }
    if (mediaFormat.containsKey(MediaFormat.KEY_WIDTH)) {
        stringBuilder.append(context.getString(R.string.stats_width, mediaFormat.getInteger(MediaFormat.KEY_WIDTH)));
    }
    if (mediaFormat.containsKey(MediaFormat.KEY_HEIGHT)) {
        stringBuilder.append(context.getString(R.string.stats_height, mediaFormat.getInteger(MediaFormat.KEY_HEIGHT)));
    }
    return stringBuilder.toString();
}
 
Example 4
Source File: TrackTranscoder.java    From LiTr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
TrackTranscoder(@NonNull MediaSource mediaSource,
                int sourceTrack,
                @NonNull MediaTarget mediaTarget,
                int targetTrack,
                @Nullable MediaFormat targetFormat,
                @Nullable Renderer renderer,
                @Nullable Decoder decoder,
                @Nullable Encoder encoder) {
    this.mediaSource = mediaSource;
    this.sourceTrack = sourceTrack;
    this.targetTrack = targetTrack;
    this.mediaMuxer = mediaTarget;
    this.targetFormat = targetFormat;
    this.renderer = renderer;
    this.decoder = decoder;
    this.encoder = encoder;

    MediaFormat sourceMedia = mediaSource.getTrackFormat(sourceTrack);
    if (sourceMedia.containsKey(MediaFormat.KEY_DURATION)) {
        duration = sourceMedia.getLong(MediaFormat.KEY_DURATION);
        if (targetFormat != null) {
            targetFormat.setLong(MediaFormat.KEY_DURATION, duration);
        }
    }
}
 
Example 5
Source File: TranscoderUtils.java    From LiTr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static int getBitrate(@NonNull MediaFormat trackFormat) {
    int bitrate = -1;
    if (trackFormat.containsKey(MediaFormat.KEY_BIT_RATE)) {
        bitrate = trackFormat.getInteger(MediaFormat.KEY_BIT_RATE);
    }
    return bitrate;
}
 
Example 6
Source File: Converter.java    From VidEffects with Apache License 2.0 5 votes vote down vote up
private MediaFormat getAudioFormat() {
    for (int i = 0; i < audioExtractor.getTrackCount(); i++) {
        MediaFormat format = audioExtractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (mime != null &&
                (mime.startsWith(AUDIO) || format.containsKey(MediaFormat.KEY_CHANNEL_COUNT))) {
            audioExtractor.selectTrack(i);
            return format;
        }
    }
    return null;
}
 
Example 7
Source File: MediaCodecVideoRenderer.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onOutputFormatChanged(MediaCodec codec, MediaFormat outputFormat) {
  boolean hasCrop = outputFormat.containsKey(KEY_CROP_RIGHT)
      && outputFormat.containsKey(KEY_CROP_LEFT) && outputFormat.containsKey(KEY_CROP_BOTTOM)
      && outputFormat.containsKey(KEY_CROP_TOP);
  currentWidth = hasCrop
      ? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1
      : outputFormat.getInteger(MediaFormat.KEY_WIDTH);
  currentHeight = hasCrop
      ? outputFormat.getInteger(KEY_CROP_BOTTOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1
      : outputFormat.getInteger(MediaFormat.KEY_HEIGHT);
  currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio;
  if (Util.SDK_INT >= 21) {
    // On API level 21 and above the decoder applies the rotation when rendering to the surface.
    // Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
    // to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
    if (pendingRotationDegrees == 90 || pendingRotationDegrees == 270) {
      int rotatedHeight = currentWidth;
      currentWidth = currentHeight;
      currentHeight = rotatedHeight;
      currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
    }
  } else {
    // On API level 20 and below the decoder does not apply the rotation.
    currentUnappliedRotationDegrees = pendingRotationDegrees;
  }
  // Must be applied each time the output format changes.
  codec.setVideoScalingMode(scalingMode);
}
 
Example 8
Source File: MediaTransformer.java    From LiTr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Nullable
private MediaFormat createTargetMediaFormat(@NonNull MediaSource mediaSource,
                                            int sourceTrackIndex) {
    MediaFormat sourceMediaFormat = mediaSource.getTrackFormat(sourceTrackIndex);
    MediaFormat targetMediaFormat = null;

    String mimeType = null;
    if (sourceMediaFormat.containsKey(MediaFormat.KEY_MIME)) {
        mimeType = sourceMediaFormat.getString(MediaFormat.KEY_MIME);
    }

    if (mimeType != null) {
        if (mimeType.startsWith("video")) {
            targetMediaFormat = MediaFormat.createVideoFormat(mimeType,
                                                              sourceMediaFormat.getInteger(MediaFormat.KEY_WIDTH),
                                                              sourceMediaFormat.getInteger(MediaFormat.KEY_HEIGHT));
            int targetBitrate = TranscoderUtils.estimateVideoTrackBitrate(mediaSource, sourceTrackIndex);
            targetMediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, targetBitrate);

            int targetKeyFrameInterval = DEFAULT_KEY_FRAME_INTERVAL;
            if (sourceMediaFormat.containsKey(MediaFormat.KEY_I_FRAME_INTERVAL)) {
                targetKeyFrameInterval = sourceMediaFormat.getInteger(MediaFormat.KEY_I_FRAME_INTERVAL);
            }
            targetMediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, targetKeyFrameInterval);
        } else if (mimeType.startsWith("audio")) {
            targetMediaFormat = MediaFormat.createAudioFormat(mimeType,
                                                              sourceMediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE),
                                                              sourceMediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
            targetMediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, sourceMediaFormat.getInteger(MediaFormat.KEY_BIT_RATE));
        }
    }

    return targetMediaFormat;
}
 
Example 9
Source File: GlVideoRenderer.java    From LiTr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void init(@Nullable Surface outputSurface, @Nullable MediaFormat sourceMediaFormat, @Nullable MediaFormat targetMediaFormat) {
    if (outputSurface == null) {
        throw new IllegalArgumentException("GlVideoRenderer requires an output surface");
    }
    if (targetMediaFormat == null) {
        throw new IllegalArgumentException("GlVideoRenderer requires target media format");
    }

    triangleVertices = ByteBuffer.allocateDirect(
            triangleVerticesData.length * FLOAT_SIZE_BYTES)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();
    triangleVertices.put(triangleVerticesData).position(0);

    // prioritize target video rotation value, fall back to source video rotation value
    int rotation = 0;
    if (targetMediaFormat.containsKey(KEY_ROTATION)) {
        rotation = targetMediaFormat.getInteger(KEY_ROTATION);
    } else if (sourceMediaFormat != null && sourceMediaFormat.containsKey(KEY_ROTATION)) {
        rotation = sourceMediaFormat.getInteger(KEY_ROTATION);
    }
    float aspectRatio = 1;
    if (targetMediaFormat.containsKey(MediaFormat.KEY_WIDTH) && targetMediaFormat.containsKey(MediaFormat.KEY_HEIGHT)) {
        aspectRatio = (float) targetMediaFormat.getInteger(MediaFormat.KEY_WIDTH) / targetMediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
    }

    this.outputSurface = new VideoRenderOutputSurface(outputSurface);

    inputSurface = new VideoRenderInputSurface();
    initMvpMatrix(rotation, aspectRatio);
    initGl();

    for (GlFilter filter : filters) {
        filter.init(Arrays.copyOf(mvpMatrix, mvpMatrix.length), 0);
    }
}
 
Example 10
Source File: BaseAudioDecoder.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void onOutputFormatChanged(@NonNull MediaFormat mediaFormat) {
    if (mediaFormat.containsKey(MediaFormat.KEY_CHANNEL_COUNT)) {
        outputChannelCount = mediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
    }

    if (mediaFormat.containsKey(MediaFormat.KEY_SAMPLE_RATE)) {
        outputSampleRate = mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N && mediaFormat.containsKey(MediaFormat.KEY_PCM_ENCODING)) {
        int key = mediaFormat.getInteger(MediaFormat.KEY_PCM_ENCODING);
        switch (key) {
            case AudioFormat.ENCODING_PCM_8BIT:
                outputSampleType = SampleType.UNSIGNED_8_BIT;
                break;
            case AudioFormat.ENCODING_PCM_FLOAT:
                outputSampleType = SampleType.FLOAT;
                break;
            case AudioFormat.ENCODING_PCM_16BIT:
            default:
                // by default we fallback to signed 16 bit samples
                outputSampleType = SampleType.SIGNED_16_BIT;
                break;
        }
    } else {
        outputSampleType = SampleType.SIGNED_16_BIT;
    }
}
 
Example 11
Source File: TranscoderUtils.java    From LiTr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Nullable
private static String getMimeType(@NonNull MediaFormat trackFormat) {
    String mimeType = null;
    if (trackFormat.containsKey(MediaFormat.KEY_MIME)) {
        mimeType = trackFormat.getString(MediaFormat.KEY_MIME);
    }
    return mimeType;
}
 
Example 12
Source File: AudioProcessThread.java    From VideoProcessor with Apache License 2.0 5 votes vote down vote up
private void doProcessAudio() throws Exception {
    mMediaSource.setDataSource(mExtractor);
    int audioTrackIndex = VideoUtil.selectTrack(mExtractor, true);
    if (audioTrackIndex >= 0) {
        //处理音频
        mExtractor.selectTrack(audioTrackIndex);
        MediaFormat mediaFormat = mExtractor.getTrackFormat(audioTrackIndex);
        String inputMimeType = mediaFormat.containsKey(MediaFormat.KEY_MIME)?mediaFormat.getString(MediaFormat.KEY_MIME):MediaFormat.MIMETYPE_AUDIO_AAC;
        String outputMimeType = MediaFormat.MIMETYPE_AUDIO_AAC;
        //音频暂不支持变速
        Integer startTimeUs = mStartTimeMs == null ? null : mStartTimeMs * 1000;
        Integer endTimeUs = mEndTimeMs == null ? null : mEndTimeMs * 1000;
        boolean await = mMuxerStartLatch.await(3, TimeUnit.SECONDS);
        if (!await) {
            throw new TimeoutException("wait muxerStartLatch timeout!");
        }
        if (mSpeed != null || !inputMimeType.equals(outputMimeType)) {
            AudioUtil.writeAudioTrackDecode(mContext, mExtractor, mMuxer, mMuxerAudioTrackIndex, startTimeUs, endTimeUs,
                    mSpeed==null?1f:mSpeed, this);
        } else {
            AudioUtil.writeAudioTrack(mExtractor, mMuxer, mMuxerAudioTrackIndex, startTimeUs, endTimeUs, this);
        }
    }
    if (mProgressAve != null) {
        mProgressAve.setAudioProgress(1);
    }
    CL.i("Audio Process Done!");
}
 
Example 13
Source File: AudioUtil.java    From VideoProcessor with Apache License 2.0 5 votes vote down vote up
public static int getAudioMaxBufferSize(MediaFormat format) {
    if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
        return format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
    } else {
        return 100 * 1000;
    }
}
 
Example 14
Source File: VideoUtil.java    From VideoProcessor with Apache License 2.0 5 votes vote down vote up
public static int getFrameRate(VideoProcessor.MediaSource mediaSource) {
    MediaExtractor extractor = new MediaExtractor();
    try {
        mediaSource.setDataSource(extractor);
        int trackIndex = VideoUtil.selectTrack(extractor, false);
        MediaFormat format = extractor.getTrackFormat(trackIndex);
        return format.containsKey(MediaFormat.KEY_FRAME_RATE) ? format.getInteger(MediaFormat.KEY_FRAME_RATE) : -1;
    } catch (IOException e) {
        CL.e(e);
        return -1;
    } finally {
        extractor.release();
    }
}
 
Example 15
Source File: DefaultStrategy.java    From GIFCompressor with Apache License 2.0 5 votes vote down vote up
/**
 * Chooses one of the input sizes that is considered to be the best.
 * After thinking about it, I think the best size is the one that is closer to the
 * average aspect ratio.
 *
 * Of course, we must consider all formats' rotation.
 * The size returned is rotated in the reference of a format with rotation = 0.
 *
 * @param formats input formats
 * @return best input size
 */
private ExactSize getBestInputSize(@NonNull List<MediaFormat> formats) {
    int count = formats.size();
    float averageAspectRatio = 0;
    float[] aspectRatio = new float[count];
    boolean[] flipSize = new boolean[count];
    for (int i = 0; i < count; i++) {
        MediaFormat format = formats.get(i);
        float width = format.getInteger(MediaFormat.KEY_WIDTH);
        float height = format.getInteger(MediaFormat.KEY_HEIGHT);
        int rotation = 0;
        if (format.containsKey(MediaFormatConstants.KEY_ROTATION_DEGREES)) {
            rotation = format.getInteger(MediaFormatConstants.KEY_ROTATION_DEGREES);
        }
        boolean flip = (rotation % 180) != 0;
        flipSize[i] = flip;
        aspectRatio[i] = flip ? height / width : width / height;
        averageAspectRatio += aspectRatio[i];
    }
    averageAspectRatio = averageAspectRatio / count;
    float bestDelta = Float.MAX_VALUE;
    int bestMatch = 0;
    for (int i = 0; i < count; i++) {
        float delta = Math.abs(aspectRatio[i] - averageAspectRatio);
        if (delta < bestDelta) {
            bestMatch = i;
            bestDelta = delta;
        }
    }
    MediaFormat bestFormat = formats.get(bestMatch);
    int bestWidth = bestFormat.getInteger(MediaFormat.KEY_WIDTH);
    int bestHeight = bestFormat.getInteger(MediaFormat.KEY_HEIGHT);
    return new ExactSize(
            flipSize[bestMatch] ? bestHeight : bestWidth,
            flipSize[bestMatch] ? bestWidth : bestHeight);
}
 
Example 16
Source File: EncoderDebugger.java    From spydroid-ipcamera with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Converts the image obtained from the decoder to NV21.
 */
private void convertToNV21(int k) {		
	byte[] buffer = new byte[3*mSize/2];

	int stride = mWidth, sliceHeight = mHeight;
	int colorFormat = mDecoderColorFormat;
	boolean planar = false;

	if (mDecOutputFormat != null) {
		MediaFormat format = mDecOutputFormat;
		if (format != null) {
			if (format.containsKey("slice-height")) {
				sliceHeight = format.getInteger("slice-height");
				if (sliceHeight<mHeight) sliceHeight = mHeight;
			}
			if (format.containsKey("stride")) {
				stride = format.getInteger("stride");
				if (stride<mWidth) stride = mWidth;
			}
			if (format.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
				if (format.getInteger(MediaFormat.KEY_COLOR_FORMAT)>0) {
					colorFormat = format.getInteger(MediaFormat.KEY_COLOR_FORMAT);
				}
			}
		}
	}

	switch (colorFormat) {
	case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
	case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar:
	case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar:
		planar = false;
		break;	
	case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
	case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar:
		planar = true;
		break;
	}

	for (int i=0;i<mSize;i++) {
		if (i%mWidth==0) i+=stride-mWidth;
		buffer[i] = mDecodedVideo[k][i];
	}

	if (!planar) {
		for (int i=0,j=0;j<mSize/4;i+=1,j+=1) {
			if (i%mWidth/2==0) i+=(stride-mWidth)/2;
			buffer[mSize+2*j+1] = mDecodedVideo[k][stride*sliceHeight+2*i];
			buffer[mSize+2*j] = mDecodedVideo[k][stride*sliceHeight+2*i+1];
		}
	} else {
		for (int i=0,j=0;j<mSize/4;i+=1,j+=1) {
			if (i%mWidth/2==0) i+=(stride-mWidth)/2;
			buffer[mSize+2*j+1] = mDecodedVideo[k][stride*sliceHeight+i];
			buffer[mSize+2*j] = mDecodedVideo[k][stride*sliceHeight*5/4+i];
		}
	}

	mDecodedVideo[k] = buffer;

}
 
Example 17
Source File: TLMediaEncoder.java    From TimeLapseRecordingSample with Apache License 2.0 4 votes vote down vote up
private static final String asString(final MediaFormat format) {
	final JSONObject map = new JSONObject();
	try {
		if (format.containsKey(MediaFormat.KEY_MIME))
			map.put(MediaFormat.KEY_MIME, format.getString(MediaFormat.KEY_MIME));
		if (format.containsKey(MediaFormat.KEY_WIDTH))
			map.put(MediaFormat.KEY_WIDTH, format.getInteger(MediaFormat.KEY_WIDTH));
		if (format.containsKey(MediaFormat.KEY_HEIGHT))
			map.put(MediaFormat.KEY_HEIGHT, format.getInteger(MediaFormat.KEY_HEIGHT));
		if (format.containsKey(MediaFormat.KEY_BIT_RATE))
			map.put(MediaFormat.KEY_BIT_RATE, format.getInteger(MediaFormat.KEY_BIT_RATE));
		if (format.containsKey(MediaFormat.KEY_COLOR_FORMAT))
			map.put(MediaFormat.KEY_COLOR_FORMAT, format.getInteger(MediaFormat.KEY_COLOR_FORMAT));
		if (format.containsKey(MediaFormat.KEY_FRAME_RATE))
			map.put(MediaFormat.KEY_FRAME_RATE, format.getInteger(MediaFormat.KEY_FRAME_RATE));
		if (format.containsKey(MediaFormat.KEY_I_FRAME_INTERVAL))
			map.put(MediaFormat.KEY_I_FRAME_INTERVAL, format.getInteger(MediaFormat.KEY_I_FRAME_INTERVAL));
		if (format.containsKey(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER))
			map.put(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, format.getLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER));
		if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE))
			map.put(MediaFormat.KEY_MAX_INPUT_SIZE, format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE));
		if (format.containsKey(MediaFormat.KEY_DURATION))
			map.put(MediaFormat.KEY_DURATION, format.getInteger(MediaFormat.KEY_DURATION));
		if (format.containsKey(MediaFormat.KEY_CHANNEL_COUNT))
			map.put(MediaFormat.KEY_CHANNEL_COUNT, format.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
		if (format.containsKey(MediaFormat.KEY_SAMPLE_RATE))
			map.put(MediaFormat.KEY_SAMPLE_RATE, format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
		if (format.containsKey(MediaFormat.KEY_CHANNEL_MASK))
			map.put(MediaFormat.KEY_CHANNEL_MASK, format.getInteger(MediaFormat.KEY_CHANNEL_MASK));
		if (format.containsKey(MediaFormat.KEY_AAC_PROFILE))
			map.put(MediaFormat.KEY_AAC_PROFILE, format.getInteger(MediaFormat.KEY_AAC_PROFILE));
		if (format.containsKey(MediaFormat.KEY_AAC_SBR_MODE))
			map.put(MediaFormat.KEY_AAC_SBR_MODE, format.getInteger(MediaFormat.KEY_AAC_SBR_MODE));
		if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE))
			map.put(MediaFormat.KEY_MAX_INPUT_SIZE, format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE));
		if (format.containsKey(MediaFormat.KEY_IS_ADTS))
			map.put(MediaFormat.KEY_IS_ADTS, format.getInteger(MediaFormat.KEY_IS_ADTS));
		if (format.containsKey("what"))
			map.put("what", format.getInteger("what"));
		if (format.containsKey("csd-0"))
			map.put("csd-0", asString(format.getByteBuffer("csd-0")));
		if (format.containsKey("csd-1"))
			map.put("csd-1", asString(format.getByteBuffer("csd-1")));
	} catch (JSONException e) {
		Log.e(TAG_STATIC, "writeFormat:", e);
	}

	return map.toString();
}
 
Example 18
Source File: MediaTransformer.java    From LiTr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Transform audio/video tracks using provided transformation components (source, target, decoder, etc.)
 * It is up to a client to provide component implementations that work together - for example, output of media source
 * should be in format that decoder would accept, or renderer should use OpenGL if decoder and encoder use Surface.
 *
 * If renderer has overlay(s), video track(s) will be transcoded with parameters as close to source format as possible.
 *
 * @param requestId client defined unique id for a transformation request. If not unique, {@link IllegalArgumentException} will be thrown.
 * @param mediaSource {@link MediaSource} to provide input frames
 * @param decoder {@link Decoder} to decode input frames
 * @param videoRenderer {@link Renderer} to draw (with optional filters) decoder's output frame onto encoder's input frame
 * @param encoder {@link Encoder} to encode output frames into target format
 * @param mediaTarget {@link MediaTarget} to write/mux output frames
 * @param targetVideoFormat target format parameters for video track(s), null to keep them as is
 * @param targetAudioFormat target format parameters for audio track(s), null to keep them as is
 * @param listener {@link TransformationListener} implementation, to get updates on transformation status/result/progress
 * @param granularity progress reporting granularity. NO_GRANULARITY for per-frame progress reporting,
 *                    or positive integer value for number of times transformation progress should be reported
 */
public void transform(@NonNull String requestId,
                      @NonNull MediaSource mediaSource,
                      @NonNull Decoder decoder,
                      @NonNull Renderer videoRenderer,
                      @NonNull Encoder encoder,
                      @NonNull MediaTarget mediaTarget,
                      @Nullable MediaFormat targetVideoFormat,
                      @Nullable MediaFormat targetAudioFormat,
                      @NonNull TransformationListener listener,
                      @IntRange(from = GRANULARITY_NONE) int granularity) {
    if (futureMap.containsKey(requestId)) {
        throw new IllegalArgumentException("Request with id " + requestId + " already exists");
    }

    int trackCount = mediaSource.getTrackCount();
    List<TrackTransform> trackTransforms = new ArrayList<>(trackCount);
    for (int track = 0; track < trackCount; track++) {
        MediaFormat sourceMediaFormat = mediaSource.getTrackFormat(track);
        String mimeType = null;
        if (sourceMediaFormat.containsKey(MediaFormat.KEY_MIME)) {
            mimeType = sourceMediaFormat.getString(MediaFormat.KEY_MIME);
        }

        if (mimeType == null) {
            Log.e(TAG, "Mime type is null for track " + track);
            continue;
        }

        TrackTransform.Builder trackTransformBuilder = new TrackTransform.Builder(mediaSource, track, mediaTarget)
            .setTargetTrack(track);

        if (mimeType.startsWith("video")) {
            trackTransformBuilder.setDecoder(decoder)
                                 .setRenderer(videoRenderer)
                                 .setEncoder(encoder)
                                 .setTargetFormat(targetVideoFormat);
        } else if (mimeType.startsWith("audio")) {
            trackTransformBuilder.setDecoder(decoder)
                                 .setEncoder(encoder)
                                 .setTargetFormat(targetAudioFormat);
        }

        trackTransforms.add(trackTransformBuilder.build());
    }

    transform(requestId, trackTransforms, listener, granularity);
}
 
Example 19
Source File: BaseTransformationFragment.java    From LiTr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private long getLong(@NonNull MediaFormat mediaFormat, @NonNull String key) {
    if (mediaFormat.containsKey(key)) {
        return mediaFormat.getLong(key);
    }
    return -1;
}
 
Example 20
Source File: MediaCodecBridge.java    From 365browser with Apache License 2.0 4 votes vote down vote up
private void maybeSetMaxInputSize(MediaFormat format) {
    if (format.containsKey(android.media.MediaFormat.KEY_MAX_INPUT_SIZE)) {
        // Already set. The source of the format may know better, so do nothing.
        return;
    }
    int maxHeight = format.getInteger(MediaFormat.KEY_HEIGHT);
    if (mAdaptivePlaybackSupported && format.containsKey(MediaFormat.KEY_MAX_HEIGHT)) {
        maxHeight = Math.max(maxHeight, format.getInteger(MediaFormat.KEY_MAX_HEIGHT));
    }
    int maxWidth = format.getInteger(MediaFormat.KEY_WIDTH);
    if (mAdaptivePlaybackSupported && format.containsKey(MediaFormat.KEY_MAX_WIDTH)) {
        maxWidth = Math.max(maxHeight, format.getInteger(MediaFormat.KEY_MAX_WIDTH));
    }
    int maxPixels;
    int minCompressionRatio;
    switch (format.getString(MediaFormat.KEY_MIME)) {
        case MimeTypes.VIDEO_H264:
            if ("BRAVIA 4K 2015".equals(Build.MODEL)) {
                // The Sony BRAVIA 4k TV has input buffers that are too small for the calculated
                // 4k video maximum input size, so use the default value.
                return;
            }
            // Round up width/height to an integer number of macroblocks.
            maxPixels = ((maxWidth + 15) / 16) * ((maxHeight + 15) / 16) * 16 * 16;
            minCompressionRatio = 2;
            break;
        case MimeTypes.VIDEO_VP8:
            // VPX does not specify a ratio so use the values from the platform's SoftVPX.cpp.
            maxPixels = maxWidth * maxHeight;
            minCompressionRatio = 2;
            break;
        case MimeTypes.VIDEO_H265:
        case MimeTypes.VIDEO_VP9:
            maxPixels = maxWidth * maxHeight;
            minCompressionRatio = 4;
            break;
        default:
            // Leave the default max input size.
            return;
    }
    // Estimate the maximum input size assuming three channel 4:2:0 subsampled input frames.
    int maxInputSize = (maxPixels * 3) / (2 * minCompressionRatio);
    format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, maxInputSize);
}