use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.
the class MediaPackageJaxbSerializationTest method testJaxbSerialization.
@Test
public void testJaxbSerialization() throws Exception {
// Build a media package
MediaPackageElementBuilder elementBuilder = MediaPackageElementBuilderFactory.newInstance().newElementBuilder();
MediaPackage mp = new MediaPackageImpl(new IdImpl("123"));
Attachment attachment = (Attachment) elementBuilder.elementFromURI(new URI("http://opencastproject.org/index.html"), Type.Attachment, Attachment.FLAVOR);
attachment.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, "123456abcd"));
mp.add(attachment);
Catalog cat1 = (Catalog) elementBuilder.elementFromURI(new URI("http://opencastproject.org/index.html"), Catalog.TYPE, MediaPackageElements.EPISODE);
cat1.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, "7891011abcd"));
mp.add(cat1);
Catalog cat2 = (Catalog) elementBuilder.elementFromURI(new URI("http://opencastproject.org/index.html"), Catalog.TYPE, MediaPackageElements.EPISODE);
cat2.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, "7891011abcd"));
mp.addDerived(cat2, cat1);
TrackImpl track = (TrackImpl) elementBuilder.elementFromURI(new URI("http://opencastproject.org/video.mpg"), Track.TYPE, MediaPackageElements.PRESENTER_SOURCE);
track.addStream(new VideoStreamImpl("video-stream-1"));
track.addStream(new VideoStreamImpl("video-stream-2"));
mp.add(track);
// Serialize the media package
String xml = MediaPackageParser.getAsXml(mp);
assertNotNull(xml);
// Serialize the media package as JSON
String json = MediaPackageParser.getAsJSON(mp);
assertNotNull(json);
// Deserialize the media package
MediaPackage deserialized = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(IOUtils.toInputStream(xml, "UTF-8"));
// Ensure that the deserialized mediapackage is correct
assertEquals(2, deserialized.getCatalogs().length);
assertEquals(1, deserialized.getAttachments().length);
assertEquals(1, deserialized.getTracks().length);
assertEquals(2, deserialized.getTracks()[0].getStreams().length);
assertEquals(1, deserialized.getCatalogs(new MediaPackageReferenceImpl(cat1)).length);
}
use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.
the class LiveScheduleServiceImplTest method testIsSameMediaPackageFalse.
@Test
public void testIsSameMediaPackageFalse() throws Exception {
URI mpURI = LiveScheduleServiceImplTest.class.getResource("/assetmanager-mp.xml").toURI();
MediaPackage mp = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(mpURI.toURL().openStream());
setUpAssetManager(mp);
replayServices();
MediaPackage mp1 = (MediaPackage) service.getSnapshot(MP_ID).getMediaPackage().clone();
mp1.setDuration(DURATION);
service.addLiveTracks(mp1, CAPTURE_AGENT_NAME);
MediaPackage mp2 = (MediaPackage) service.getSnapshot(MP_ID).getMediaPackage().clone();
mp2.setDuration(DURATION);
service.addLiveTracks(mp2, CAPTURE_AGENT_NAME);
// Change title
String previous = mp2.getTitle();
mp2.setTitle("Changed");
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.setTitle(previous);
// Change language
previous = mp2.getLanguage();
mp2.setLanguage("Changed");
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.setLanguage(previous);
// Change series
previous = mp2.getSeries();
mp2.setSeries("Changed");
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.setSeries(previous);
// Change series title
previous = mp2.getSeriesTitle();
mp2.setSeriesTitle("Changed");
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.setSeriesTitle(previous);
// Change date
Date dt = mp2.getDate();
mp2.setDate(new Date());
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.setDate(dt);
// Change creators
mp2.addCreator("New object");
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.removeCreator("New object");
// Change contributors
mp2.addContributor("New object");
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.removeContributor("New object");
// Change subjects
mp2.addSubject("New object");
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.removeSubject("New object");
// Change track uri
Track track = mp2.getTracks()[0];
URI previousURI = track.getURI();
track.setURI(new URI("http://new.url.com"));
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
track.setURI(previousURI);
// Change duration
long duration = mp2.getDuration();
for (Track t : mp2.getTracks()) {
((TrackImpl) t).setDuration(1L);
}
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
for (Track t : mp2.getTracks()) {
((TrackImpl) t).setDuration(duration);
}
// Change number of tracks
track = (Track) mp2.getTracks()[0].clone();
mp2.remove(track);
Assert.assertFalse(service.isSameMediaPackage(mp1, mp2));
mp2.add(track);
}
use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.
the class MediaInspector method inspectTrack.
/**
* Inspects the element that is passed in as uri.
*
* @param trackURI
* the element uri
* @return the inspected track
* @throws org.opencastproject.inspection.api.MediaInspectionException
* if inspection fails
*/
public Track inspectTrack(URI trackURI, Map<String, String> options) throws MediaInspectionException {
logger.debug("inspect(" + trackURI + ") called, using workspace " + workspace);
throwExceptionIfInvalid(options);
try {
// Get the file from the URL (runtime exception if invalid)
File file = null;
try {
file = workspace.get(trackURI);
} catch (NotFoundException notFound) {
throw new MediaInspectionException("Unable to find resource " + trackURI, notFound);
} catch (IOException ioe) {
throw new MediaInspectionException("Error reading " + trackURI + " from workspace", ioe);
}
// TODO: Try to guess the extension from the container's metadata
if ("".equals(FilenameUtils.getExtension(file.getName()))) {
throw new MediaInspectionException("Can not inspect files without a filename extension");
}
MediaContainerMetadata metadata = getFileMetadata(file, getAccurateFrameCount(options));
if (metadata == null) {
throw new MediaInspectionException("Media analyzer returned no metadata from " + file);
} else {
MediaPackageElementBuilder elementBuilder = MediaPackageElementBuilderFactory.newInstance().newElementBuilder();
TrackImpl track;
MediaPackageElement element;
try {
element = elementBuilder.elementFromURI(trackURI, MediaPackageElement.Type.Track, null);
} catch (UnsupportedElementException e) {
throw new MediaInspectionException("Unable to create track element from " + file, e);
}
track = (TrackImpl) element;
// Duration
if (metadata.getDuration() != null && metadata.getDuration() > 0)
track.setDuration(metadata.getDuration());
// Checksum
try {
track.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, file));
} catch (IOException e) {
throw new MediaInspectionException("Unable to read " + file, e);
}
// Mimetype
InputStream is = null;
try {
// Try to get the Mimetype from Apache Tika
is = new FileInputStream(file);
MimeType mimeType = extractContentType(is);
// If Mimetype could not be extracted try to get it from opencast
if (mimeType == null) {
mimeType = MimeTypes.fromURL(file.toURI().toURL());
// The mimetype library doesn't know about audio/video metadata, so the type might be wrong.
if ("audio".equals(mimeType.getType()) && metadata.hasVideoStreamMetadata()) {
mimeType = MimeTypes.parseMimeType("video/" + mimeType.getSubtype());
} else if ("video".equals(mimeType.getType()) && !metadata.hasVideoStreamMetadata()) {
mimeType = MimeTypes.parseMimeType("audio/" + mimeType.getSubtype());
}
}
track.setMimeType(mimeType);
} catch (Exception e) {
logger.error("Unable to find mimetype for {}", file.getAbsolutePath());
} finally {
IoSupport.closeQuietly(is);
}
// Audio metadata
try {
addAudioStreamMetadata(track, metadata);
} catch (Exception e) {
throw new MediaInspectionException("Unable to extract audio metadata from " + file, e);
}
// Videometadata
try {
addVideoStreamMetadata(track, metadata);
} catch (Exception e) {
throw new MediaInspectionException("Unable to extract video metadata from " + file, e);
}
return track;
}
} catch (Exception e) {
logger.warn("Error inspecting " + trackURI, e);
if (e instanceof MediaInspectionException) {
throw (MediaInspectionException) e;
} else {
throw new MediaInspectionException(e);
}
}
}
use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.
the class StreamingDistributionServiceImpl method distributeElement.
/**
* Distribute a Mediapackage element to the download distribution service.
*
* @param mp
* The media package that contains the element to distribute.
* @param mpeId
* The id of the element that should be distributed contained within the media package.
* @return A reference to the MediaPackageElement that has been distributed.
* @throws DistributionException
* Thrown if the parent directory of the MediaPackageElement cannot be created, if the MediaPackageElement
* cannot be copied or another unexpected exception occurs.
*/
private MediaPackageElement distributeElement(String channelId, final MediaPackage mp, String mpeId) throws DistributionException {
RequireUtil.notNull(channelId, "channelId");
RequireUtil.notNull(mp, "mp");
RequireUtil.notNull(mpeId, "mpeId");
//
final MediaPackageElement element = mp.getElementById(mpeId);
// Make sure the element exists
if (element == null) {
throw new IllegalStateException("No element " + mpeId + " found in media package");
}
try {
File source;
try {
source = workspace.get(element.getURI());
} catch (NotFoundException e) {
throw new DistributionException("Unable to find " + element.getURI() + " in the workspace", e);
} catch (IOException e) {
throw new DistributionException("Error loading " + element.getURI() + " from the workspace", e);
}
// Try to find a duplicated element source
try {
source = findDuplicatedElementSource(source, mp.getIdentifier().compact());
} catch (IOException e) {
logger.warn("Unable to find duplicated source {}: {}", source, ExceptionUtils.getMessage(e));
}
final File destination = locations.get().createDistributionFile(securityService.getOrganization().getId(), channelId, mp.getIdentifier().compact(), element.getIdentifier(), element.getURI());
if (!destination.equals(source)) {
// Put the file in place if sourcesfile differs destinationfile
try {
FileUtils.forceMkdir(destination.getParentFile());
} catch (IOException e) {
throw new DistributionException("Unable to create " + destination.getParentFile(), e);
}
logger.info("Distributing {} to {}", mpeId, destination);
try {
FileSupport.link(source, destination, true);
} catch (IOException e) {
throw new DistributionException("Unable to copy " + source + " to " + destination, e);
}
}
// Create a representation of the distributed file in the mediapackage
final MediaPackageElement distributedElement = (MediaPackageElement) element.clone();
distributedElement.setURI(locations.get().createDistributionUri(securityService.getOrganization().getId(), channelId, mp.getIdentifier().compact(), element.getIdentifier(), element.getURI()));
distributedElement.setIdentifier(null);
((TrackImpl) distributedElement).setTransport(TrackImpl.StreamingProtocol.RTMP);
logger.info("Finished distribution of {}", element);
return distributedElement;
} catch (Exception e) {
logger.warn("Error distributing " + element, e);
if (e instanceof DistributionException) {
throw (DistributionException) e;
} else {
throw new DistributionException(e);
}
}
}
use of org.opencastproject.mediapackage.track.TrackImpl in project opencast by opencast.
the class WowzaAdaptiveStreamingDistributionService method addElementToSmil.
private void addElementToSmil(Document doc, String channelId, MediaPackage mediapackage, MediaPackageElement element) throws DOMException, URISyntaxException {
if (!(element instanceof TrackImpl))
return;
TrackImpl track = (TrackImpl) element;
NodeList switchElementsList = doc.getElementsByTagName("switch");
Node switchElement = null;
// If there is no switch element we need to create the xml first.
if (switchElementsList.getLength() > 0) {
switchElement = switchElementsList.item(0);
} else {
if (doc.getElementsByTagName("head").getLength() < 1)
doc.appendChild(doc.createElement("head"));
if (doc.getElementsByTagName("body").getLength() < 1)
doc.appendChild(doc.createElement("body"));
switchElement = doc.createElement("switch");
doc.getElementsByTagName("body").item(0).appendChild(switchElement);
}
Element video = doc.createElement("video");
video.setAttribute("src", getAdaptiveDistributionName(channelId, mediapackage, element));
float bitrate = 0;
// Add bitrate corresponding to the audio streams
for (AudioStream stream : track.getAudio()) {
bitrate += stream.getBitRate();
}
// Add bitrate corresponding to the video streams
// Also, set the video width and height values:
// In the rare case where there is more than one video stream, the values of the first stream
// have priority, but always prefer the first stream with both "frameWidth" and "frameHeight"
// parameters defined
Integer width = null;
Integer height = null;
for (VideoStream stream : track.getVideo()) {
bitrate += stream.getBitRate();
// Update if both width and height are defined for a stream or if we have no values at all
if (((stream.getFrameWidth() != null) && (stream.getFrameHeight() != null)) || ((width == null) && (height == null))) {
width = stream.getFrameWidth();
height = stream.getFrameHeight();
}
}
video.setAttribute(SMIL_ATTR_VIDEO_BITRATE, Integer.toString((int) bitrate));
if (width != null) {
video.setAttribute(SMIL_ATTR_VIDEO_WIDTH, Integer.toString(width));
} else {
logger.debug("Could not set video width in the SMIL file for element {} of mediapackage {}. The value was null", element.getIdentifier(), mediapackage.getIdentifier());
}
if (height != null) {
video.setAttribute(SMIL_ATTR_VIDEO_HEIGHT, Integer.toString(height));
} else {
logger.debug("Could not set video height in the SMIL file for element {} of mediapackage {}. The value was null", element.getIdentifier(), mediapackage.getIdentifier());
}
NodeList currentVideos = switchElement.getChildNodes();
for (int i = 0; i < currentVideos.getLength(); i++) {
Node current = currentVideos.item(i);
if ("video".equals(current.getNodeName())) {
Float currentBitrate = Float.parseFloat(current.getAttributes().getNamedItem(SMIL_ATTR_VIDEO_BITRATE).getTextContent());
if ((isSmilOrderDescending && (currentBitrate < bitrate)) || (!isSmilOrderDescending && (currentBitrate > bitrate))) {
switchElement.insertBefore(video, current);
return;
}
}
}
// If we get here, we could not insert the video before
switchElement.appendChild(video);
}
Aggregations