Search in sources :

Example 26 with Transformer

use of androidx.media3.transformer.Transformer in project knetbuilder by Rothamsted.

the class Parser method start.

public void start() throws InvalidPluginArgumentException {
    GeneralOutputEvent so = new GeneralOutputEvent("Starting PubMed/MEDLINE parser...", Parser.getCurrentMethodName());
    fireEventOccurred(so);
    XMLParser xmlParser = new XMLParser();
    Transformer writer = new Transformer(graph);
    Set<Abstract> abs = new HashSet<Abstract>();
    try {
        // Input: Directory with PubMed XML files
        if (args.getUniqueValue(FileArgumentDefinition.INPUT_FILE) != null) {
            File file = new File((String) args.getUniqueValue(FileArgumentDefinition.INPUT_FILE));
            fireEventOccurred(new GeneralOutputEvent("Start parsing file " + file.getAbsolutePath(), Parser.getCurrentMethodName()));
            abs.addAll(xmlParser.parseMedlineXML(file));
            fireEventOccurred(new GeneralOutputEvent("Number of publications found: " + abs.size(), Parser.getCurrentMethodName()));
        }
        // Input: File with integer pmids
        if (args.getUniqueValue(ArgumentNames.PMID_FILE_ARG) != null) {
            File idFile = new File((String) args.getUniqueValue(ArgumentNames.PMID_FILE_ARG));
            HashSet<String> pmidSet = new HashSet<>();
            fireEventOccurred(new GeneralOutputEvent("Retrieving PMIDs from " + "file: " + idFile.getAbsolutePath(), Parser.getCurrentMethodName()));
            BufferedReader in = new BufferedReader(new FileReader(idFile));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                inputLine = inputLine.trim();
                if (!inputLine.equals("")) {
                    // check if more than one value separated by ;
                    String[] ids = inputLine.split(" ");
                    for (String id : ids) {
                        pmidSet.add(id.trim());
                    }
                }
            }
            abs.addAll(xmlParser.parsePMIDs(pmidSet));
            in.close();
            fireEventOccurred(new GeneralOutputEvent("Number of publications found: " + pmidSet.size(), Parser.getCurrentMethodName()));
        }
        // Input: Import cited publications
        Boolean isImpOnlyCitedPub = (Boolean) args.getUniqueValue(ArgumentNames.IMP_CITED_PUB_ARG);
        if (isImpOnlyCitedPub) {
            fireEventOccurred(new GeneralOutputEvent("Retrieving PMIDs " + "cited in the Ondex graph...", Parser.getCurrentMethodName()));
            HashSet<String> pmidSet = new HashSet<String>();
            ConceptClass ccPub = graph.getMetaData().getConceptClass(MetaData.CC_PUBLICATION);
            for (ONDEXConcept c : graph.getConceptsOfConceptClass(ccPub)) {
                for (ConceptAccession accession : c.getConceptAccessions()) {
                    if (accession.getElementOf().getId().equalsIgnoreCase(MetaData.CV_NLM)) {
                        pmidSet.add(accession.getAccession());
                    }
                }
            }
            // System.out.println("pmidSet: " + pmidSet.iterator().next());
            abs.addAll(xmlParser.parsePMIDs(pmidSet));
            fireEventOccurred(new GeneralOutputEvent("Number of publications found: " + pmidSet.size(), Parser.getCurrentMethodName()));
        }
        fireEventOccurred(new GeneralOutputEvent("Adding " + abs.size() + " unique publication concepts to Ondex graph...", Parser.getCurrentMethodName()));
        writer.writeConcepts(abs);
        xmlParser = null;
        writer.cleanUp();
        writer = null;
        fireEventOccurred(new GeneralOutputEvent("Finished PubMed/MEDLINE parsing" + " with success!", Parser.getCurrentMethodName()));
    } catch (Exception e) {
        fireEventOccurred(new GeneralOutputEvent("Error: PubMed/MEDLINE import did not" + " finish! " + e.getMessage(), Parser.getCurrentMethodName()));
        e.printStackTrace();
    }
}
Also used : ConceptClass(net.sourceforge.ondex.core.ConceptClass) Transformer(net.sourceforge.ondex.parser.medline2.transformer.Transformer) Abstract(net.sourceforge.ondex.parser.medline2.sink.Abstract) ConceptAccession(net.sourceforge.ondex.core.ConceptAccession) InvalidPluginArgumentException(net.sourceforge.ondex.InvalidPluginArgumentException) ONDEXConcept(net.sourceforge.ondex.core.ONDEXConcept) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) XMLParser(net.sourceforge.ondex.parser.medline2.xml.XMLParser) GeneralOutputEvent(net.sourceforge.ondex.event.type.GeneralOutputEvent) File(java.io.File) HashSet(java.util.HashSet)

