Search in sources :

Example 21 with TrackImpl

use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.

the class EventsEndpoint method getEventMedia.

@GET
@Path("{eventId}/media")
@Produces({ "application/json", "application/v1.0.0+json" })
public Response getEventMedia(@HeaderParam("Accept") String acceptHeader, @PathParam("eventId") String id) throws Exception {
    ArrayList<TrackImpl> tracks = new ArrayList<>();
    for (final Event event : indexService.getEvent(id, externalIndex)) {
        final MediaPackage mp = indexService.getEventMediapackage(event);
        for (Track track : mp.getTracks()) {
            if (track instanceof TrackImpl) {
                tracks.add((TrackImpl) track);
            }
        }
        List<JValue> tracksJson = new ArrayList<>();
        for (Track track : tracks) {
            List<Field> fields = new ArrayList<>();
            if (track.getChecksum() != null)
                fields.add(f("checksum", v(track.getChecksum().toString())));
            if (track.getDescription() != null)
                fields.add(f("description", v(track.getDescription())));
            if (track.getDuration() != null)
                fields.add(f("duration", v(track.getDuration())));
            if (track.getElementDescription() != null)
                fields.add(f("element-description", v(track.getElementDescription())));
            if (track.getFlavor() != null)
                fields.add(f("flavor", v(track.getFlavor().toString())));
            if (track.getIdentifier() != null)
                fields.add(f("identifier", v(track.getIdentifier())));
            if (track.getMimeType() != null)
                fields.add(f("identifier", v(track.getMimeType().toString())));
            fields.add(f("size", v(track.getSize())));
            if (track.getStreams() != null) {
                List<Field> streams = new ArrayList<>();
                for (Stream stream : track.getStreams()) {
                    streams.add(f(stream.getIdentifier(), getJsonStream(stream)));
                }
                fields.add(f("streams", obj(streams)));
            }
            if (track.getTags() != null) {
                List<JValue> tags = new ArrayList<>();
                for (String tag : track.getTags()) {
                    tags.add(v(tag));
                }
                fields.add(f("tags", arr(tags)));
            }
            if (track.getURI() != null)
                fields.add(f("uri", v(track.getURI().toString())));
            tracksJson.add(obj(fields));
        }
        return ApiResponses.Json.ok(ApiVersion.VERSION_1_0_0, arr(tracksJson));
    }
    return ApiResponses.notFound("Cannot find an event with id '%s'.", id);
}
Also used : Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) AudioStream(org.opencastproject.mediapackage.AudioStream) Stream(org.opencastproject.mediapackage.Stream) VideoStream(org.opencastproject.mediapackage.VideoStream) Track(org.opencastproject.mediapackage.Track) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 22 with TrackImpl

use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.

the class AbstractFeedGenerator method populateFeedEntry.

/**
 * Populates the feed entry with metadata and the enclosures.
 *
 * @param entry
 *          the entry to enrich
 * @param metadata
 *          the metadata
 * @param enclosures
 *          the media enclosures
 * @return the enriched item
 */
