Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit dff71281 authored by Hangyu Kuang's avatar Hangyu Kuang Committed by Android (Google) Code Review
Browse files

Merge "transcoding: Fix the bug in openFileDescriptor and add more tests."

parents 9ebdeab7 c1b763c9
Loading
Loading
Loading
Loading
+7 −5
Original line number Diff line number Diff line
@@ -22,6 +22,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
@@ -245,10 +246,10 @@ public final class MediaTranscodeManager {

                    Uri uri = Uri.parse(fileUri);
                    try {
                        ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(uri,
                        AssetFileDescriptor afd = mContentResolver.openAssetFileDescriptor(uri,
                                mode);
                        if (pfd != null) {
                            return pfd;
                        if (afd != null) {
                            return afd.getParcelFileDescriptor();
                        }
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Cannot find content uri: " + uri, e);
@@ -411,8 +412,8 @@ public final class MediaTranscodeManager {
            // TODO(hkuang): Implement all the fields here to pass to service.
            parcel.priority = mPriority;
            parcel.transcodingType = mType;
            parcel.sourceFilePath = mSourceUri.getPath();
            parcel.destinationFilePath = mDestinationUri.getPath();
            parcel.sourceFilePath = mSourceUri.toString();
            parcel.destinationFilePath = mDestinationUri.toString();
            if (mTestConfig != null) {
                parcel.isForTesting = true;
                parcel.testConfig = mTestConfig;
@@ -441,6 +442,7 @@ public final class MediaTranscodeManager {
             * @return The same builder instance.
             * @throws IllegalArgumentException if Uri is null or empty.
             */
            // TODO(hkuang): Add documentation on how the app could generate the correct Uri.
            @NonNull
            public Builder setSourceUri(@NonNull Uri sourceUri) throws IllegalArgumentException {
                if (sourceUri == null || Uri.EMPTY.equals(sourceUri)) {
+173 −1
Original line number Diff line number Diff line
@@ -32,6 +32,7 @@ import android.media.TranscodingRequestParcel;
import android.media.TranscodingResultParcel;
import android.media.TranscodingTestConfig;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
@@ -110,6 +111,30 @@ public class MediaTranscodeManagerWithMockServiceTest
                Log.d(TAG, "Start to process job " + mJob.jobId);
                TranscodingResultParcel result = new TranscodingResultParcel();
                try {
                    // Try to open the source fd.
                    ParcelFileDescriptor sourceFd = mCallback.openFileDescriptor(
                            mJob.request.sourceFilePath, "r");
                    if (sourceFd == null) {
                        Log.d(TAG, "Failed to open sourceFd");
                        // TODO(hkuang): Pass the correct error code.
                        mCallback.onTranscodingFailed(mJob.jobId, 1);
                        return;
                    } else {
                        Log.d(TAG, "Successfully open sourceFd");
                    }

                    // Try to write to the destination fd.
                    ParcelFileDescriptor destinationFd = mCallback.openFileDescriptor(
                            mJob.request.destinationFilePath, "w");
                    if (destinationFd == null) {
                        Log.d(TAG, "Failed to open destinationFd");
                        // TODO(hkuang): Pass the correct error code.
                        mCallback.onTranscodingFailed(mJob.jobId, 1);
                        return;
                    } else {
                        Log.d(TAG, "Successfully open destinationFd");
                    }

                    mCallback.onTranscodingFinished(mJob.jobId, result);
                    // Removes the job from job map.
                    mJobMap.remove(mJob.jobId);
@@ -349,6 +374,154 @@ public class MediaTranscodeManagerWithMockServiceTest
        });
    }

    // Tests transcoding from invalid a invalid  and expects failure.
    @Test
    public void testTranscodingInvalidSrcUri() throws Exception {
        Log.d(TAG, "Starting: testMediaTranscodeManager");

        Uri invalidSrcUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + mContext.getPackageName() + "/source.mp4");
        Log.d(TAG, "Transcoding from source: " + invalidSrcUri);

        // Create a file Uri: file:///data/user/0/com.android.mediatranscodingtest/cache/temp.mp4
        // The full path of this file is:
        // /data/user/0/com.android.mediatranscodingtest/cache/temp.mp4
        Uri destinationUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + mContext.getPackageName() + "/temp.mp4");
        Log.d(TAG, "Transcoding to destination: " + destinationUri);

        Semaphore transcodeCompleteSemaphore = new Semaphore(0);
        TranscodingTestConfig testConfig = new TranscodingTestConfig();
        testConfig.passThroughMode = true;
        testConfig.processingTotalTimeMs = 300; // minimum time spent on transcoding.

        TranscodingRequest request =
                new TranscodingRequest.Builder()
                        .setSourceUri(invalidSrcUri)
                        .setDestinationUri(destinationUri)
                        .setType(MediaTranscodeManager.TRANSCODING_TYPE_VIDEO)
                        .setPriority(MediaTranscodeManager.PRIORITY_REALTIME)
                        .setVideoTrackFormat(createMediaFormat())
                        .setTestConfig(testConfig)
                        .build();
        Executor listenerExecutor = Executors.newSingleThreadExecutor();

        TranscodingJob job = mMediaTranscodeManager.enqueueRequest(request, listenerExecutor,
                transcodingJob -> {
                    Log.d(TAG, "Transcoding completed with result: " + transcodingJob.getResult());
                    assertTrue("Transcoding should failed.",
                            transcodingJob.getResult() == TranscodingJob.RESULT_ERROR);
                    transcodeCompleteSemaphore.release();
                });
        assertNotNull(job);

        if (job != null) {
            Log.d(TAG, "testMediaTranscodeManager - Waiting for transcode to complete.");
            boolean finishedOnTime = transcodeCompleteSemaphore.tryAcquire(
                    TRANSCODE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
            assertTrue("Transcode failed to complete in time.", finishedOnTime);
        }
    }


    // Tests transcoding to a uri in res folder and expects failure as we could not write to res
    // folder.
    @Test
    public void testTranscodingToResFolder() throws Exception {
        Log.d(TAG, "Starting: testMediaTranscodeManager");

        // Create a file Uri: file:///data/user/0/com.android.mediatranscodingtest/cache/temp.mp4
        // The full path of this file is:
        // /data/user/0/com.android.mediatranscodingtest/cache/temp.mp4
        Uri destinationUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + mContext.getPackageName() + "/temp.mp4");
        Log.d(TAG, "Transcoding to destination: " + destinationUri);

        Semaphore transcodeCompleteSemaphore = new Semaphore(0);
        TranscodingTestConfig testConfig = new TranscodingTestConfig();
        testConfig.passThroughMode = true;
        testConfig.processingTotalTimeMs = 300; // minimum time spent on transcoding.

        TranscodingRequest request =
                new TranscodingRequest.Builder()
                        .setSourceUri(mSourceHEVCVideoUri)
                        .setDestinationUri(destinationUri)
                        .setType(MediaTranscodeManager.TRANSCODING_TYPE_VIDEO)
                        .setPriority(MediaTranscodeManager.PRIORITY_REALTIME)
                        .setVideoTrackFormat(createMediaFormat())
                        .setTestConfig(testConfig)
                        .build();
        Executor listenerExecutor = Executors.newSingleThreadExecutor();

        TranscodingJob job = mMediaTranscodeManager.enqueueRequest(request, listenerExecutor,
                transcodingJob -> {
                    Log.d(TAG, "Transcoding completed with result: " + transcodingJob.getResult());
                    assertTrue("Transcoding should failed.",
                            transcodingJob.getResult() == TranscodingJob.RESULT_ERROR);
                    transcodeCompleteSemaphore.release();
                });
        assertNotNull(job);

        if (job != null) {
            Log.d(TAG, "testMediaTranscodeManager - Waiting for transcode to complete.");
            boolean finishedOnTime = transcodeCompleteSemaphore.tryAcquire(
                    TRANSCODE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
            assertTrue("Transcode failed to complete in time.", finishedOnTime);
        }
    }

    // Tests transcoding to a uri in internal storage folder and expects success.
    @Test
    public void testTranscodingToCacheDir() throws Exception {
        Log.d(TAG, "Starting: testMediaTranscodeManager");

        // Create a file Uri: file:///data/user/0/com.android.mediatranscodingtest/cache/temp.mp4
        // The full path of this file is:
        // /data/user/0/com.android.mediatranscodingtest/cache/temp.mp4
        Uri destinationUri = Uri.parse(ContentResolver.SCHEME_FILE + "://"
                + mContext.getCacheDir().getAbsolutePath() + "/temp.mp4");

        Semaphore transcodeCompleteSemaphore = new Semaphore(0);
        TranscodingTestConfig testConfig = new TranscodingTestConfig();
        testConfig.passThroughMode = true;
        testConfig.processingTotalTimeMs = 300; // minimum time spent on transcoding.

        TranscodingRequest request =
                new TranscodingRequest.Builder()
                        .setSourceUri(mSourceHEVCVideoUri)
                        .setDestinationUri(destinationUri)
                        .setType(MediaTranscodeManager.TRANSCODING_TYPE_VIDEO)
                        .setPriority(MediaTranscodeManager.PRIORITY_REALTIME)
                        .setVideoTrackFormat(createMediaFormat())
                        .setTestConfig(testConfig)
                        .build();
        Executor listenerExecutor = Executors.newSingleThreadExecutor();

        TranscodingJob job = mMediaTranscodeManager.enqueueRequest(request, listenerExecutor,
                transcodingJob -> {
                    Log.d(TAG, "Transcoding completed with result: " + transcodingJob.getResult());
                    assertTrue("Transcoding failed.",
                            transcodingJob.getResult() == TranscodingJob.RESULT_SUCCESS);
                    transcodeCompleteSemaphore.release();
                });
        assertNotNull(job);

        if (job != null) {
            Log.d(TAG, "testMediaTranscodeManager - Waiting for transcode to complete.");
            boolean finishedOnTime = transcodeCompleteSemaphore.tryAcquire(
                    TRANSCODE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
            assertTrue("Transcode failed to complete in time.", finishedOnTime);
        }

        // Checks the destination file get generated.
        File file = new File(destinationUri.getPath());
        assertTrue("Failed to create destination file", file.exists());

        // Removes the file.
        file.delete();
    }


    @Test
    public void testTranscodingOneVideo() throws Exception {
        Log.d(TAG, "Starting: testMediaTranscodeManager");
@@ -383,5 +556,4 @@ public class MediaTranscodeManagerWithMockServiceTest
            assertTrue("Transcode failed to complete in time.", finishedOnTime);
        }
    }

}