Example 27 with Transformer

use of androidx.media3.transformer.Transformer in project media by androidx.

the class TransformerActivity method createTransformer.

@RequiresNonNull({ "playerView", "debugTextView", "informationTextView", "transformationStopwatch", "progressViewGroup", "debugFrame" })
private Transformer createTransformer(@Nullable Bundle bundle, String filePath) {
    Transformer.Builder transformerBuilder = new Transformer.Builder(/* context= */
    this);
    if (bundle != null) {
        TransformationRequest.Builder requestBuilder = new TransformationRequest.Builder();
        requestBuilder.setFlattenForSlowMotion(bundle.getBoolean(ConfigurationActivity.SHOULD_FLATTEN_FOR_SLOW_MOTION));
        @Nullable String audioMimeType = bundle.getString(ConfigurationActivity.AUDIO_MIME_TYPE);
        if (audioMimeType != null) {
            requestBuilder.setAudioMimeType(audioMimeType);
        }
        @Nullable String videoMimeType = bundle.getString(ConfigurationActivity.VIDEO_MIME_TYPE);
        if (videoMimeType != null) {
            requestBuilder.setVideoMimeType(videoMimeType);
        }
        int resolutionHeight = bundle.getInt(ConfigurationActivity.RESOLUTION_HEIGHT, /* defaultValue= */
        C.LENGTH_UNSET);
        if (resolutionHeight != C.LENGTH_UNSET) {
            requestBuilder.setResolution(resolutionHeight);
        }
        Matrix transformationMatrix = getTransformationMatrix(bundle);
        if (!transformationMatrix.isIdentity()) {
            requestBuilder.setTransformationMatrix(transformationMatrix);
        }
        requestBuilder.experimental_setEnableHdrEditing(bundle.getBoolean(ConfigurationActivity.ENABLE_HDR_EDITING));
        transformerBuilder.setTransformationRequest(requestBuilder.build()).setRemoveAudio(bundle.getBoolean(ConfigurationActivity.SHOULD_REMOVE_AUDIO)).setRemoveVideo(bundle.getBoolean(ConfigurationActivity.SHOULD_REMOVE_VIDEO));
    }
    return transformerBuilder.addListener(new Transformer.Listener() {

        @Override
        public void onTransformationCompleted(MediaItem mediaItem) {
            TransformerActivity.this.onTransformationCompleted(filePath);
        }

        @Override
        public void onTransformationError(MediaItem mediaItem, TransformationException exception) {
            TransformerActivity.this.onTransformationError(exception);
        }
    }).setDebugViewProvider(new DemoDebugViewProvider()).build();
}
Also used : TransformationException(androidx.media3.transformer.TransformationException) Transformer(androidx.media3.transformer.Transformer) TransformationRequest(androidx.media3.transformer.TransformationRequest) Matrix(android.graphics.Matrix) MediaItem(androidx.media3.common.MediaItem) Nullable(androidx.annotation.Nullable) RequiresNonNull(org.checkerframework.checker.nullness.qual.RequiresNonNull)

Example 28 with Transformer

use of androidx.media3.transformer.Transformer in project media by androidx.

the class AndroidTestUtil method runTransformer.

/**
 * Transforms the {@code uriString} with the {@link Transformer}.
 *
 * @param context The {@link Context}.
 * @param testId An identifier for the test.
 * @param transformer The {@link Transformer} that performs the transformation.
 * @param uriString The uri (as a {@link String}) that will be transformed.
 * @param timeoutSeconds The transformer timeout. An assertion confirms this is not exceeded.
 * @return The {@link TransformationResult}.
 * @throws Exception The cause of the transformation not completing.
 */