private FeedEntry populateFeedEntry(FeedEntry entry, SearchResultItem metadata, List<MediaPackageElement> enclosures) {
    Date d = metadata.getDcCreated();
    Date updatedDate = metadata.getModified();
    String title = metadata.getDcTitle();
    // Configure the iTunes extension
    ITunesFeedEntryExtension iTunesEntry = new ITunesFeedEntryExtension();
    iTunesEntry.setDuration(metadata.getDcExtent());
    iTunesEntry.setBlocked(false);
    iTunesEntry.setExplicit(false);
    if (StringUtils.isNotBlank(metadata.getDcCreator()))
        iTunesEntry.setAuthor(metadata.getDcCreator());
    // TODO: Add iTunes keywords and subtitles
    // iTunesEntry.setKeywords(keywords);
    // iTunesEntry.setSubtitle(subtitle);
    // Configure the DC extension
    DublinCoreExtension dcExtension = new DublinCoreExtension();
    dcExtension.setTitle(title);
    dcExtension.setIdentifier(metadata.getId());
    // Set contributor
    if (!StringUtils.isEmpty(metadata.getDcContributor())) {
        for (String contributor : metadata.getDcContributor().split(";;")) {
            entry.addContributor(new PersonImpl(contributor));
            dcExtension.addContributor(contributor);
        }
    }
    // Set creator
    if (!StringUtils.isEmpty(metadata.getDcCreator())) {
        for (String creator : metadata.getDcCreator().split(";;")) {
            if (iTunesEntry.getAuthor() == null)
                iTunesEntry.setAuthor(creator);
            entry.addAuthor(new PersonImpl(creator));
            dcExtension.addCreator(creator);
        }
    }
    // Set publisher
    if (!StringUtils.isEmpty(metadata.getDcPublisher())) {
        dcExtension.addPublisher(metadata.getDcPublisher());
    }
    // Set rights
    if (!StringUtils.isEmpty(metadata.getDcAccessRights())) {
        dcExtension.setRights(metadata.getDcAccessRights());
    }
    // Set description
    if (!StringUtils.isEmpty(metadata.getDcDescription())) {
        String summary = metadata.getDcDescription();
        entry.setDescription(new ContentImpl(summary));
        iTunesEntry.setSummary(summary);
        dcExtension.setDescription(summary);
    }
    // Set the language
    if (!StringUtils.isEmpty(metadata.getDcLanguage())) {
        dcExtension.setLanguage(metadata.getDcLanguage());
    }
    // Set the publication date
    if (d != null) {
        entry.setPublishedDate(d);
        dcExtension.setDate(d);
    } else if (metadata.getModified() != null) {
        entry.setPublishedDate(metadata.getModified());
        dcExtension.setDate(metadata.getModified());
    }
    // Set the updated date
    if (updatedDate == null)
        updatedDate = d;
    entry.setUpdatedDate(updatedDate);
    // TODO: Finish dc support
    // Set format
    // if (!StringUtils.isEmpty(resultItem.getMediaType())) {
    // dcExtension.setFormat(resultItem.getMediaType());
    // }
    // dcEntry.setCoverage(arg0);
    // dcEntry.setRelation(arg0);
    // dcEntry.setSource(arg0);
    // dcEntry.setSubject(arg0);
    // Set the cover image
    String coverUrl = null;
    if (!StringUtils.isEmpty(metadata.getCover())) {
        coverUrl = metadata.getCover();
        setImage(entry, coverUrl);
    }
    entry.addExtension(iTunesEntry);
    entry.addExtension(dcExtension);
    // Add the enclosures
    for (MediaPackageElement element : enclosures) {
        String trackMimeType = element.getMimeType().toString();
        long trackLength = element.getSize();
        if (trackLength <= 0 && element instanceof Track) {
            // filesize unset so estimate from duration and bitrate
            trackLength = 0;
            if (((TrackImpl) element).hasVideo()) {
                List<VideoStream> video = ((TrackImpl) element).getVideo();
                if (video.get(0).getBitRate() != null) {
                    trackLength += metadata.getDcExtent() / 1000 * video.get(0).getBitRate() / 8;
                }
            }
            if (((TrackImpl) element).hasAudio()) {
                List<AudioStream> audio = ((TrackImpl) element).getAudio();
                if (audio.get(0).getBitRate() != null) {
                    trackLength += metadata.getDcExtent() / 1000 * audio.get(0).getBitRate() / 8;
                }
            }
        }
        // order of magnitude correct
        if (trackLength <= 0) {
            trackLength = metadata.getDcExtent();
        }
        String trackFlavor = element.getFlavor().toString();
        String trackUrl = null;
        try {
            trackUrl = element.getURI().toURL().toExternalForm();
        } catch (MalformedURLException e) {
        // Can't happen
        }
        Enclosure enclosure = new EnclosureImpl(trackUrl, trackMimeType, trackFlavor, trackLength);
        entry.addEnclosure(enclosure);
    }
    return entry;
}
Also used : MalformedURLException(java.net.MalformedURLException) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) VideoStream(org.opencastproject.mediapackage.VideoStream) Enclosure(org.opencastproject.feed.api.Enclosure) Date(java.util.Date) AudioStream(org.opencastproject.mediapackage.AudioStream) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) Track(org.opencastproject.mediapackage.Track)

Example 23 with TrackImpl

use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.

the class ProbeResolutionWorkflowOperationHandler method start.

