use of org.opencastproject.metadata.mpeg7.Mpeg7Catalog in project opencast by opencast.
the class Mpeg7CaptionConverter method importCaption.
/**
* @see org.opencastproject.caption.api.CaptionConverter#importCaption(java.io.InputStream, java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
public List<Caption> importCaption(InputStream inputStream, String language) throws CaptionConverterException {
List<Caption> captions = new ArrayList<Caption>();
Mpeg7Catalog catalog = new Mpeg7CatalogImpl(inputStream);
Iterator<Audio> audioContentIterator = catalog.audioContent();
if (audioContentIterator == null)
return captions;
content: while (audioContentIterator.hasNext()) {
Audio audioContent = audioContentIterator.next();
TemporalDecomposition<AudioSegment> audioSegments = (TemporalDecomposition<AudioSegment>) audioContent.getTemporalDecomposition();
Iterator<AudioSegment> audioSegmentIterator = audioSegments.segments();
if (audioSegmentIterator == null)
continue content;
while (audioSegmentIterator.hasNext()) {
AudioSegment segment = audioSegmentIterator.next();
Iterator<TextAnnotation> annotationIterator = segment.textAnnotations();
if (annotationIterator == null)
continue content;
while (annotationIterator.hasNext()) {
TextAnnotation annotation = annotationIterator.next();
if (!annotation.getLanguage().equals(language)) {
logger.debug("Skipping audio content '{}' because of language mismatch", audioContent.getId());
continue content;
}
List<String> captionLines = new ArrayList<String>();
Iterator<FreeTextAnnotation> freeTextAnnotationIterator = annotation.freeTextAnnotations();
if (freeTextAnnotationIterator == null)
continue;
while (freeTextAnnotationIterator.hasNext()) {
FreeTextAnnotation freeTextAnnotation = freeTextAnnotationIterator.next();
captionLines.add(freeTextAnnotation.getText());
}
MediaTime segmentTime = segment.getMediaTime();
MediaTimePoint stp = segmentTime.getMediaTimePoint();
MediaDuration d = segmentTime.getMediaDuration();
Calendar startCalendar = Calendar.getInstance();
int millisAtStart = (int) (stp.getTimeInMilliseconds() - (((stp.getHour() * 60 + stp.getMinutes()) * 60 + stp.getSeconds()) * 1000));
int millisAtEnd = (int) (d.getDurationInMilliseconds() - (((d.getHours() * 60 + d.getMinutes()) * 60 + d.getSeconds()) * 1000));
startCalendar.set(Calendar.HOUR, stp.getHour());
startCalendar.set(Calendar.MINUTE, stp.getMinutes());
startCalendar.set(Calendar.SECOND, stp.getSeconds());
startCalendar.set(Calendar.MILLISECOND, millisAtStart);
startCalendar.add(Calendar.HOUR, d.getHours());
startCalendar.add(Calendar.MINUTE, d.getMinutes());
startCalendar.add(Calendar.SECOND, d.getSeconds());
startCalendar.set(Calendar.MILLISECOND, millisAtEnd);
try {
Time startTime = new TimeImpl(stp.getHour(), stp.getMinutes(), stp.getSeconds(), millisAtStart);
Time endTime = new TimeImpl(startCalendar.get(Calendar.HOUR), startCalendar.get(Calendar.MINUTE), startCalendar.get(Calendar.SECOND), startCalendar.get(Calendar.MILLISECOND));
Caption caption = new CaptionImpl(startTime, endTime, captionLines.toArray(new String[captionLines.size()]));
captions.add(caption);
} catch (IllegalTimeFormatException e) {
logger.warn("Error setting caption time: {}", e.getMessage());
}
}
}
}
return captions;
}
use of org.opencastproject.metadata.mpeg7.Mpeg7Catalog in project opencast by opencast.
the class Mpeg7CaptionConverter method getLanguageList.
/**
* @see org.opencastproject.caption.api.CaptionConverter#getLanguageList(java.io.InputStream)
*/
@SuppressWarnings("unchecked")
@Override
public String[] getLanguageList(InputStream inputStream) throws CaptionConverterException {
Set<String> languages = new HashSet<String>();
Mpeg7Catalog catalog = new Mpeg7CatalogImpl(inputStream);
Iterator<Audio> audioContentIterator = catalog.audioContent();
if (audioContentIterator == null)
return languages.toArray(new String[languages.size()]);
content: while (audioContentIterator.hasNext()) {
Audio audioContent = audioContentIterator.next();
TemporalDecomposition<AudioSegment> audioSegments = (TemporalDecomposition<AudioSegment>) audioContent.getTemporalDecomposition();
Iterator<AudioSegment> audioSegmentIterator = audioSegments.segments();
if (audioSegmentIterator == null)
continue content;
while (audioSegmentIterator.hasNext()) {
AudioSegment segment = audioSegmentIterator.next();
Iterator<TextAnnotation> annotationIterator = segment.textAnnotations();
if (annotationIterator == null)
continue content;
while (annotationIterator.hasNext()) {
TextAnnotation annotation = annotationIterator.next();
String language = annotation.getLanguage();
if (language != null)
languages.add(language);
}
}
}
return languages.toArray(new String[languages.size()]);
}
use of org.opencastproject.metadata.mpeg7.Mpeg7Catalog in project opencast by opencast.
the class SolrIndexManager method createEpisodeInputDocument.
/**
* Creates a solr input document for the episode metadata of the media package.
*
* @param mediaPackage
* the media package
* @param acl
* the access control list for this mediapackage
* @return an input document ready to be posted to solr
* @throws MediaPackageException
* if serialization of the media package fails
*/
private SolrInputDocument createEpisodeInputDocument(MediaPackage mediaPackage, AccessControlList acl) throws MediaPackageException, IOException {
SolrInputDocument doc = new SolrInputDocument();
String mediaPackageId = mediaPackage.getIdentifier().toString();
// Fill the input document
Schema.setId(doc, mediaPackageId);
// /
// OC specific fields
Schema.setOcMediatype(doc, SearchResultItemType.AudioVisual.toString());
Schema.setOrganization(doc, securityService.getOrganization().getId());
Schema.setOcMediapackage(doc, MediaPackageParser.getAsXml(mediaPackage));
Schema.setOcElementtags(doc, tags(mediaPackage));
Schema.setOcElementflavors(doc, flavors(mediaPackage));
// Add cover
Attachment[] cover = mediaPackage.getAttachments(MediaPackageElements.MEDIAPACKAGE_COVER_FLAVOR);
if (cover != null && cover.length > 0) {
Schema.setOcCover(doc, cover[0].getURI().toString());
}
// naive approach. works as long as only setters, not adders are available in the schema
for (StaticMetadata md : getMetadata(mdServices, mediaPackage)) addEpisodeMetadata(doc, md);
// /
// Add mpeg7
logger.debug("Looking for mpeg-7 catalogs containing segment texts");
Catalog[] mpeg7Catalogs = mediaPackage.getCatalogs(MediaPackageElements.TEXTS);
if (mpeg7Catalogs.length == 0) {
logger.debug("No text catalogs found, trying segments only");
mpeg7Catalogs = mediaPackage.getCatalogs(MediaPackageElements.SEGMENTS);
}
// TODO: merge the segments from each mpeg7 if there is more than one mpeg7 catalog
if (mpeg7Catalogs.length > 0) {
try {
Mpeg7Catalog mpeg7Catalog = loadMpeg7Catalog(mpeg7Catalogs[0]);
addMpeg7Metadata(doc, mediaPackage, mpeg7Catalog);
} catch (IOException e) {
logger.error("Error loading mpeg7 catalog. Skipping catalog: {}", e.getMessage());
}
} else {
logger.debug("No segmentation catalog found");
}
// /
// Add authorization
setAuthorization(doc, securityService, acl);
return doc;
}
use of org.opencastproject.metadata.mpeg7.Mpeg7Catalog in project opencast by opencast.
the class SolrIndexManager method addMpeg7Metadata.
/**
* Add the mpeg 7 catalog data to the solr document.
*
* @param doc
* the input document to the solr index
* @param mpeg7
* the mpeg7 catalog
*/
@SuppressWarnings("unchecked")
static void addMpeg7Metadata(SolrInputDocument doc, MediaPackage mediaPackage, Mpeg7Catalog mpeg7) {
// Check for multimedia content
if (!mpeg7.multimediaContent().hasNext()) {
logger.warn("Mpeg-7 doesn't contain multimedia content");
return;
}
// Get the content duration by looking at the first content track. This
// of course assumes that all tracks are equally long.
MultimediaContent<? extends MultimediaContentType> mc = mpeg7.multimediaContent().next();
MultimediaContentType mct = mc.elements().next();
MediaTime mediaTime = mct.getMediaTime();
Schema.setDcExtent(doc, mediaTime.getMediaDuration().getDurationInMilliseconds());
// Check if the keywords have been filled by (manually) added dublin
// core data. If not, look for the most relevant fields in mpeg-7.
SortedSet<TextAnnotation> sortedAnnotations = null;
if (!"".equals(Schema.getOcKeywords(doc))) {
sortedAnnotations = new TreeSet<TextAnnotation>(new Comparator<TextAnnotation>() {
@Override
public int compare(TextAnnotation a1, TextAnnotation a2) {
if ((RELEVANCE_BOOST * a1.getRelevance() + a1.getConfidence()) > (RELEVANCE_BOOST * a2.getRelevance() + a2.getConfidence()))
return -1;
else if ((RELEVANCE_BOOST * a1.getRelevance() + a1.getConfidence()) < (RELEVANCE_BOOST * a2.getRelevance() + a2.getConfidence()))
return 1;
return 0;
}
});
}
// Iterate over the tracks and extract keywords and hints
Iterator<MultimediaContent<? extends MultimediaContentType>> mmIter = mpeg7.multimediaContent();
int segmentCount = 0;
while (mmIter.hasNext()) {
MultimediaContent<?> multimediaContent = mmIter.next();
// We need to process visual segments first, due to the way they are handled in the ui.
for (Iterator<?> iterator = multimediaContent.elements(); iterator.hasNext(); ) {
MultimediaContentType type = (MultimediaContentType) iterator.next();
if (!(type instanceof Video) && !(type instanceof AudioVisual))
continue;
// for every segment in the current multimedia content track
Video video = (Video) type;
Iterator<VideoSegment> vsegments = (Iterator<VideoSegment>) video.getTemporalDecomposition().segments();
while (vsegments.hasNext()) {
VideoSegment segment = vsegments.next();
StringBuffer segmentText = new StringBuffer();
StringBuffer hintField = new StringBuffer();
// Collect the video text elements to a segment text
SpatioTemporalDecomposition spt = segment.getSpatioTemporalDecomposition();
if (spt != null) {
for (VideoText videoText : spt.getVideoText()) {
if (segmentText.length() > 0)
segmentText.append(" ");
segmentText.append(videoText.getText().getText());
// TODO: Add hint on bounding box
}
}
// Add keyword annotations
Iterator<TextAnnotation> textAnnotations = segment.textAnnotations();
while (textAnnotations.hasNext()) {
TextAnnotation textAnnotation = textAnnotations.next();
Iterator<?> kwIter = textAnnotation.keywordAnnotations();
while (kwIter.hasNext()) {
KeywordAnnotation keywordAnnotation = (KeywordAnnotation) kwIter.next();
if (segmentText.length() > 0)
segmentText.append(" ");
segmentText.append(keywordAnnotation.getKeyword());
}
}
// Add free text annotations
Iterator<TextAnnotation> freeIter = segment.textAnnotations();
if (freeIter.hasNext()) {
Iterator<FreeTextAnnotation> freeTextIter = freeIter.next().freeTextAnnotations();
while (freeTextIter.hasNext()) {
FreeTextAnnotation freeTextAnnotation = freeTextIter.next();
if (segmentText.length() > 0)
segmentText.append(" ");
segmentText.append(freeTextAnnotation.getText());
}
}
// add segment text to solr document
Schema.setSegmentText(doc, new DField<String>(segmentText.toString(), Integer.toString(segmentCount)));
// get the segments time properties
MediaTimePoint timepoint = segment.getMediaTime().getMediaTimePoint();
MediaDuration duration = segment.getMediaTime().getMediaDuration();
// TODO: define a class with hint field constants
hintField.append("time=" + timepoint.getTimeInMilliseconds() + "\n");
hintField.append("duration=" + duration.getDurationInMilliseconds() + "\n");
// Look for preview images. Their characteristics are that they are
// attached as attachments with a flavor of preview/<something>.
String time = timepoint.toString();
for (Attachment slide : mediaPackage.getAttachments(MediaPackageElements.PRESENTATION_SEGMENT_PREVIEW)) {
MediaPackageReference ref = slide.getReference();
if (ref != null && time.equals(ref.getProperty("time"))) {
hintField.append("preview");
hintField.append(".");
hintField.append(ref.getIdentifier());
hintField.append("=");
hintField.append(slide.getURI().toString());
hintField.append("\n");
}
}
logger.trace("Adding segment: " + timepoint.toString());
Schema.setSegmentHint(doc, new DField<String>(hintField.toString(), Integer.toString(segmentCount)));
// increase segment counter
segmentCount++;
}
}
}
// Put the most important keywords into a special solr field
if (sortedAnnotations != null) {
Schema.setOcKeywords(doc, importantKeywordsString(sortedAnnotations).toString());
}
}
use of org.opencastproject.metadata.mpeg7.Mpeg7Catalog in project opencast by opencast.
the class SegmentPreviewsWorkflowOperationHandler method createPreviews.
/**
* Encode tracks from MediaPackage using profiles stored in properties and updates current MediaPackage.
*
* @param mediaPackage
* @param properties
* @return the operation result containing the updated mediapackage
* @throws EncoderException
* @throws ExecutionException
* @throws InterruptedException
* @throws IOException
* @throws NotFoundException
* @throws WorkflowOperationException
*/
private WorkflowOperationResult createPreviews(final MediaPackage mediaPackage, WorkflowOperationInstance operation) throws EncoderException, InterruptedException, ExecutionException, NotFoundException, MediaPackageException, IOException, WorkflowOperationException {
long totalTimeInQueue = 0;
// Read the configuration properties
String sourceVideoFlavor = StringUtils.trimToNull(operation.getConfiguration("source-flavor"));
String sourceTags = StringUtils.trimToNull(operation.getConfiguration("source-tags"));
String targetImageTags = StringUtils.trimToNull(operation.getConfiguration("target-tags"));
String targetImageFlavor = StringUtils.trimToNull(operation.getConfiguration("target-flavor"));
String encodingProfileName = StringUtils.trimToNull(operation.getConfiguration("encoding-profile"));
String referenceFlavor = StringUtils.trimToNull(operation.getConfiguration("reference-flavor"));
String referenceTags = StringUtils.trimToNull(operation.getConfiguration("reference-tags"));
// Find the encoding profile
EncodingProfile profile = composerService.getProfile(encodingProfileName);
if (profile == null)
throw new IllegalStateException("Encoding profile '" + encodingProfileName + "' was not found");
List<String> sourceTagSet = asList(sourceTags);
// Select the tracks based on the tags and flavors
Set<Track> videoTrackSet = new HashSet<>();
for (Track track : mediaPackage.getTracksByTags(sourceTagSet)) {
if (sourceVideoFlavor == null || (track.getFlavor() != null && sourceVideoFlavor.equals(track.getFlavor().toString()))) {
if (!track.hasVideo())
continue;
videoTrackSet.add(track);
}
}
if (videoTrackSet.size() == 0) {
logger.debug("Mediapackage {} has no suitable tracks to extract images based on tags {} and flavor {}", mediaPackage, sourceTags, sourceVideoFlavor);
return createResult(mediaPackage, Action.CONTINUE);
} else {
// Determine the tagset for the reference
List<String> referenceTagSet = asList(referenceTags);
// Determine the reference master
for (Track t : videoTrackSet) {
// Try to load the segments catalog
MediaPackageReference trackReference = new MediaPackageReferenceImpl(t);
Catalog[] segmentCatalogs = mediaPackage.getCatalogs(MediaPackageElements.SEGMENTS, trackReference);
Mpeg7Catalog mpeg7 = null;
if (segmentCatalogs.length > 0) {
mpeg7 = loadMpeg7Catalog(segmentCatalogs[0]);
if (segmentCatalogs.length > 1)
logger.warn("More than one segments catalog found for track {}. Resuming with the first one ({})", t, mpeg7);
} else {
logger.debug("No segments catalog found for track {}", t);
continue;
}
// Check the catalog's consistency
if (mpeg7.videoContent() == null || mpeg7.videoContent().next() == null) {
logger.info("Segments catalog {} contains no video content", mpeg7);
continue;
}
Video videoContent = mpeg7.videoContent().next();
TemporalDecomposition<? extends Segment> decomposition = videoContent.getTemporalDecomposition();
// Are there any segments?
if (decomposition == null || !decomposition.hasSegments()) {
logger.info("Segments catalog {} contains no video content", mpeg7);
continue;
}
// Is a derived track with the configured reference flavor available?
MediaPackageElement referenceMaster = getReferenceMaster(mediaPackage, t, referenceFlavor, referenceTagSet);
// Create the preview images according to the mpeg7 segments
if (t.hasVideo() && mpeg7 != null) {
Iterator<? extends Segment> segmentIterator = decomposition.segments();
List<MediaTimePoint> timePointList = new LinkedList<>();
while (segmentIterator.hasNext()) {
Segment segment = segmentIterator.next();
MediaTimePoint tp = segment.getMediaTime().getMediaTimePoint();
timePointList.add(tp);
}
// convert to time array
double[] timeArray = new double[timePointList.size()];
for (int i = 0; i < timePointList.size(); i++) timeArray[i] = (double) timePointList.get(i).getTimeInMilliseconds() / 1000;
Job job = composerService.image(t, profile.getIdentifier(), timeArray);
if (!waitForStatus(job).isSuccess()) {
throw new WorkflowOperationException("Extracting preview image from " + t + " failed");
}
// Get the latest copy
try {
job = serviceRegistry.getJob(job.getId());
} catch (ServiceRegistryException e) {
throw new WorkflowOperationException(e);
}
// add this receipt's queue time to the total
totalTimeInQueue += job.getQueueTime();
List<? extends MediaPackageElement> composedImages = MediaPackageElementParser.getArrayFromXml(job.getPayload());
Iterator<MediaTimePoint> it = timePointList.iterator();
for (MediaPackageElement element : composedImages) {
Attachment composedImage = (Attachment) element;
if (composedImage == null)
throw new IllegalStateException("Unable to compose image");
// Add the flavor, either from the operation configuration or from the composer
if (targetImageFlavor != null) {
composedImage.setFlavor(MediaPackageElementFlavor.parseFlavor(targetImageFlavor));
logger.debug("Preview image has flavor '{}'", composedImage.getFlavor());
}
// Set the mimetype
if (profile.getMimeType() != null)
composedImage.setMimeType(MimeTypes.parseMimeType(profile.getMimeType()));
// Add tags
for (String tag : asList(targetImageTags)) {
logger.trace("Tagging image with '{}'", tag);
composedImage.addTag(tag);
}
// Refer to the original track including a timestamp
MediaPackageReferenceImpl ref = new MediaPackageReferenceImpl(referenceMaster);
ref.setProperty("time", it.next().toString());
composedImage.setReference(ref);
// store new image in the mediaPackage
mediaPackage.add(composedImage);
String fileName = getFileNameFromElements(t, composedImage);
composedImage.setURI(workspace.moveTo(composedImage.getURI(), mediaPackage.getIdentifier().toString(), composedImage.getIdentifier(), fileName));
}
}
}
}
return createResult(mediaPackage, Action.CONTINUE, totalTimeInQueue);
}
Aggregations