public static TransformationResult runTransformer(Context context, String testId, Transformer transformer, String uriString, int timeoutSeconds) throws Exception {
    AtomicReference<@NullableType Exception> exceptionReference = new AtomicReference<>();
    CountDownLatch countDownLatch = new CountDownLatch(1);
    Transformer testTransformer = transformer.buildUpon().addListener(new Transformer.Listener() {

        @Override
        public void onTransformationCompleted(MediaItem inputMediaItem) {
            countDownLatch.countDown();
        }

        @Override
        public void onTransformationError(MediaItem inputMediaItem, TransformationException exception) {
            exceptionReference.set(exception);
            countDownLatch.countDown();
        }
    }).build();
    Uri uri = Uri.parse(uriString);
    File outputVideoFile = createExternalCacheFile(context, /* fileName= */
    testId + "-output.mp4");
    InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
        try {
            testTransformer.startTransformation(MediaItem.fromUri(uri), outputVideoFile.getAbsolutePath());
        } catch (IOException e) {
            exceptionReference.set(e);
        }
    });
    assertWithMessage("Transformer timed out after " + timeoutSeconds + " seconds.").that(countDownLatch.await(timeoutSeconds, SECONDS)).isTrue();
    @Nullable Exception exception = exceptionReference.get();
    if (exception != null) {
        throw exception;
    }
    TransformationResult result = new TransformationResult.Builder(testId).setFileSizeBytes(outputVideoFile.length()).build();
    writeTransformationResultToFile(context, result);
    return result;
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Uri(android.net.Uri) IOException(java.io.IOException) MediaItem(androidx.media3.common.MediaItem) File(java.io.File) Nullable(androidx.annotation.Nullable)

Example 29 with Transformer

use of androidx.media3.transformer.Transformer in project media by androidx.

the class TransformerEndToEndTest method startTransformation_withIoError_completesWithError.

@Test
public void startTransformation_withIoError_completesWithError() throws Exception {
    Transformer transformer = createTransformerBuilder().build();
    MediaItem mediaItem = MediaItem.fromUri("asset:///non-existing-path.mp4");
    transformer.startTransformation(mediaItem, outputPath);
    TransformationException exception = TransformerTestRunner.runUntilError(transformer);
    assertThat(exception).hasCauseThat().hasCauseThat().isInstanceOf(IOException.class);
    assertThat(exception.errorCode).isEqualTo(TransformationException.ERROR_CODE_IO_FILE_NOT_FOUND);
}
Also used : MediaItem(androidx.media3.common.MediaItem) Test(org.junit.Test)

Example 30 with Transformer

use of androidx.media3.transformer.Transformer in project media by androidx.

the class TransformerEndToEndTest method startTransformation_fromSpecifiedThread_completesSuccessfully.

@Test
public void startTransformation_fromSpecifiedThread_completesSuccessfully() throws Exception {
    HandlerThread anotherThread = new HandlerThread("AnotherThread");
    anotherThread.start();
    Looper looper = anotherThread.getLooper();
    Transformer transformer = createTransformerBuilder().setLooper(looper).build();
    MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_AUDIO_VIDEO);
    AtomicReference<Exception> exception = new AtomicReference<>();
    CountDownLatch countDownLatch = new CountDownLatch(1);
    new Handler(looper).post(() -> {
        try {
            transformer.startTransformation(mediaItem, outputPath);
            TransformerTestRunner.runUntilCompleted(transformer);
        } catch (Exception e) {
            exception.set(e);
        } finally {
            countDownLatch.countDown();
        }
    });
    countDownLatch.await();
    assertThat(exception.get()).isNull();
    DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_AUDIO_VIDEO));
}
Also used : Looper(android.os.Looper) HandlerThread(android.os.HandlerThread) MediaItem(androidx.media3.common.MediaItem) Handler(android.os.Handler) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)45 MediaItem (androidx.media3.common.MediaItem)29 Context (android.content.Context)18 AndroidTestUtil.runTransformer (androidx.media3.transformer.AndroidTestUtil.runTransformer)10 Transformer (androidx.media3.transformer.Transformer)10 Transformer (com.google.android.exoplayer2.transformer.Transformer)10 Matrix (android.graphics.Matrix)9 AndroidTestUtil.runTransformer (com.google.android.exoplayer2.transformer.AndroidTestUtil.runTransformer)8 Handler (android.os.Handler)7 HashSet (java.util.HashSet)7 Nullable (androidx.annotation.Nullable)5 IOException (java.io.IOException)5 RequiresNonNull (org.checkerframework.checker.nullness.qual.RequiresNonNull)4 Uri (android.net.Uri)3 Message (android.os.Message)3 AndroidTestUtil (androidx.media3.transformer.AndroidTestUtil)3 AndroidTestUtil (com.google.android.exoplayer2.transformer.AndroidTestUtil)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3