@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
    logger.info("Running probe-resolution workflow operation");
    final MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    final String sourceFlavorName = getConfig(workflowInstance, OPT_SOURCE_FLAVOR);
    final MediaPackageElementFlavor sourceFlavor = MediaPackageElementFlavor.parseFlavor(sourceFlavorName);
    // Ensure we have a matching track
    final Track[] tracks = mediaPackage.getTracks(sourceFlavor);
    if (tracks.length <= 0) {
        logger.info("No tracks with specified flavor ({}).", sourceFlavorName);
        return createResult(mediaPackage, Action.CONTINUE);
    }
    // Create mapping:  resolution -> [varNames]
    Map<Fraction, Set<String>> resolutionMapping = new HashMap<>();
    for (String key : workflowInstance.getCurrentOperation().getConfigurationKeys()) {
        if (key.startsWith(OPT_VAR_PREFIX)) {
            String varName = key.substring(OPT_VAR_PREFIX.length());
            for (Fraction resolution : getResolutions(getConfig(workflowInstance, key))) {
                if (!resolutionMapping.containsKey(resolution)) {
                    resolutionMapping.put(resolution, new HashSet<String>());
                }
                resolutionMapping.get(resolution).add(varName);
            }
        }
    }
    // Create mapping:  varName -> value
    Map<String, String> valueMapping = new HashMap<>();
    for (String key : workflowInstance.getCurrentOperation().getConfigurationKeys()) {
        if (key.startsWith(OPT_VAL_PREFIX)) {
            String varName = key.substring(OPT_VAL_PREFIX.length());
            valueMapping.put(varName, getConfig(workflowInstance, key));
        }
    }
    Map<String, String> properties = new HashMap<String, String>();
    for (Track track : tracks) {
        final String flavor = toVariableName(track.getFlavor());
        // Check if resolution fits
        if (track.hasVideo()) {
            for (VideoStream video : ((TrackImpl) track).getVideo()) {
                Fraction resolution = Fraction.getFraction(video.getFrameWidth(), video.getFrameHeight());
                if (resolutionMapping.containsKey(resolution)) {
                    for (String varName : resolutionMapping.get(resolution)) {
                        String value = valueMapping.containsKey(varName) ? valueMapping.get(varName) : "true";
                        properties.put(flavor + varName, value);
                    }
                }
            }
        }
    }
    logger.info("Finished workflow operation adding the properties: {}", properties);
    return createResult(mediaPackage, properties, Action.CONTINUE, 0);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) VideoStream(org.opencastproject.mediapackage.VideoStream) Fraction(org.apache.commons.lang3.math.Fraction) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Track(org.opencastproject.mediapackage.Track)

Example 24 with TrackImpl

use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.

the class AnalyzeTracksWorkflowOperationHandlerTest method testStart.

@Test
public void testStart() throws MediaPackageException, WorkflowOperationException {
    MediaPackage mediaPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().createNew();
    VideoStreamImpl videoStream = new VideoStreamImpl("234");
    videoStream.setFrameWidth(1280);
    videoStream.setFrameHeight(720);
    videoStream.setFrameRate(30.0f);
    TrackImpl track = new TrackImpl();
    track.setFlavor(MediaPackageElementFlavor.parseFlavor("presenter/source"));
    track.addStream(videoStream);
    JobContext jobContext = EasyMock.createMock(JobContext.class);
    EasyMock.replay(jobContext);
    WorkflowOperationInstance operationInstance = EasyMock.createMock(WorkflowOperationInstance.class);
    String[][] config = { { AnalyzeTracksWorkflowOperationHandler.OPT_SOURCE_FLAVOR, "*/source" }, { AnalyzeTracksWorkflowOperationHandler.OPT_VIDEO_ASPECT, "4/3,16/9" } };
    for (String[] cfg : config) {
        EasyMock.expect(operationInstance.getConfiguration(cfg[0])).andReturn(cfg[1]).anyTimes();
    }
    EasyMock.expect(operationInstance.getConfiguration(AnalyzeTracksWorkflowOperationHandler.OPT_FAIL_NO_TRACK)).andReturn("true");
    EasyMock.expect(operationInstance.getConfiguration(AnalyzeTracksWorkflowOperationHandler.OPT_FAIL_NO_TRACK)).andReturn("false").anyTimes();
    EasyMock.replay(operationInstance);
    WorkflowInstance workflowInstance = EasyMock.createMock(WorkflowInstance.class);
    EasyMock.expect(workflowInstance.getMediaPackage()).andReturn(mediaPackage).anyTimes();
    EasyMock.expect(workflowInstance.getId()).andReturn(0L).anyTimes();
    EasyMock.expect(workflowInstance.getCurrentOperation()).andReturn(operationInstance).anyTimes();
    EasyMock.replay(workflowInstance);
    // With no matching track (should fail)
    try {
        operationHandler.start(workflowInstance, jobContext);
        fail();
    } catch (WorkflowOperationException e) {
        logger.info("Fail on no tracks works");
    }
    WorkflowOperationResult workflowOperationResult = operationHandler.start(workflowInstance, jobContext);
    Map<String, String> properties = workflowOperationResult.getProperties();
    assertTrue(properties.isEmpty());
    // With matching track
    mediaPackage.add(track);
    workflowOperationResult = operationHandler.start(workflowInstance, jobContext);
    properties = workflowOperationResult.getProperties();
    String[][] props = { { "presenter_source_media", "true" }, { "presenter_source_audio", "false" }, { "presenter_source_aspect", "16/9" }, { "presenter_source_resolution_y", "720" }, { "presenter_source_resolution_x", "1280" }, { "presenter_source_aspect_snap", "16/9" }, { "presenter_source_video", "true" }, { "presenter_source_framerate", "30.0" } };
    for (String[] prop : props) {
        assertEquals(prop[1], properties.get(prop[0]));
    }
}
Also used : WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) MediaPackage(org.opencastproject.mediapackage.MediaPackage) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) VideoStreamImpl(org.opencastproject.mediapackage.track.VideoStreamImpl) JobContext(org.opencastproject.job.api.JobContext) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) WorkflowOperationResult(org.opencastproject.workflow.api.WorkflowOperationResult) Test(org.junit.Test)

Example 25 with TrackImpl

use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.

the class TrackBuilderPlugin method elementFromManifest.

/**
 * @see org.opencastproject.mediapackage.elementbuilder.MediaPackageElementBuilderPlugin#elementFromManifest(org.w3c.dom.Node,
 *      org.opencastproject.mediapackage.MediaPackageSerializer)
 */
@Override
public MediaPackageElement elementFromManifest(Node elementNode, MediaPackageSerializer serializer) throws UnsupportedElementException {
    String id = null;
    MimeType mimeType = null;
    MediaPackageElementFlavor flavor = null;
    TrackImpl.StreamingProtocol transport = null;
    String reference = null;
    URI url = null;
    long size = -1;
    Checksum checksum = null;
    try {
        // id
        id = (String) xpath.evaluate("@id", elementNode, XPathConstants.STRING);
        // url
        url = serializer.decodeURI(new URI(xpath.evaluate("url/text()", elementNode).trim()));
        // reference
        reference = (String) xpath.evaluate("@ref", elementNode, XPathConstants.STRING);
        // size
        String trackSize = xpath.evaluate("size/text()", elementNode).trim();
        if (!"".equals(trackSize))
            size = Long.parseLong(trackSize);
        // flavor
        String flavorValue = (String) xpath.evaluate("@type", elementNode, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(flavorValue))
            flavor = MediaPackageElementFlavor.parseFlavor(flavorValue);
        // transport
        String transportValue = (String) xpath.evaluate("@transport", elementNode, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(transportValue))
            transport = TrackImpl.StreamingProtocol.valueOf(transportValue);
        // checksum
        String checksumValue = (String) xpath.evaluate("checksum/text()", elementNode, XPathConstants.STRING);
        String checksumType = (String) xpath.evaluate("checksum/@type", elementNode, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(checksumValue) && checksumType != null)
            checksum = Checksum.create(checksumType.trim(), checksumValue.trim());
        // mimetype
        String mimeTypeValue = (String) xpath.evaluate("mimetype/text()", elementNode, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(mimeTypeValue))
            mimeType = MimeTypes.parseMimeType(mimeTypeValue);
        // 
        // Build the track
        TrackImpl track = TrackImpl.fromURI(url);
        if (StringUtils.isNotBlank(id))
            track.setIdentifier(id);
        // Add url
        track.setURI(url);
        // Add reference
        if (StringUtils.isNotEmpty(reference))
            track.referTo(MediaPackageReferenceImpl.fromString(reference));
        // Set size
        if (size > 0)
            track.setSize(size);
        // Set checksum
        if (checksum != null)
            track.setChecksum(checksum);
        // Set mimetpye
        if (mimeType != null)
            track.setMimeType(mimeType);
        if (flavor != null)
            track.setFlavor(flavor);
        // set transport
        if (transport != null)
            track.setTransport(transport);
        // description
        String description = (String) xpath.evaluate("description/text()", elementNode, XPathConstants.STRING);
        if (StringUtils.isNotBlank(description))
            track.setElementDescription(description.trim());
        // tags
        NodeList tagNodes = (NodeList) xpath.evaluate("tags/tag", elementNode, XPathConstants.NODESET);
        for (int i = 0; i < tagNodes.getLength(); i++) {
            track.addTag(tagNodes.item(i).getTextContent());
        }
        // duration
        try {
            String strDuration = (String) xpath.evaluate("duration/text()", elementNode, XPathConstants.STRING);
            if (StringUtils.isNotEmpty(strDuration)) {
                long duration = Long.parseLong(strDuration.trim());
                track.setDuration(duration);
            }
        } catch (NumberFormatException e) {
            throw new UnsupportedElementException("Duration of track " + url + " is malformatted");
        }
        // is live
        String strLive = (String) xpath.evaluate("live/text()", elementNode, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(strLive)) {
            boolean live = Boolean.parseBoolean(strLive.trim());
            track.setLive(live);
        }
        // audio settings
        Node audioSettingsNode = (Node) xpath.evaluate("audio", elementNode, XPathConstants.NODE);
        if (audioSettingsNode != null && audioSettingsNode.hasChildNodes()) {
            try {
                AudioStreamImpl as = AudioStreamImpl.fromManifest(createStreamID(track), audioSettingsNode, xpath);
                track.addStream(as);
            } catch (IllegalStateException e) {
                throw new UnsupportedElementException("Illegal state encountered while reading audio settings from " + url + ": " + e.getMessage());
            } catch (XPathException e) {
                throw new UnsupportedElementException("Error while parsing audio settings from " + url + ": " + e.getMessage());
            }
        }
        // video settings
        Node videoSettingsNode = (Node) xpath.evaluate("video", elementNode, XPathConstants.NODE);
        if (videoSettingsNode != null && videoSettingsNode.hasChildNodes()) {
            try {
                VideoStreamImpl vs = VideoStreamImpl.fromManifest(createStreamID(track), videoSettingsNode, xpath);
                track.addStream(vs);
            } catch (IllegalStateException e) {
                throw new UnsupportedElementException("Illegal state encountered while reading video settings from " + url + ": " + e.getMessage());
            } catch (XPathException e) {
                throw new UnsupportedElementException("Error while parsing video settings from " + url + ": " + e.getMessage());
            }
        }
        return track;
    } catch (XPathExpressionException e) {
        throw new UnsupportedElementException("Error while reading track information from manifest: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new UnsupportedElementException("Unsupported digest algorithm: " + e.getMessage());
    } catch (URISyntaxException e) {
        throw new UnsupportedElementException("Error while reading presenter track " + url + ": " + e.getMessage());
    }
}
Also used : XPathException(javax.xml.xpath.XPathException) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) AudioStreamImpl(org.opencastproject.mediapackage.track.AudioStreamImpl) VideoStreamImpl(org.opencastproject.mediapackage.track.VideoStreamImpl) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URISyntaxException(java.net.URISyntaxException) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) URI(java.net.URI) MimeType(org.opencastproject.util.MimeType) UnsupportedElementException(org.opencastproject.mediapackage.UnsupportedElementException) Checksum(org.opencastproject.util.Checksum)

Aggregations

TrackImpl (org.opencastproject.mediapackage.track.TrackImpl)42 Test (org.junit.Test)21 Track (org.opencastproject.mediapackage.Track)20 MediaPackageElementFlavor (org.opencastproject.mediapackage.MediaPackageElementFlavor)17 URI (java.net.URI)14 MediaPackage (org.opencastproject.mediapackage.MediaPackage)13 VideoStreamImpl (org.opencastproject.mediapackage.track.VideoStreamImpl)12 WorkflowOperationResult (org.opencastproject.workflow.api.WorkflowOperationResult)11 Job (org.opencastproject.job.api.Job)9 ArrayList (java.util.ArrayList)7 AudioStream (org.opencastproject.mediapackage.AudioStream)7 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)7 File (java.io.File)6 IOException (java.io.IOException)6 HashMap (java.util.HashMap)6 VideoStream (org.opencastproject.mediapackage.VideoStream)6 InputStream (java.io.InputStream)5 SmilResponse (org.opencastproject.smil.api.SmilResponse)5 NotFoundException (org.opencastproject.util.NotFoundException)5 FileInputStream (java.io.FileInputStream)4