index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/IMFErrorLogger.java
/* * * * Copyright 2015 Netflix, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.utils.ErrorLogger; import java.util.List; /** * An interface to represent errors that occurred while reading an MXF file */ public interface IMFErrorLogger extends ErrorLogger { /** * A method to add errors to a persistent list * * @param errorCode the error code * @param errorLevel the error level * @param errorDescription the error description */ void addError(IMFErrors.ErrorCodes errorCode, IMFErrors.ErrorLevels errorLevel, String errorDescription); public void addError(ErrorObject errorObject); public void addAllErrors(List<ErrorObject> errorObjects); public List<ErrorObject> getErrors(); public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorLevels errorLevel) throws IllegalArgumentException; public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorLevels errorLevel, int startIndex, int endIndex) throws IllegalArgumentException; public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorCodes errorCode) throws IllegalArgumentException; public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorCodes errorCode, int startIndex, int endIndex) throws IllegalArgumentException; public Boolean hasFatalErrors(); public Boolean hasFatalErrors(int startIndex, int endIndex); final class IMFErrors { private IMFErrors() {//to prevent instantiation } /** * An enumeration for Error codes */ public enum ErrorCodes { /** * The IMF_ESSENCE_METADATA_ERROR. */ IMF_ESSENCE_METADATA_ERROR("IMF Essence metadata Error"), /** * The IMF_ESSENCE_COMPONENT_ERROR. */ IMF_ESSENCE_COMPONENT_ERROR("IMF Essence Component Error"), /** * The IMF_CPL_ERROR. */ IMF_CPL_ERROR("IMF CPL Error"), /** * The IMF_PKL_ERROR. */ IMF_PKL_ERROR("IMF PKL Error"), /** * Error in processing of AssetMap or a mapped file set */ IMF_AM_ERROR("IMF AssetMap Error"), /** * The IMF_CORE_CONSTRAINTS_ERROR. */ IMF_CORE_CONSTRAINTS_ERROR("IMF Core Constraints Error"), /** * EssenceDescriptorList element is mssing from an IMF CPL (st2067-2:2016 Section 6.8) */ IMF_CORE_CONSTRAINTS_ESSENCE_DESCRIPTOR_LIST_MISSING("IMF Core Constraints Essence Descriptor List Missing"), /** * The IMF_MASTER_PACKAGE_ERROR. */ IMF_MASTER_PACKAGE_ERROR("IMF Master Package Error"), /** * The IMP_VALIDATOR_PAYLOAD_ERROR. */ IMP_VALIDATOR_PAYLOAD_ERROR("IMP Validator Payload Error"), /** * The UUID_ERROR. */ UUID_ERROR("UUID Syntax Error"), /** * The URI_ERROR. */ URI_ERROR("URI Syntax Error"), /** * INTERNAL_ERROR. */ INTERNAL_ERROR ("Internal processing error"), /** * APPLICATION_COMPOSITION_ERROR. */ APPLICATION_COMPOSITION_ERROR ("Application Composition error"), /** * SMPTE_REGISTER_PARSING_ERROR. */ SMPTE_REGISTER_PARSING_ERROR("SMPTE Register parsing error"), /** * The IMF_OPL_ERROR. */ IMF_OPL_ERROR("IMF OPL Error"); private final String error; ErrorCodes(String error){ this.error = error; } /** * A toString() method * @return string representation of this enumeration constant */ public String toString(){ return this.error; } } /** * An enumeration for the Error levels */ public enum ErrorLevels { /** * WARNING */ WARNING("WARNING"), /** * The NON_FATAL. */ NON_FATAL("NON FATAL"), /** * The FATAL. */ FATAL("FATAL"); private final String errorLevel; ErrorLevels(String errorLevel){ this.errorLevel = errorLevel; } /** * A toString() method * @return string representation of this enumeration constant */ public String toString(){ return this.errorLevel; } } } }
5,000
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * This package contains classes that represent the data model of the Material Exchange Format (MXF) * as defined by the SMPTE st0377-1:2011 specification. * It also contains classes that are used to represent the metadata of an MXF essence in an * Interoperable Master Format (IMF) compliant Composition Playlist as defined by the SMPTE st2067-3:2013 * specification and constrained by the SMPTE IMF-Core Constraints SMPTE st2067-2:2013. * * @since 1.0 * @version 1.0 */ package com.netflix.imflibrary;
5,001
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/OutputProfileListModel_st2067_100_2014.java
package com.netflix.imflibrary.st2067_100; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.st2067_100.macro.audioRoutingMixing.AudioRoutingMixingMacro; import com.netflix.imflibrary.st2067_100.macro.audioRoutingMixing.InputEntity; import com.netflix.imflibrary.st2067_100.macro.audioRoutingMixing.OutputAudioChannel; import com.netflix.imflibrary.st2067_100.macro.ColorEncoding; import com.netflix.imflibrary.st2067_100.macro.Macro; import com.netflix.imflibrary.st2067_100.macro.crop.CropInputImageSequence; import com.netflix.imflibrary.st2067_100.macro.crop.CropMacro; import com.netflix.imflibrary.st2067_100.macro.crop.CropOutputImageSequence; import com.netflix.imflibrary.st2067_100.macro.crop.MXFRectangle; import com.netflix.imflibrary.st2067_100.macro.crop.RectanglePadding; import com.netflix.imflibrary.st2067_100.macro.pixelDecoder.PixelDecoderInputImageSequence; import com.netflix.imflibrary.st2067_100.macro.pixelDecoder.PixelDecoderMacro; import com.netflix.imflibrary.st2067_100.macro.pixelDecoder.PixelDecoderOutputImageSequence; import com.netflix.imflibrary.st2067_100.macro.pixelEncoder.PixelEncoderInputImageSequence; import com.netflix.imflibrary.st2067_100.macro.pixelEncoder.PixelEncoderMacro; import com.netflix.imflibrary.st2067_100.macro.pixelEncoder.PixelEncoderOutputImageSequence; import com.netflix.imflibrary.st2067_100.macro.preset.PresetMacro; import com.netflix.imflibrary.st2067_100.macro.scale.Lanczos; import com.netflix.imflibrary.st2067_100.macro.scale.ScaleAlgorithm; import com.netflix.imflibrary.st2067_100.macro.scale.ScaleInputImageSequence; import com.netflix.imflibrary.st2067_100.macro.scale.ScaleMacro; import com.netflix.imflibrary.st2067_100.macro.scale.ScaleOutputImageSequence; import javax.annotation.concurrent.Immutable; import org.smpte_ra.schemas._2067_100._2014.OutputProfileListType.AliasList.Alias; import org.smpte_ra.schemas._2067_100._2014.PresetMacroType; import org.smpte_ra.schemas._2067_101._2014.crop_macro.ImageCropMacroType; import org.smpte_ra.schemas._2067_101._2014.pixel_decoder.PixelDecoderType; import org.smpte_ra.schemas._2067_101._2014.pixel_encoder.PixelEncoderType; import org.smpte_ra.schemas._2067_101._2014.scale_macro.ImageScaleMacroType; import org.smpte_ra.schemas._2067_103._2014.AudioRoutingMixingMacroType; import org.smpte_ra.schemas._2067_103._2014.OutputAudioChannelType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * A class that models OutputProfileList as per specification st2067-100:2014. */ @Immutable class OutputProfileListModel_st2067_100_2014 { private final IMFErrorLogger imfErrorLogger; private final org.smpte_ra.schemas._2067_100._2014.OutputProfileListType outputProfileListType; private final OutputProfileList normalizedOutputProfileList; OutputProfileListModel_st2067_100_2014(org.smpte_ra.schemas._2067_100._2014.OutputProfileListType outputProfileListType, IMFErrorLogger imfErrorLogger) { this.imfErrorLogger = imfErrorLogger; this.outputProfileListType = outputProfileListType; this.normalizedOutputProfileList = createNormalizedOutputProfileList(); } public OutputProfileList getNormalizedOutputProfileList() { return normalizedOutputProfileList; } /** * A stateless method that reads and parses OPL as per st 2067-100:2014 schema and returns normalized(schema agnostic) OutputProfileList object. * @return Normalized object model for OutputProfileList */ private OutputProfileList createNormalizedOutputProfileList () { Map<String, Macro> macroMap = new HashMap<>(); Map<String, String> aliasMap = new HashMap<>(); for(org.smpte_ra.schemas._2067_100._2014.MacroType macroType: outputProfileListType.getMacroList().getMacro()) { Macro macro = createMacro(macroType); if(macro != null) { macroMap.put(macroType.getName(), macro); } } for(Alias alias: outputProfileListType.getAliasList().getAlias()) { aliasMap.put(alias.getValue(), alias.getHandle()); } OutputProfileList normalizedOutputProfileList = new OutputProfileList( outputProfileListType.getId(), outputProfileListType.getAnnotation() != null ? outputProfileListType.getAnnotation().getValue() : null, outputProfileListType.getCompositionPlaylistId(), aliasMap, macroMap); this.imfErrorLogger.addAllErrors(normalizedOutputProfileList.getErrors()); return normalizedOutputProfileList; } private Macro createMacro(org.smpte_ra.schemas._2067_100._2014.MacroType macroType) { if(macroType instanceof ImageCropMacroType) { return createCropMacro((ImageCropMacroType) macroType); } else if(macroType instanceof ImageScaleMacroType) { return createScaleMacro((ImageScaleMacroType) macroType); } else if(macroType instanceof PixelDecoderType) { return createPixelDecoderMacro((PixelDecoderType) macroType); } else if(macroType instanceof PixelEncoderType) { return createPixelEncoderMacro((PixelEncoderType) macroType); } else if(macroType instanceof AudioRoutingMixingMacroType) { return createAudioRoutingMixingMacro((AudioRoutingMixingMacroType) macroType); } else if(macroType instanceof PresetMacroType) { return createPresetMacro((PresetMacroType) macroType); } else { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Unknown macro type with %s in OPL", macroType.getName())); return null; } } private CropMacro createCropMacro(ImageCropMacroType imageCropMacroType) { if(imageCropMacroType.getInputImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing InputImageSequence in %s macro", imageCropMacroType.getName())); } ImageCropMacroType.InputImageSequence inputImageSequence = imageCropMacroType.getInputImageSequence(); MXFRectangle mxfRectangleEnum = MXFRectangle.fromValue(inputImageSequence.getReferenceRectangle().value()); RectanglePadding inset = new RectanglePadding(inputImageSequence.getInset().getLeft().intValue(), inputImageSequence.getInset().getRight().intValue(), inputImageSequence.getInset().getTop().intValue(), inputImageSequence.getInset().getBottom().intValue()); CropInputImageSequence input = new CropInputImageSequence(inputImageSequence.getAnnotation() != null ? inputImageSequence.getAnnotation().getValue() : null, inputImageSequence.getHandle(), mxfRectangleEnum, inset); if(imageCropMacroType.getOutputImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing OutputImageSequence in %s macro", imageCropMacroType.getName())); } ImageCropMacroType.OutputImageSequence outputImageSequence = imageCropMacroType.getOutputImageSequence(); RectanglePadding padding = new RectanglePadding(outputImageSequence.getPadding().getLeft().intValue(), outputImageSequence.getPadding().getRight().intValue(), outputImageSequence.getPadding().getTop().intValue(), outputImageSequence.getPadding().getBottom().intValue()); ColorEncoding colorEncodingEnum = ColorEncoding.fromValue(outputImageSequence.getFillColor().getClass().getName()); CropOutputImageSequence output = new CropOutputImageSequence( outputImageSequence.getAnnotation() != null ? outputImageSequence.getAnnotation().getValue() : null, "macros/" + imageCropMacroType.getName() + "/outputs/images", padding, colorEncodingEnum); return new CropMacro( imageCropMacroType.getName(), imageCropMacroType.getAnnotation() != null ? imageCropMacroType.getAnnotation().getValue() : null, input, output); } private ScaleMacro createScaleMacro(ImageScaleMacroType imageScaleMacroType) { if(imageScaleMacroType.getInputImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing InputImageSequence in %s macro", imageScaleMacroType.getName())); } ImageScaleMacroType.InputImageSequence inputImageSequence = imageScaleMacroType.getInputImageSequence(); ScaleInputImageSequence input = new ScaleInputImageSequence(inputImageSequence.getAnnotation() != null ? inputImageSequence.getAnnotation().getValue() : null, inputImageSequence.getHandle()); if(imageScaleMacroType.getOutputImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing OutputImageSequence in %s macro", imageScaleMacroType.getName())); } ImageScaleMacroType.OutputImageSequence outputImageSequence = imageScaleMacroType.getOutputImageSequence(); ScaleAlgorithm scaleAlgorithmType = null; if(outputImageSequence.getAlgorithm() instanceof org.smpte_ra.schemas._2067_101._2014.lanczos.LanczosType) { scaleAlgorithmType = new Lanczos(((org.smpte_ra.schemas._2067_101._2014.lanczos.LanczosType) outputImageSequence.getAlgorithm()).getParameterA().intValue()); } if(scaleAlgorithmType == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Unsupported scaling algorithm in %s macro", imageScaleMacroType.getName())); } ScaleOutputImageSequence output = new ScaleOutputImageSequence( outputImageSequence.getAnnotation() != null ? outputImageSequence.getAnnotation().getValue() : null, "macros/" + imageScaleMacroType.getName() + "/outputs/images", outputImageSequence.getWidth().intValue(), outputImageSequence.getHeight().intValue(), outputImageSequence.getBoundaryCondition(), scaleAlgorithmType); return new ScaleMacro( imageScaleMacroType.getName(), imageScaleMacroType.getAnnotation() != null ? imageScaleMacroType.getAnnotation().getValue() : null, input, output); } private PixelDecoderMacro createPixelDecoderMacro(PixelDecoderType pixelDecoderType) { if(pixelDecoderType.getInputImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing InputImageSequence in %s macro", pixelDecoderType.getName())); } PixelDecoderType.InputImageSequence inputImageSequence = pixelDecoderType.getInputImageSequence(); PixelDecoderInputImageSequence input = new PixelDecoderInputImageSequence(inputImageSequence.getAnnotation() != null ? inputImageSequence.getAnnotation().getValue() : null, inputImageSequence.getHandle()); if(pixelDecoderType.getOutputReferenceImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing OutputImageSequence in %s macro", pixelDecoderType.getName())); } PixelDecoderType.OutputReferenceImageSequence outputImageSequence = pixelDecoderType.getOutputReferenceImageSequence(); PixelDecoderOutputImageSequence output = new PixelDecoderOutputImageSequence( outputImageSequence.getAnnotation() != null ? outputImageSequence.getAnnotation().getValue() : null, "macros/" + pixelDecoderType.getName() + "/outputs/images"); return new PixelDecoderMacro(pixelDecoderType.getName(), pixelDecoderType.getAnnotation() != null ? pixelDecoderType.getAnnotation().getValue() : null, input, output); } private PixelEncoderMacro createPixelEncoderMacro(PixelEncoderType pixelEncoderType) { if(pixelEncoderType.getInputReferenceImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing InputImageSequence in %s macro", pixelEncoderType.getName())); } PixelEncoderType.InputReferenceImageSequence inputImageSequence = pixelEncoderType.getInputReferenceImageSequence(); PixelEncoderInputImageSequence input = new PixelEncoderInputImageSequence(inputImageSequence.getAnnotation() != null ? inputImageSequence.getAnnotation().getValue() : null, inputImageSequence.getHandle()); if(pixelEncoderType.getOutputImageSequence() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing OutputImageSequence in %s macro", pixelEncoderType.getName())); } PixelEncoderType.OutputImageSequence outputImageSequence = pixelEncoderType.getOutputImageSequence(); PixelEncoderOutputImageSequence output = new PixelEncoderOutputImageSequence( outputImageSequence.getAnnotation() != null ? outputImageSequence.getAnnotation().getValue() : null, "macros/" + pixelEncoderType.getName() + "/outputs/images"); return new PixelEncoderMacro(pixelEncoderType.getName(), pixelEncoderType.getAnnotation() != null ? pixelEncoderType.getAnnotation().getValue() : null, input, output); } private AudioRoutingMixingMacro createAudioRoutingMixingMacro(AudioRoutingMixingMacroType audioRoutingMixingMacroType) { if(audioRoutingMixingMacroType.getOutputEntityList() == null) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing OutputEntityList in %s macro", audioRoutingMixingMacroType.getName())); } AudioRoutingMixingMacroType.OutputEntityList outputEntityList = audioRoutingMixingMacroType.getOutputEntityList(); List<OutputAudioChannel> outputAudioChannels = new ArrayList<>(); for(OutputAudioChannelType outputAudioChannelType: outputEntityList.getOutputAudioChannel()) { List<InputEntity> inputEntityList = outputAudioChannelType.getInputEntityList().getInputEntity().stream().map(e -> new InputEntity( "", e.getHandle(), e.getGain())).collect(Collectors.toList()); outputAudioChannels.add(new OutputAudioChannel( outputAudioChannelType.getAnnotation() != null ? outputAudioChannelType.getAnnotation().getValue() : null, "macros/" + audioRoutingMixingMacroType.getName() + "/outputs/" + outputAudioChannelType.getHandle(), inputEntityList)); } return new AudioRoutingMixingMacro(audioRoutingMixingMacroType.getName(), audioRoutingMixingMacroType.getAnnotation() != null ? audioRoutingMixingMacroType.getAnnotation().getValue() : null, outputAudioChannels); } private PresetMacro createPresetMacro(PresetMacroType presetMacroType) { return new PresetMacro(presetMacroType.getName(), presetMacroType.getAnnotation() != null ? presetMacroType.getAnnotation().getValue() : null, presetMacroType.getPreset()); } }
5,002
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/OutputProfileList.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.st2067_100.handle.Handle; import com.netflix.imflibrary.st2067_100.handle.MCADictionaryIdHandle; import com.netflix.imflibrary.st2067_100.handle.MCALinkIdHandle; import com.netflix.imflibrary.st2067_100.handle.MCATagSymbolHandle; import com.netflix.imflibrary.st2067_100.handle.MacroHandle; import com.netflix.imflibrary.st2067_100.handle.VirtualTrackHandle; import com.netflix.imflibrary.st2067_100.macro.Macro; import com.netflix.imflibrary.st2067_100.macro.Sequence; import com.netflix.imflibrary.st2067_100.macro.preset.PresetMacro; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.st2067_2.IMFEssenceComponentVirtualTrack; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.annotation.concurrent.Immutable; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * A class that models an IMF OutputProfileList structure. */ @Immutable public final class OutputProfileList { private final static QName outputProfileList_QNAME = new QName("http://www.smpte-ra.org/schemas/2067-100/2014", "OutputProfileList"); private final static String outputProfileList_context_path = "org.w3._2000._09.xmldsig_:" + "org.smpte_ra.schemas._433._2008.dcmltypes:" + "org.smpte_ra.schemas._2067_100._2014:" + "org.smpte_ra.schemas._2067_101._2014.color_schemes:" + "org.smpte_ra.schemas._2067_101._2014.crop_macro:" + "org.smpte_ra.schemas._2067_101._2014.lanczos:" + "org.smpte_ra.schemas._2067_101._2014.pixel_decoder:" + "org.smpte_ra.schemas._2067_101._2014.pixel_encoder:" + "org.smpte_ra.schemas._2067_101._2014.scale_macro:" + "org.smpte_ra.schemas._2067_102._2014:" + "org.smpte_ra.schemas._2067_103._2014"; private static final String dcmlTypes_schema_path = "org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd"; private static final String xmldsig_core_schema_path = "org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"; private static final String opl_100a_schema_path = "org/smpte_ra/schemas/st2067_100_2014/st2067-100a-2014.xsd"; private static final String opl_101a_schema_path = "org/smpte_ra/schemas/st2067_101_2014/st2067-101a-2014.xsd"; private static final String opl_101b_schema_path = "org/smpte_ra/schemas/st2067_101_2014/st2067-101b-2014.xsd"; private static final String opl_101c_schema_path = "org/smpte_ra/schemas/st2067_101_2014/st2067-101c-2014.xsd"; private static final String opl_101d_schema_path = "org/smpte_ra/schemas/st2067_101_2014/st2067-101d-2014.xsd"; private static final String opl_101e_schema_path = "org/smpte_ra/schemas/st2067_101_2014/st2067-101e-2014.xsd"; private static final String opl_101f_schema_path = "org/smpte_ra/schemas/st2067_101_2014/st2067-101f-2014.xsd"; private static final String opl_102a_schema_path = "org/smpte_ra/schemas/st2067_102_2014/st2067-102a-2014.xsd"; private static final String opl_103b_schema_path = "org/smpte_ra/schemas/st2067_103_2014/st2067-103b-2014.xsd"; private static final Logger logger = LoggerFactory.getLogger(OutputProfileList.class); private final UUID id; private final String annotation; private final UUID compositionPlaylistId; private final IMFErrorLogger imfErrorLogger; private final Map<String, Macro> macroMap; private final Map<String, String> aliasMap; public OutputProfileList(String id, String annotation, String compositionPlaylistId, Map<String, String> aliasMap, Map<String, Macro> macroTypeMap) { this.id = UUIDHelper.fromUUIDAsURNStringToUUID(id); imfErrorLogger = new IMFErrorLoggerImpl(); this.annotation = annotation; this.compositionPlaylistId = UUIDHelper.fromUUIDAsURNStringToUUID(compositionPlaylistId); this.aliasMap = Collections.unmodifiableMap(aliasMap); this.macroMap = Collections.unmodifiableMap(macroTypeMap); Map<String, Handle> handleMap = new HashMap<>(); for (Map.Entry<String, Macro> entry : this.macroMap.entrySet()) { Macro macro = entry.getValue(); if (macro != null) { if(macro instanceof PresetMacro && this.macroMap.size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.NON_FATAL, String.format("OPL with id %s contains Preset Macro with other macro types", id)); } for (Sequence input : macro.getInputs()) { String inputHandle = getHandle(input.getHandle()); if(inputHandle.startsWith("cpl/")) { handleMap.put(inputHandle, new VirtualTrackHandle(inputHandle, null)); } } } } populateMacroHandles( handleMap); if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Failed to create OutputProfileList", imfErrorLogger); } } /** * A method that confirms if the inputStream corresponds to a OutputProfileList document instance. * * @param resourceByteRangeProvider corresponding to the OutputProfileList XML file. * @return a boolean indicating if the input file is a OutputProfileList document * @throws IOException - any I/O related error is exposed through an IOException */ public static boolean isOutputProfileList(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1);) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); //obtain root node NodeList nodeList = document.getElementsByTagNameNS(outputProfileList_QNAME.getNamespaceURI(), outputProfileList_QNAME.getLocalPart()); if (nodeList != null && nodeList.getLength() == 1) { return true; } } catch (ParserConfigurationException | SAXException e) { return false; } return false; } /** * A method to get output profile list object model from OutputProfileList document instance. * @param resourceByteRangeProvider corresponding to the OutputProfileList XML file. * @param imfErrorLogger - an object for logging errors * @return Output profile list object model * @throws IOException - any I/O related error is exposed through an IOException */ public static OutputProfileList getOutputProfileListType(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException { JAXBElement jaxbElement = null; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1); InputStream xmldsig_core_is = contextClassLoader.getResourceAsStream(xmldsig_core_schema_path); InputStream dcmlTypes_is = contextClassLoader.getResourceAsStream(dcmlTypes_schema_path); InputStream imf_opl_100a_is = contextClassLoader.getResourceAsStream(opl_100a_schema_path); InputStream imf_opl_101a_is = contextClassLoader.getResourceAsStream(opl_101a_schema_path); InputStream imf_opl_101b_is = contextClassLoader.getResourceAsStream(opl_101b_schema_path); InputStream imf_opl_101c_is = contextClassLoader.getResourceAsStream(opl_101c_schema_path); InputStream imf_opl_101d_is = contextClassLoader.getResourceAsStream(opl_101d_schema_path); InputStream imf_opl_101e_is = contextClassLoader.getResourceAsStream(opl_101e_schema_path); InputStream imf_opl_101f_is = contextClassLoader.getResourceAsStream(opl_101f_schema_path); InputStream imf_opl_102a_is = contextClassLoader.getResourceAsStream(opl_102a_schema_path); InputStream imf_opl_103b_is = contextClassLoader.getResourceAsStream(opl_103b_schema_path) ) { StreamSource[] streamSources = new StreamSource[11]; streamSources[0] = new StreamSource(xmldsig_core_is); streamSources[1] = new StreamSource(dcmlTypes_is); streamSources[2] = new StreamSource(imf_opl_100a_is); streamSources[3] = new StreamSource(imf_opl_101d_is); streamSources[4] = new StreamSource(imf_opl_101b_is); streamSources[5] = new StreamSource(imf_opl_101c_is); streamSources[6] = new StreamSource(imf_opl_101a_is); streamSources[7] = new StreamSource(imf_opl_101e_is); streamSources[8] = new StreamSource(imf_opl_101f_is); streamSources[9] = new StreamSource(imf_opl_102a_is); streamSources[10] = new StreamSource(imf_opl_103b_is); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(streamSources); ValidationEventHandlerImpl validationEventHandlerImpl = new ValidationEventHandlerImpl(true); JAXBContext jaxbContext = JAXBContext.newInstance(outputProfileList_context_path); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setEventHandler(validationEventHandlerImpl); unmarshaller.setSchema(schema); jaxbElement = (JAXBElement) unmarshaller.unmarshal(inputStream); if (validationEventHandlerImpl.hasErrors()) { validationEventHandlerImpl.getErrors().stream() .map(e -> new ErrorLogger.ErrorObject( IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, e.getValidationEventSeverity(), "Line Number : " + e.getLineNumber().toString() + " - " + e.getErrorMessage()) ) .forEach(imfErrorLogger::addError); throw new IMFException(validationEventHandlerImpl.toString(), imfErrorLogger); } } catch (SAXException | JAXBException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.FATAL, e.getMessage()); throw new IMFException(e.getMessage(), imfErrorLogger); } org.smpte_ra.schemas._2067_100._2014.OutputProfileListType outputProfileListTypeJaxb = (org.smpte_ra.schemas._2067_100._2014.OutputProfileListType) jaxbElement.getValue(); OutputProfileListModel_st2067_100_2014 outputProfileListModel = new OutputProfileListModel_st2067_100_2014(outputProfileListTypeJaxb, imfErrorLogger); return outputProfileListModel.getNormalizedOutputProfileList(); } /** * A method to apply output profile on an application composition * @param applicationComposition ApplicationComposition related to this output profile * @return List of errors that occurred while applying output profile on the application composition */ public List<ErrorLogger.ErrorObject> applyOutputProfileOnComposition(ApplicationComposition applicationComposition) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Map<String, Handle> handleMapConformed = getHandleMapWithApplicationComposition(applicationComposition, imfErrorLogger); /** * Validate alias handles */ for(String handle: this.aliasMap.values()) { Handle handleType = handleMapConformed.get(handle); if (handleType == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Invalid handle %s in alias", handle)); } } return imfErrorLogger.getErrors(); } /** * A method to get handle map with Application Composition applied on output profile * @param applicationComposition ApplicationComposition related to this output profile * @param imfErrorLogger logger for recording any parsing errors * @return Map containing a string handle to object representation of the handle */ public Map<String, Handle> getHandleMapWithApplicationComposition(ApplicationComposition applicationComposition, IMFErrorLogger imfErrorLogger) { Map<String, Handle> handleMapConformed = new HashMap<>(); /** * Add handles for CPL tracks */ populateCPLVirtualTrackHandles(applicationComposition, handleMapConformed); /** * Add handles for OPL macros */ populateMacroHandles(handleMapConformed); /** * Verify that input dependencies for all the macros are resolved */ for(Map.Entry<String, Macro> entry: this.macroMap.entrySet()) { Macro macro = entry.getValue(); for(Sequence input: macro.getInputs()) { Handle handleType = handleMapConformed.get(getHandle(input.getHandle())); if (handleType == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Invalid handle %s in %s macro", input.getHandle(), macro.getName())); } } } return handleMapConformed; } private static Map<String, Handle> populateCPLVirtualTrackHandles(ApplicationComposition applicationComposition, Map<String, Handle> handleMap) { List<? extends Composition.VirtualTrack> virtualTrackList = applicationComposition.getVirtualTracks(); for(Composition.VirtualTrack virtualTrack: virtualTrackList) { switch(virtualTrack.getSequenceTypeEnum()) { case MainImageSequence: { StringBuilder handleBuilder = new StringBuilder(); handleBuilder.append("cpl/virtual-tracks/" + virtualTrack.getTrackID()); Handle handleType = new VirtualTrackHandle(handleBuilder.toString(), virtualTrack); handleMap.put(handleBuilder.toString(), handleType); } break; case MainAudioSequence: { IMFEssenceComponentVirtualTrack imfEssenceComponentVirtualTrack = (IMFEssenceComponentVirtualTrack) virtualTrack; for (UUID uuid : imfEssenceComponentVirtualTrack.getTrackResourceIds()) { DOMNodeObjectModel domNodeObjectModel = applicationComposition.getEssenceDescriptor(uuid); if (domNodeObjectModel != null) { Set<UL> mcaLabelDictionaryIDs = domNodeObjectModel.getFieldsAsUL("MCALabelDictionaryID"); for (UL mcaLabelDictionaryID : mcaLabelDictionaryIDs) { StringBuilder handleBuilder = new StringBuilder(); handleBuilder.append("cpl/virtual-tracks/" + virtualTrack.getTrackID()); handleBuilder.append("/MCADictionaryLabelID=" + mcaLabelDictionaryID.toStringBytes()); Handle handleType = new MCADictionaryIdHandle(handleBuilder.toString(), virtualTrack, mcaLabelDictionaryID); handleMap.put(handleBuilder.toString(), handleType); } Set<UUID> mcaLinkIDs = domNodeObjectModel.getFieldsAsUUID("MCALinkID"); for (UUID mcaLinkID : mcaLinkIDs) { StringBuilder handleBuilder = new StringBuilder(); handleBuilder.append("cpl/virtual-tracks/" + virtualTrack.getTrackID()); handleBuilder.append("/MCALinkID=" + mcaLinkID.toString()); Handle handleType = new MCALinkIdHandle(handleBuilder.toString(), virtualTrack, mcaLinkID); handleMap.put(handleBuilder.toString(), handleType); } Set<String> mcaTagSymbols = domNodeObjectModel.getFieldsAsStringRecursive("MCATagSymbol"); for (String mcaTagSymbol : mcaTagSymbols) { StringBuilder handleBuilder = new StringBuilder(); handleBuilder.append("cpl/virtual-tracks/" + virtualTrack.getTrackID()); handleBuilder.append("/MCATagSymbol=" + mcaTagSymbol); Handle handleType = new MCATagSymbolHandle(handleBuilder.toString(), virtualTrack, mcaTagSymbol); handleMap.put(handleBuilder.toString(), handleType); } } } } break; } } return handleMap; } private void populateMacroHandles(Map<String, Handle> handleMap) { /** * Add handles for OPL macros */ for( int iteration = 0; iteration < this.macroMap.size(); iteration++) { boolean bAllDependencyMet = true; for (Map.Entry<String, Macro> entry : this.macroMap.entrySet()) { Macro macro = entry.getValue(); /* Check for all the input dependencies for the macro */ if (macro != null && !macro.getOutputs().isEmpty() && !handleMap.containsKey(getHandle(macro.getOutputs().get(0).getHandle()))) { boolean bDependencyMet = true; for (Sequence input : macro.getInputs()) { Handle handleType = handleMap.get(getHandle(input.getHandle())); if (handleType == null) { bDependencyMet = false; } } bAllDependencyMet &= bDependencyMet; /* If input dependencies are met create output handles */ if (bDependencyMet) { for (Sequence output : macro.getOutputs()) { String outputHandle = getHandle(output.getHandle()); handleMap.put(outputHandle, new MacroHandle(outputHandle, macro)); } } } } if(bAllDependencyMet) { break; } } /** * Verify that input dependencies for all the macros are resolved */ for(Map.Entry<String, Macro> entry: this.macroMap.entrySet()) { Macro macro = entry.getValue(); for(Sequence input: macro.getInputs()) { Handle handleType = handleMap.get(getHandle(input.getHandle())); if (handleType == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Invalid handle %s in %s macro", input.getHandle(), macro.getName())); } } } /** * Validate alias handles */ for(String handle: this.aliasMap.values()) { Handle handleType = handleMap.get(handle); // Ignore input aliases as they are not needed for dependency resolution // Ignore cpl/virtual track aliases too. All track IDs are not available for OPL and hence cannot validate. if (handleType == null && !handle.contains("/inputs/") && !handle.startsWith("cpl/virtual-tracks/")) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Invalid handle %s in alias", handle)); } } } private String getHandle(String handle) { if(handle.startsWith("alias/")) { handle = handle.replace("alias/", ""); } if(this.aliasMap.containsKey(handle)) { handle = this.aliasMap.get(handle); } return handle; } /** * Getter for the OutputProfileList ID * @return a string representing the urn:uuid of the OutputProfileList */ public UUID getId(){ return this.id; } /** * Getter for the OutputProfileList annotation * @return a string representing annotation of the OutputProfileList */ public String getAnnotation(){ return this.annotation; } public Map<String, String> getAliasMap() { return aliasMap; } public Map<String, Macro> getMacroMap() { return macroMap; } public UUID getCompositionPlaylistId() { return compositionPlaylistId; } public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <inputFilePath>%n", OutputProfileList.class.getName())); return sb.toString(); } public static void main(String args[]) throws IOException, SAXException, JAXBException { if (args.length != 1) { logger.error(usage()); throw new IllegalArgumentException("Invalid parameters"); } File inputFile = new File(args[0]); if(!inputFile.exists()){ logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.OutputProfileList, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject>errors = IMPValidator.validateOPL(payloadRecord); if(errors.size() > 0){ long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("OutputProfileList Document has %d errors and %d warnings", errors.size() - warningCount, warningCount)); for(ErrorLogger.ErrorObject errorObject : errors){ if(errorObject.getErrorLevel() != IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if(errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } } else{ logger.info("No errors were detected in the OutputProfileList Document."); } } }
5,003
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/handle/MCALinkIdHandle.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.handle; import com.netflix.imflibrary.st2067_2.Composition; import javax.annotation.concurrent.Immutable; import java.util.UUID; @Immutable public class MCALinkIdHandle extends Handle { private final Composition.VirtualTrack virtualTrack; private final UUID mcaLinkId; public MCALinkIdHandle(String handle, Composition.VirtualTrack virtualTrack, UUID mcaLinkId) { super(handle); this.virtualTrack = virtualTrack; this.mcaLinkId = mcaLinkId; } public Composition.VirtualTrack getVirtualTrack() { return virtualTrack; } public UUID getMcaLinkId() { return mcaLinkId; } }
5,004
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/handle/MacroHandle.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.handle; import com.netflix.imflibrary.st2067_100.macro.Macro; import javax.annotation.concurrent.Immutable; @Immutable public class MacroHandle extends Handle { private final Macro macroType; public MacroHandle(String handle, Macro macroType) { super(handle); this.macroType = macroType; } public Macro getMacroType() { return macroType; } }
5,005
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/handle/MCATagSymbolHandle.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.handle; import com.netflix.imflibrary.st2067_2.Composition; import javax.annotation.concurrent.Immutable; @Immutable public class MCATagSymbolHandle extends Handle { private final Composition.VirtualTrack virtualTrack; private final String mcaTagSymbol; public MCATagSymbolHandle(String handle, Composition.VirtualTrack virtualTrack, String mcaTagSymbol) { super(handle); this.virtualTrack = virtualTrack; this.mcaTagSymbol = mcaTagSymbol; } public Composition.VirtualTrack getVirtualTrack() { return virtualTrack; } public String getMcaTagSymbol() { return mcaTagSymbol; } }
5,006
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/handle/MCADictionaryIdHandle.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.handle; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.st2067_2.Composition; import javax.annotation.concurrent.Immutable; @Immutable public class MCADictionaryIdHandle extends Handle { private final Composition.VirtualTrack virtualTrack; private final UL mcaLabelDictionaryId; public MCADictionaryIdHandle(String handle, Composition.VirtualTrack virtualTrack, UL mcaLabelDictionaryId) { super(handle); this.virtualTrack = virtualTrack; this.mcaLabelDictionaryId = mcaLabelDictionaryId; } public Composition.VirtualTrack getVirtualTrack() { return virtualTrack; } public UL getMcaLabelDictionaryId() { return mcaLabelDictionaryId; } }
5,007
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/handle/VirtualTrackHandle.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.handle; import com.netflix.imflibrary.st2067_2.Composition; import javax.annotation.concurrent.Immutable; @Immutable public class VirtualTrackHandle extends Handle { private final Composition.VirtualTrack virtualTrack; public VirtualTrackHandle(String handle, Composition.VirtualTrack virtualTrack) { super(handle); this.virtualTrack = virtualTrack; } public Composition.VirtualTrack getVirtualTrack() { return virtualTrack; } }
5,008
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/handle/Handle.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.handle; import javax.annotation.concurrent.Immutable; @Immutable public abstract class Handle { private final String handle; public Handle(String handle) { this.handle = handle; } public String getHandle() { return handle; } }
5,009
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/Sequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro; import javax.annotation.concurrent.Immutable; @Immutable public abstract class Sequence { private final String annotaion; private final String handle; public Sequence(String annotaion, String handle) { this.annotaion = annotaion; this.handle = handle; } public String getAnnotaion() { return annotaion; } public String getHandle() { return handle; } }
5,010
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/ColorEncoding.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro; import org.smpte_ra.schemas._2067_102._2014.REC709FullRGB10ColorEncodingType; import org.smpte_ra.schemas._2067_102._2014.REC709RGB10ColorEncodingType; import org.smpte_ra.schemas._2067_102._2014.REC709RGB8ColorEncodingType; import org.smpte_ra.schemas._2067_102._2014.REC709YCrCb8ColorEncodingType; public enum ColorEncoding { REC709RGB10ColorEncoding(REC709RGB10ColorEncodingType.class.getName()), REC709YCrCb8ColorEncoding(REC709YCrCb8ColorEncodingType.class.getName()), REC709FullRGB10ColorEncoding(REC709FullRGB10ColorEncodingType.class.getName()), REC709RGB8ColorEncoding(REC709RGB8ColorEncodingType.class.getName()); private final String value; ColorEncoding(String value) { this.value = value; } public static ColorEncoding fromValue(String value) { for (ColorEncoding colorEncodingEnum: ColorEncoding.values()) { if (colorEncodingEnum.value.equals(value)) { return colorEncodingEnum; } } throw new IllegalArgumentException(value); } public String getValue() { return value; } }
5,011
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/Macro.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro; import javax.annotation.concurrent.Immutable; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * A class that models an OPL Macro. */ @Immutable public abstract class Macro { private final String name; private final String annotaion; private final List<Sequence> inputs; private final List<Sequence> outputs; public Macro(String name, String annotaion, Sequence input, Sequence output) { this.name = name; this.annotaion = annotaion; this.inputs = Collections.unmodifiableList(Arrays.asList(input)); this.outputs = Collections.unmodifiableList(Arrays.asList(output)); } public Macro(String name, String annotaion, List<Sequence> inputs, List<Sequence> outputs) { this.name = name; this.annotaion = annotaion; this.inputs = Collections.unmodifiableList(inputs); this.outputs = Collections.unmodifiableList(outputs); } public List<Sequence> getInputs() { return inputs; } public List<Sequence> getOutputs() { return outputs; } public String getAnnotaion() { return annotaion; } public String getName() { return name; } }
5,012
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/scale/ScaleOutputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.scale; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class ScaleOutputImageSequence extends Sequence { private final int width; private final int height; private final String boundaryCondition; private final ScaleAlgorithm scalingAlgorithmType; public ScaleOutputImageSequence(String annotation, String handle, int width, int height, String boundaryCondition, ScaleAlgorithm scalingAlgorithmType) { super(annotation, handle); this.width = width; this.height = height; this.boundaryCondition = boundaryCondition; this.scalingAlgorithmType = scalingAlgorithmType; } public int getHeight() { return height; } public int getWidth() { return width; } public String getBoundaryCondition() { return boundaryCondition; } public ScaleAlgorithm getScalingAlgorithmType() { return scalingAlgorithmType; } }
5,013
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/scale/ScaleAlgorithm.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.scale; import javax.annotation.concurrent.Immutable; @Immutable public abstract class ScaleAlgorithm { }
5,014
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/scale/ScaleMacro.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.scale; import com.netflix.imflibrary.st2067_100.macro.Macro; import javax.annotation.concurrent.Immutable; @Immutable public class ScaleMacro extends Macro { public ScaleMacro(String name, String annotaion, ScaleInputImageSequence input, ScaleOutputImageSequence output) { super(name, annotaion, input, output); } public ScaleInputImageSequence getScaleInputImageSequence() { return (ScaleInputImageSequence)this.getInputs().get(0); } public ScaleOutputImageSequence getScaleOutputImageSequence() { return (ScaleOutputImageSequence)this.getOutputs().get(0); } }
5,015
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/scale/ScaleInputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.scale; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class ScaleInputImageSequence extends Sequence { public ScaleInputImageSequence(String annotaion, String handle) { super(annotaion, handle); } }
5,016
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/scale/Lanczos.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.scale; import javax.annotation.concurrent.Immutable; @Immutable public class Lanczos extends ScaleAlgorithm { private final int parameterA; public Lanczos(int parameterA) { this.parameterA = parameterA; } public int getParameterA() { return parameterA; } }
5,017
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/preset/PresetMacro.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.preset; import com.netflix.imflibrary.st2067_100.macro.Macro; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; import java.util.ArrayList; @Immutable public class PresetMacro extends Macro { private final String preset; public PresetMacro(String name, String annotaion, String preset) { super(name, annotaion, new ArrayList<Sequence>(), new ArrayList<Sequence>()); this.preset = preset; } public String getPreset() { return preset; } }
5,018
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/crop/CropOutputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.crop; import com.netflix.imflibrary.st2067_100.macro.ColorEncoding; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class CropOutputImageSequence extends Sequence { private final RectanglePadding padding; private final ColorEncoding fillColor; public CropOutputImageSequence(String annotation, String handle, RectanglePadding padding, ColorEncoding fillColor) { super(annotation, handle); this.padding = padding; this.fillColor = fillColor; } public RectanglePadding getPadding() { return padding; } public ColorEncoding getFillColor() { return fillColor; } }
5,019
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/crop/CropMacro.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.crop; import com.netflix.imflibrary.st2067_100.macro.Macro; import javax.annotation.concurrent.Immutable; @Immutable public class CropMacro extends Macro { public CropMacro(String name, String annotaion, CropInputImageSequence input, CropOutputImageSequence output) { super(name, annotaion, input, output); } public CropInputImageSequence getCropInputImageSequence() { return (CropInputImageSequence)this.getInputs().get(0); } public CropOutputImageSequence getCropOutputImageSequence() { return (CropOutputImageSequence)this.getOutputs().get(0); } }
5,020
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/crop/RectanglePadding.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.crop; import javax.annotation.concurrent.Immutable; @Immutable public class RectanglePadding { private final int left; private final int right; private final int top; private final int bottom; public RectanglePadding(int left, int right, int top, int bottom) { this.left = left; this.right = right; this.top = top; this.bottom = bottom; } public int getBottom() { return bottom; } public int getLeft() { return left; } public int getRight() { return right; } public int getTop() { return top; } }
5,021
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/crop/MXFRectangle.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.crop; public enum MXFRectangle { STORED("Stored"), SAMPLED("Sampled"), DISPLAY("Display"), ACTIVE("Active"); private final String value; MXFRectangle(String value) { this.value = value; } public static MXFRectangle fromValue(String value) { for (MXFRectangle mxfRectangleEnum: MXFRectangle.values()) { if (mxfRectangleEnum.value.equals(value)) { return mxfRectangleEnum; } } throw new IllegalArgumentException(value); } }
5,022
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/crop/CropInputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.crop; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class CropInputImageSequence extends Sequence { private final MXFRectangle referenceRectangle; private final RectanglePadding inset; public CropInputImageSequence(String annotaion, String handle, MXFRectangle referenceRectangle, RectanglePadding inset) { super(annotaion, handle); this.referenceRectangle = referenceRectangle; this.inset = inset; } public MXFRectangle getReferenceRectangle() { return referenceRectangle; } public RectanglePadding getInset() { return inset; } }
5,023
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/audioRoutingMixing/AudioRoutingMixingMacro.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.audioRoutingMixing; import com.netflix.imflibrary.st2067_100.macro.Macro; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; import java.util.List; import java.util.stream.Collectors; @Immutable public class AudioRoutingMixingMacro extends Macro { public AudioRoutingMixingMacro(String name, String annotaion, List<? extends Sequence> outputAudioChannelList) { super(name, annotaion, getInputs(outputAudioChannelList), (List<Sequence>)outputAudioChannelList); } public List<OutputAudioChannel> getOutputAudioChannelList() { return this.getOutputs().stream().map(e -> (OutputAudioChannel)e).collect(Collectors.toList()); } private static List<Sequence> getInputs(List<? extends Sequence> outputAudioChannelList) { return outputAudioChannelList.stream().flatMap(e -> ((OutputAudioChannel)e).getInputEntityList().stream()).collect(Collectors.toList()); } }
5,024
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/audioRoutingMixing/InputEntity.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.audioRoutingMixing; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; import java.math.BigDecimal; @Immutable public class InputEntity extends Sequence { private final BigDecimal gain; public InputEntity(String annotaion, String handle, BigDecimal gain) { super(annotaion, handle); this.gain = gain; } }
5,025
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/audioRoutingMixing/OutputAudioChannel.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.audioRoutingMixing; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; @Immutable public class OutputAudioChannel extends Sequence { private final List<InputEntity> inputEntityList; public OutputAudioChannel(String annotation, String handle, List<InputEntity> inputEntityList) { super(annotation, handle); this.inputEntityList = Collections.unmodifiableList(inputEntityList); } public List<InputEntity> getInputEntityList() { return inputEntityList; } }
5,026
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/pixelEncoder/PixelEncoderInputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.pixelEncoder; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class PixelEncoderInputImageSequence extends Sequence { public PixelEncoderInputImageSequence(String annotaion, String handle) { super(annotaion, handle); } }
5,027
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/pixelEncoder/PixelEncoderOutputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.pixelEncoder; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class PixelEncoderOutputImageSequence extends Sequence { public PixelEncoderOutputImageSequence(String annotation, String handle) { super(annotation, handle); } }
5,028
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/pixelEncoder/PixelEncoderMacro.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.pixelEncoder; import com.netflix.imflibrary.st2067_100.macro.Macro; import javax.annotation.concurrent.Immutable; @Immutable public class PixelEncoderMacro extends Macro { public PixelEncoderMacro(String name, String annotaion, PixelEncoderInputImageSequence input, PixelEncoderOutputImageSequence output) { super(name, annotaion, input, output); } public PixelEncoderInputImageSequence getPixelEncoderInputImageSequence() { return (PixelEncoderInputImageSequence)this.getInputs().get(0); } public PixelEncoderOutputImageSequence getPixelEncoderOutputImageSequence() { return (PixelEncoderOutputImageSequence)this.getOutputs().get(0); } }
5,029
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/pixelDecoder/PixelDecoderOutputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.pixelDecoder; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class PixelDecoderOutputImageSequence extends Sequence { public PixelDecoderOutputImageSequence(String annotation, String handle) { super(annotation, handle); } }
5,030
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/pixelDecoder/PixelDecoderInputImageSequence.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.pixelDecoder; import com.netflix.imflibrary.st2067_100.macro.Sequence; import javax.annotation.concurrent.Immutable; @Immutable public class PixelDecoderInputImageSequence extends Sequence { public PixelDecoderInputImageSequence(String annotaion, String handle) { super(annotaion, handle); } }
5,031
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_100/macro/pixelDecoder/PixelDecoderMacro.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_100.macro.pixelDecoder; import com.netflix.imflibrary.st2067_100.macro.Macro; import javax.annotation.concurrent.Immutable; @Immutable public class PixelDecoderMacro extends Macro { public PixelDecoderMacro(String name, String annotaion, PixelDecoderInputImageSequence input, PixelDecoderOutputImageSequence output) { super(name, annotaion, input, output); } public PixelDecoderInputImageSequence getPixelDecoderInputImageSequence() { return (PixelDecoderInputImageSequence)this.getInputs().get(0); } public PixelDecoderOutputImageSequence getPixelDecoderOutputImageSequence() { return (PixelDecoderOutputImageSequence)this.getOutputs().get(0); } }
5,032
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/RESTfulInterfaces/IMPValidator.java
package com.netflix.imflibrary.RESTfulInterfaces; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.IndexTableSegment; import com.netflix.imflibrary.st0377.PartitionPack; import com.netflix.imflibrary.st0377.RandomIndexPack; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st0429_8.PackingList; import com.netflix.imflibrary.st0429_9.AssetMap; import com.netflix.imflibrary.st2067_100.OutputProfileList; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.st2067_2.Composition.VirtualTrack; import com.netflix.imflibrary.st2067_2.IMFEssenceComponentVirtualTrack; import com.netflix.imflibrary.st2067_201.IABTrackFileConstraints; import com.netflix.imflibrary.utils.ByteArrayByteRangeProvider; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.Utilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import javax.annotation.Nullable; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * A RESTful interface for validating an IMF Master Package. */ public class IMPValidator { private static final Logger logger = LoggerFactory.getLogger(IMPValidator.class); /** * A stateless method that determines if the Asset type of the payload is an IMF AssetMap, Packinglist or Composition * @param payloadRecord - a payload record corresponding to the asset whose type needs to be confirmed * Note: for now this method only supports text/xml documents identified in the PKL * application/mxf asset types cannot be determined. * @return asset type of the payload either one of AssetMap, PackingList or Composition * @throws IOException - any I/O related error is exposed through an IOException */ public static PayloadRecord.PayloadAssetType getPayloadType(PayloadRecord payloadRecord) throws IOException { ResourceByteRangeProvider resourceByteRangeProvider = new ByteArrayByteRangeProvider(payloadRecord.getPayload()); if(AssetMap.isFileOfSupportedSchema(resourceByteRangeProvider)){ return PayloadRecord.PayloadAssetType.AssetMap; } else if(PackingList.isFileOfSupportedSchema(resourceByteRangeProvider)){ return PayloadRecord.PayloadAssetType.PackingList; } else if(ApplicationComposition.isCompositionPlaylist(resourceByteRangeProvider)){ return PayloadRecord.PayloadAssetType.CompositionPlaylist; } else if(OutputProfileList.isOutputProfileList(resourceByteRangeProvider)){ return PayloadRecord.PayloadAssetType.OutputProfileList; } return PayloadRecord.PayloadAssetType.Unknown; } /** * A stateless method that will validate an IMF PackingList document * @param pkl - a payload record for a Packing List document * @return list of error messages encountered while validating a Packing List document * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validatePKL(PayloadRecord pkl) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); if(pkl.getPayloadAssetType() != PayloadRecord.PayloadAssetType.PackingList){ throw new IMFException(String.format("Payload asset type is %s, expected asset type %s", pkl .getPayloadAssetType(), PayloadRecord.PayloadAssetType.PackingList.toString()), imfErrorLogger); } try{ PackingList packingList = new PackingList(new ByteArrayByteRangeProvider(pkl.getPayload())); imfErrorLogger.addAllErrors(packingList.getErrors()); } catch (IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } return imfErrorLogger.getErrors(); } /** * A stateless method that will validate an IMF AssetMap document * @param assetMapPayload - a payload record for an AssetMap document * @return list of error messages encountered while validating an AssetMap document * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validateAssetMap(PayloadRecord assetMapPayload) throws IOException { if(assetMapPayload.getPayloadAssetType() != PayloadRecord.PayloadAssetType.AssetMap){ throw new IMFException(String.format("Payload asset type is %s, expected asset type %s", assetMapPayload .getPayloadAssetType(), PayloadRecord.PayloadAssetType.AssetMap.toString())); } try{ AssetMap assetMap = new AssetMap(new ByteArrayByteRangeProvider(assetMapPayload.getPayload())); return assetMap.getErrors(); } catch(IMFException e) { return e.getErrors(); } } /** * A stateless method that will validate IMF AssetMap and PackingList documents for all the data * that should be cross referenced by both * @param assetMapPayload - a payload record for an AssetMap document * @param pklPayloads - a list of payload records for Packing List documents referenced by the AssetMap * @return list of error messages encountered while validating an AssetMap document * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validatePKLAndAssetMap(PayloadRecord assetMapPayload, List<PayloadRecord> pklPayloads) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> packingListPayloadRecords = Collections.unmodifiableList(pklPayloads); if(assetMapPayload.getPayloadAssetType() != PayloadRecord.PayloadAssetType.AssetMap){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Payload asset type is %s, expected asset type %s", assetMapPayload .getPayloadAssetType(), PayloadRecord.PayloadAssetType.AssetMap.toString())); } ResourceByteRangeProvider assetMapByteRangeProvider = new ByteArrayByteRangeProvider(assetMapPayload.getPayload()); AssetMap assetMapObjectModel = null; try { assetMapObjectModel = new AssetMap(assetMapByteRangeProvider); imfErrorLogger.addAllErrors(assetMapObjectModel.getErrors()); if(assetMapObjectModel.getPackingListAssets().size() == 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Asset map should reference atleast one PackingList, %d " + "references found", assetMapObjectModel.getPackingListAssets().size())); } } catch( IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } List<ResourceByteRangeProvider> packingLists = new ArrayList<>(); for(PayloadRecord payloadRecord : packingListPayloadRecords){ if(payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.PackingList){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_MASTER_PACKAGE_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels .FATAL, String.format("Payload asset type is %s, expected asset type %s", assetMapPayload.getPayloadAssetType(), PayloadRecord.PayloadAssetType.PackingList.toString())); } else { packingLists.add(new ByteArrayByteRangeProvider(payloadRecord.getPayload())); } } if(packingLists.size() == 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_MASTER_PACKAGE_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Atleast one PackingList is expected, %d were detected", packingLists.size())); } if(imfErrorLogger.hasFatalErrors()) { return imfErrorLogger.getErrors(); } List<PackingList> packingListObjectModels = new ArrayList<>(); for (ResourceByteRangeProvider resourceByteRangeProvider : packingLists) { try { PackingList packingList = new PackingList(resourceByteRangeProvider); packingListObjectModels.add(packingList); imfErrorLogger.addAllErrors(packingList.getErrors()); } catch (IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); return imfErrorLogger.getErrors(); } } List<UUID> assetUUIDsAssetMapList = new ArrayList<>(); for(AssetMap.Asset asset : assetMapObjectModel.getAssetList()){ assetUUIDsAssetMapList.add(asset.getUUID()); } /* //Sort the UUIDs in the AssetMap assetUUIDsAssetMapList.sort(new Comparator<UUID>() { @Override public int compare(UUID o1, UUID o2) { return o1.compareTo(o2); } }); */ /* Collect all the assets in all of the PKLs that are a part of this IMP delivery */ List<UUID> assetUUIDsPackingList = new ArrayList<>(); for(PackingList packingList : packingListObjectModels) { assetUUIDsPackingList.add(packingList.getUUID());//PKL's UUID is also added to this list since that should be present in the AssetMap for (PackingList.Asset asset : packingList.getAssets()) { assetUUIDsPackingList.add(asset.getUUID()); } } /* //Sort the UUIDs in the PackingList assetUUIDsPackingList.sort(new Comparator<UUID>() { @Override public int compare(UUID o1, UUID o2) { return o1.compareTo(o2); } }); */ /* Check to see if all the Assets referenced in the PKL are also referenced by the Asset Map */ Set<UUID> assetUUIDsAssetMapSet = new HashSet<>(assetUUIDsAssetMapList); Set<UUID> assetUUIDsPKLSet = new HashSet<>(assetUUIDsPackingList); StringBuilder unreferencedPKLAssetsUUIDs = new StringBuilder(); for(UUID uuid : assetUUIDsPKLSet){ if(!assetUUIDsAssetMapSet.contains(uuid)) { unreferencedPKLAssetsUUIDs.append(uuid.toString()); unreferencedPKLAssetsUUIDs.append(", "); } } if(!unreferencedPKLAssetsUUIDs.toString().isEmpty()){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The following UUID/s %s in the Packing list are not referenced by the AssetMap.", unreferencedPKLAssetsUUIDs.toString())); return imfErrorLogger.getErrors(); } /* Check if all the assets in the AssetMap that are supposed to be PKLs have the same UUIDs as the PKLs themselves */ Set<UUID> packingListAssetsUUIDsSet = new HashSet<>(); for(AssetMap.Asset asset : assetMapObjectModel.getPackingListAssets()){ packingListAssetsUUIDsSet.add(asset.getUUID()); } StringBuilder unreferencedPKLUUIDs = new StringBuilder(); for(PackingList packingList : packingListObjectModels) { if (!packingListAssetsUUIDsSet.contains(packingList.getUUID())) { unreferencedPKLUUIDs.append(packingList.getUUID()); } } if(!unreferencedPKLUUIDs.toString().isEmpty()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The following Packing lists %s are not referenced in the AssetMap", unreferencedPKLUUIDs.toString())); return imfErrorLogger.getErrors(); } return imfErrorLogger.getErrors(); } /** * A stateless method that will validate an IMF Composition document * @param cpl - a payload record for a Composition document * @return list of error messages encountered while validating an AssetMap document * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validateCPL(PayloadRecord cpl) throws IOException{ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); if(cpl.getPayloadAssetType() != PayloadRecord.PayloadAssetType.CompositionPlaylist){ throw new IMFException(String.format("Payload asset type is %s, expected asset type %s", cpl .getPayloadAssetType(), PayloadRecord.PayloadAssetType.CompositionPlaylist.toString())); } try { ApplicationCompositionFactory.getApplicationComposition(new ByteArrayByteRangeProvider(cpl.getPayload()), imfErrorLogger); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } return imfErrorLogger.getErrors(); } /** * A stateless method to retrieve all the VirtualTracks that are a part of a Composition * @param cpl - a payload corresponding to the Composition Playlist * @return list of VirtualTracks * @throws IOException - any I/O related error is exposed through an IOException */ public static List<? extends VirtualTrack> getVirtualTracks(PayloadRecord cpl) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<ErrorLogger.ErrorObject> errorList = validateCPL(cpl); imfErrorLogger.addAllErrors(errorList); if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Virtual track failed validation", imfErrorLogger); } ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new ByteArrayByteRangeProvider(cpl.getPayload()), imfErrorLogger); if(applicationComposition == null) { return new ArrayList<>(); } return applicationComposition.getVirtualTracks(); } /** * A stateless method that can be used to determine if a Virtual Track in a Composition is conformant. Conformance checks * perform deeper inspection of the Composition and the EssenceDescriptors corresponding to the Virtual Track * @param cplPayloadRecord a payload record corresponding to the Composition payload * @param virtualTrack that needs to be conformed in the Composition * @param essencesHeaderPartitionPayloads list of payload records containing the raw bytes of the HeaderPartitions of the IMF Track files that are a part of * the Virtual Track to be conformed * @return list of error messages encountered while performing conformance validation of the Composition document * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> isVirtualTrackInCPLConformed(PayloadRecord cplPayloadRecord, VirtualTrack virtualTrack, List<PayloadRecord> essencesHeaderPartitionPayloads) throws IOException { List<VirtualTrack> virtualTracks = new ArrayList<>(); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); virtualTracks.add(virtualTrack); imfErrorLogger.addAllErrors(checkVirtualTrackAndEssencesHeaderPartitionPayloadRecords(virtualTracks, essencesHeaderPartitionPayloads)); if(imfErrorLogger.hasFatalErrors()){ return imfErrorLogger.getErrors(); } imfErrorLogger.addAllErrors(conformVirtualTracksInCPL(cplPayloadRecord, essencesHeaderPartitionPayloads, false)); return imfErrorLogger.getErrors(); } /** * A stateless method that can be used to determine if a Composition is conformant. Conformance checks * perform deeper inspection of the Composition and the EssenceDescriptors corresponding to all the * Virtual Tracks that are a part of the Composition * @param cplPayloadRecord a payload record corresponding to the Composition payload * @param essencesHeaderPartitionPayloads list of payload records containing the raw bytes of the HeaderPartitions of the IMF Track files that are a part of the Virtual Track/s in the Composition * @return list of error messages encountered while performing conformance validation of the Composition document * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> areAllVirtualTracksInCPLConformed( PayloadRecord cplPayloadRecord, List<PayloadRecord> essencesHeaderPartitionPayloads) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new ByteArrayByteRangeProvider(cplPayloadRecord.getPayload()), imfErrorLogger); if(applicationComposition == null) { return imfErrorLogger.getErrors(); } List<VirtualTrack> virtualTracks = new ArrayList<>(applicationComposition.getVirtualTracks()); imfErrorLogger.addAllErrors(checkVirtualTrackAndEssencesHeaderPartitionPayloadRecords(virtualTracks, essencesHeaderPartitionPayloads)); if(imfErrorLogger.hasFatalErrors()){ return imfErrorLogger.getErrors(); } imfErrorLogger.addAllErrors(conformVirtualTracksInCPL(cplPayloadRecord, essencesHeaderPartitionPayloads, true)); return imfErrorLogger.getErrors(); } public static List<ErrorLogger.ErrorObject> conformVirtualTracksInCPL(PayloadRecord cplPayloadRecord, List<PayloadRecord> essencesHeaderPartitionPayloads,boolean conformAllVirtualTracks) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> essencesHeaderPartition = Collections.unmodifiableList(essencesHeaderPartitionPayloads); try { imfErrorLogger.addAllErrors(validateCPL(cplPayloadRecord)); if (imfErrorLogger.hasFatalErrors()) return Collections.unmodifiableList(imfErrorLogger.getErrors()); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new ByteArrayByteRangeProvider(cplPayloadRecord.getPayload()), imfErrorLogger); if(applicationComposition == null) { return imfErrorLogger.getErrors(); } imfErrorLogger.addAllErrors(validateIMFTrackFileHeaderMetadata(essencesHeaderPartition)); List<Composition.HeaderPartitionTuple> headerPartitionTuples = new ArrayList<>(); for (PayloadRecord payloadRecord : essencesHeaderPartition) { if (payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_MASTER_PACKAGE_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.FATAL, String.format ("Payload asset type is %s, expected asset type %s", payloadRecord .getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); continue; } headerPartitionTuples.add(new Composition.HeaderPartitionTuple(new HeaderPartition(new ByteArrayDataProvider(payloadRecord.getPayload()), 0L, (long) payloadRecord.getPayload().length, imfErrorLogger), new ByteArrayByteRangeProvider(payloadRecord.getPayload()))); } if (imfErrorLogger.hasFatalErrors()) { return imfErrorLogger.getErrors(); } imfErrorLogger.addAllErrors(applicationComposition.conformVirtualTracksInComposition(Collections.unmodifiableList (headerPartitionTuples), conformAllVirtualTracks)); imfErrorLogger.addAllErrors(applicationComposition.getErrors()); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } return imfErrorLogger.getErrors(); } /** * A stateless method that determines if 2 or more Composition documents corresponding to the same title can be inferred to * represent the same presentation timeline. This method is present to work around current limitations in the IMF eco system * wherein CPL's might not be built incrementally to include all the IMF essences that are a part of the same timeline * @param referenceCPLPayloadRecord - a payload record corresponding to a Reference Composition document, perhaps the first * composition playlist document that was delivered for a particular composition. * @param cplPayloads - a list of payload records corresponding to each of the Composition documents * that need to be verified for mergeability * @return a boolean indicating if the CPLs can be merged or not * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> isCPLMergeable(PayloadRecord referenceCPLPayloadRecord, List<PayloadRecord> cplPayloads) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> cplPayloadRecords = Collections.unmodifiableList(cplPayloads); List<ApplicationComposition> applicationCompositions = new ArrayList<>(); try { ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new ByteArrayByteRangeProvider(referenceCPLPayloadRecord.getPayload()), imfErrorLogger); if(applicationComposition == null) { return imfErrorLogger.getErrors(); } applicationCompositions.add(applicationComposition); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } for (PayloadRecord cpl : cplPayloadRecords) { try { ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new ByteArrayByteRangeProvider(cpl.getPayload()), imfErrorLogger); if(applicationComposition != null) { applicationCompositions.add(applicationComposition); } } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } if(imfErrorLogger.hasFatalErrors()) { return imfErrorLogger.getErrors(); } VirtualTrack referenceVideoVirtualTrack = applicationCompositions.get(0).getVideoVirtualTrack(); UUID referenceCPLUUID = applicationCompositions.get(0).getUUID(); for (int i = 1; i < applicationCompositions.size(); i++) { if (!referenceVideoVirtualTrack.equivalent(applicationCompositions.get(i).getVideoVirtualTrack())) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("CPL Id %s can't be merged with Reference CPL Id %s, since the video virtual tracks do not seem to represent the same timeline.", applicationCompositions.get(i).getUUID(), referenceCPLUUID)); } } /** * Perform AudioTrack mergeability checks * 1) Identify AudioTracks that are the same language * 2) Compare language tracks to see if they represent the same timeline */ Boolean bAudioVirtualTrackMapFail = false; List<Map<Set<DOMNodeObjectModel>, ? extends VirtualTrack>> audioVirtualTracksMapList = new ArrayList<>(); for (ApplicationComposition applicationComposition : applicationCompositions) { try { audioVirtualTracksMapList.add(applicationComposition.getAudioVirtualTracksMap()); } catch(IMFException e) { bAudioVirtualTrackMapFail = false; imfErrorLogger.addAllErrors(e.getErrors()); } } if(!bAudioVirtualTrackMapFail) { Map<Set<DOMNodeObjectModel>, ? extends VirtualTrack> referenceAudioVirtualTracksMap = audioVirtualTracksMapList.get(0); for (int i = 1; i < audioVirtualTracksMapList.size(); i++) { if (!compareAudioVirtualTrackMaps(Collections.unmodifiableMap(referenceAudioVirtualTracksMap), Collections.unmodifiableMap(audioVirtualTracksMapList.get(i)), imfErrorLogger)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("CPL Id %s can't be merged with Reference CPL Id %s, since 2 same language audio tracks do not seem to represent the same timeline.", applicationCompositions.get(i).getUUID(), referenceCPLUUID)); } } } /** * Perform MarkerTrack mergeability checks */ Composition.VirtualTrack referenceMarkerVirtualTrack = applicationCompositions.get(0).getMarkerVirtualTrack(); if (referenceMarkerVirtualTrack != null) { UUID referenceMarkerCPLUUID = applicationCompositions.get(0).getUUID(); for (int i = 1; i < applicationCompositions.size(); i++) { if (!referenceMarkerVirtualTrack.equivalent(applicationCompositions.get(i).getMarkerVirtualTrack())) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("CPL Id %s can't be merged with Reference CPL Id %s, since the marker virtual tracks do not seem to represent the same timeline.", applicationCompositions.get(i).getUUID(), referenceMarkerCPLUUID)); } } } return imfErrorLogger.getErrors(); } /* IMF essence related inspection calls*/ /** * A stateless method that will return the size of the RandomIndexPack present within a MXF file. In a typical IMF workflow * this would be the first method that would need to be invoked to perform IMF essence component level validation * @param essenceFooter4Bytes - the last 4 bytes of the MXF file used to infer the size of the RandomIndexPack * @return a long integer value representing the size of the RandomIndexPack */ public static Long getRandomIndexPackSize(PayloadRecord essenceFooter4Bytes){ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); if(essenceFooter4Bytes.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssenceFooter4Bytes){ throw new IMFException(String.format("Payload asset type is %s, expected asset type %s", essenceFooter4Bytes.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssenceFooter4Bytes .toString()), imfErrorLogger); } return (long)(ByteBuffer.wrap(essenceFooter4Bytes.getPayload()).getInt()); } /** * A stateless method that will read and parse the RandomIndexPack within a MXF file and return a list of byte offsets * corresponding to the partitions of the MXF file. In a typical IMF workflow this would be the second method after * {@link #getRandomIndexPackSize(PayloadRecord)} that would need to be invoked to perform IMF essence component * level validation * @param randomIndexPackPayload - a payload containing the raw bytes corresponding to the RandomIndexPack of the MXF file * @param randomIndexPackSize - size of the RandomIndexPack of the MXF file * @return list of long integer values representing the byte offsets of the partitions in the MXF file * @throws IOException - any I/O related error is exposed through an IOException */ public static List<Long> getEssencePartitionOffsets(PayloadRecord randomIndexPackPayload, Long randomIndexPackSize) throws IOException { if(randomIndexPackPayload.getPayload().length != randomIndexPackSize){ throw new IllegalArgumentException(String.format("RandomIndexPackSize passed in is = %d, RandomIndexPack payload size = %d, they should be equal", randomIndexPackSize, randomIndexPackPayload.getPayload().length)); } RandomIndexPack randomIndexPack = new RandomIndexPack(new ByteArrayDataProvider(randomIndexPackPayload.getPayload()), 0L, randomIndexPackSize); return randomIndexPack.getAllPartitionByteOffsets(); } /** * A stateless method that validates an IMFEssenceComponent's header partition and verifies MXF OP1A and IMF compliance. This could be utilized * to perform preliminary validation of IMF essences * @param essencesHeaderPartitionPayloads - a list of IMF Essence Component header partition payloads * @return a list of errors encountered while performing compliance checks on the IMF Essence Component Header partition * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validateIMFTrackFileHeaderMetadata(List<PayloadRecord> essencesHeaderPartitionPayloads) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> essencesHeaderPartition = Collections.unmodifiableList(essencesHeaderPartitionPayloads); for(PayloadRecord payloadRecord : essencesHeaderPartition){ if(payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format ("Payload asset type is %s, expected asset type %s", payloadRecord .getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); continue; } HeaderPartition headerPartition = null; try { headerPartition = new HeaderPartition(new ByteArrayDataProvider(payloadRecord.getPayload()), 0L, (long)payloadRecord.getPayload().length, imfErrorLogger); MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); if (headerPartitionIMF.getEssenceType() == HeaderPartition.EssenceTypeEnum.IABEssence) { IABTrackFileConstraints.checkCompliance(headerPartitionIMF, imfErrorLogger); } } catch (IMFException | MXFException e){ if(headerPartition != null) { Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("IMFTrackFile with ID %s has fatal errors", packageUUID.toString()))); } if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } } } return imfErrorLogger.getErrors(); } /** * A stateless method that returns the RFC-5646 Spoken Language Tag present in the Header Partition of an Audio Essence * @param essencesHeaderPartition - a list of payloads corresponding to the Header Partitions of TrackFiles that are a part of an Audio VirtualTrack * @param audioVirtualTrack - the audio virtual track whose spoken language needs to be ascertained * @return string corresponding to the RFC-5646 language tag present in the header partition of the Audio Essence * @throws IOException - any I/O related error is exposed through an IOException */ @Nullable public static String getAudioTrackSpokenLanguage(VirtualTrack audioVirtualTrack, List<PayloadRecord> essencesHeaderPartition) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); if(audioVirtualTrack.getSequenceTypeEnum() != Composition.SequenceTypeEnum.MainAudioSequence){ throw new IMFException(String.format("Virtual track that was passed in is of type %s, spoken language is " + "currently supported for only %s tracks", audioVirtualTrack.getSequenceTypeEnum().toString(), Composition.SequenceTypeEnum.MainAudioSequence.toString())); } List<VirtualTrack> virtualTracks = new ArrayList<>(); virtualTracks.add(audioVirtualTrack); imfErrorLogger.addAllErrors(checkVirtualTrackAndEssencesHeaderPartitionPayloadRecords(virtualTracks, essencesHeaderPartition)); if(imfErrorLogger.hasFatalErrors()){ throw new IMFException(String.format("Fatal Errors were detected when trying to verify the Virtual Track and Essence Header Partition payloads %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors()))); } Set<String> audioLanguageSet = new HashSet<>(); for (PayloadRecord payloadRecord : essencesHeaderPartition){ if (payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) { throw new IMFException(String.format("Payload asset type is %s, expected asset type %s", payloadRecord.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString ()), imfErrorLogger); } HeaderPartition headerPartition = new HeaderPartition(new ByteArrayDataProvider(payloadRecord.getPayload()), 0L, (long) payloadRecord.getPayload().length, imfErrorLogger); audioLanguageSet.add(headerPartition.getAudioEssenceSpokenLanguage()); } if(audioLanguageSet.size() > 1){ throw new IMFException(String.format("It seems that RFC-5646 spoken language is not consistent across " + "resources of this Audio Virtual Track, found references to %s languages in the HeaderPartition", Utilities.serializeObjectCollectionToString(audioLanguageSet)), imfErrorLogger); } return audioLanguageSet.iterator().next(); } private static boolean compareAudioVirtualTrackMaps(Map<Set<DOMNodeObjectModel>, ? extends VirtualTrack> map1, Map<Set<DOMNodeObjectModel>, ? extends VirtualTrack> map2, IMFErrorLogger imfErrorLogger){ boolean result = true; Iterator refIterator = map1.entrySet().iterator(); while(refIterator.hasNext()){ Map.Entry<Set<DOMNodeObjectModel>, VirtualTrack> entry = (Map.Entry<Set<DOMNodeObjectModel>, VirtualTrack>) refIterator.next(); VirtualTrack refVirtualTrack = entry.getValue(); VirtualTrack otherVirtualTrack = map2.get(entry.getKey()); if(otherVirtualTrack != null){//If we identified an audio virtual track with the same essence description we can compare, else no point comparing hence the default result = true. result &= refVirtualTrack.equivalent(otherVirtualTrack); } } return result; } private static List<ErrorLogger.ErrorObject> checkVirtualTrackAndEssencesHeaderPartitionPayloadRecords(List<VirtualTrack> virtualTracks, List<PayloadRecord> essencesHeaderPartition) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Set<UUID> trackFileIDsSet = new HashSet<>(); for (PayloadRecord payloadRecord : essencesHeaderPartition){ if (payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) { throw new IMFException(String.format("Payload asset type is %s, expected asset type %s", payloadRecord.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString ()), imfErrorLogger); } HeaderPartition headerPartition = new HeaderPartition(new ByteArrayDataProvider(payloadRecord.getPayload()), 0L, (long) payloadRecord.getPayload().length, imfErrorLogger); Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); trackFileIDsSet.add(packageUUID); try { /** * Add the Top Level Package UUID to the set of TrackFileIDs, this is required to validate that the essences header partition that were passed in * are in fact from the constituent resources of the VirtualTack */ MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); if (headerPartitionIMF.hasMatchingEssence(HeaderPartition.EssenceTypeEnum.IABEssence)) { IABTrackFileConstraints.checkCompliance(headerPartitionIMF, imfErrorLogger); } } catch (IMFException | MXFException e){ if(headerPartition != null) { } imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("IMFTrackFile with ID %s has fatal errors", packageUUID.toString()))); if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } } } Set<UUID> virtualTrackResourceIDsSet = new HashSet<>(); for(Composition.VirtualTrack virtualTrack : virtualTracks){ if(virtualTrack instanceof IMFEssenceComponentVirtualTrack) { virtualTrackResourceIDsSet.addAll(IMFEssenceComponentVirtualTrack.class.cast(virtualTrack).getTrackResourceIds()); } } /** * Following check ensures that the Header Partitions corresponding to all the Resources of the VirtualTracks were passed in. */ Set<UUID> unreferencedResourceIDsSet = new HashSet<>(); for(UUID uuid : virtualTrackResourceIDsSet){ if(!trackFileIDsSet.contains(uuid)){ unreferencedResourceIDsSet.add(uuid); } } if(unreferencedResourceIDsSet.size() > 0){ imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("It seems that no EssenceHeaderPartition data was passed in for " + "VirtualTrack Resource Ids %s, please verify that the correct Header Partition payloads for the " + "Virtual Track were passed in", Utilities.serializeObjectCollectionToString (unreferencedResourceIDsSet)))); } /** * Following check ensures that the Header Partitions corresponding to only the Resource that are a part of the VirtualTracks were passed in. */ Set<UUID> unreferencedTrackFileIDsSet = new HashSet<>(); for(UUID uuid : trackFileIDsSet){ if(!virtualTrackResourceIDsSet.contains(uuid)){ unreferencedTrackFileIDsSet.add(uuid); } } if(unreferencedTrackFileIDsSet.size() > 0){ imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("It seems that EssenceHeaderPartition data was passed in for " + "Resource Ids %s which are not part of this virtual track, please verify that only the Header " + "Partition payloads for the Virtual Track were passed in", Utilities .serializeObjectCollectionToString(unreferencedTrackFileIDsSet)))); } return imfErrorLogger.getErrors(); } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <filePath1><filePath2><filePath3> - List of files corresponding to the AssetMap, PackingList and CompositionPlaylist in no particular order%n", IMPValidator.class.getName())); return sb.toString(); } public static void main(String args[]) throws IOException, URISyntaxException, SAXException, JAXBException { if (args.length != 3) { logger.error(usage()); throw new IllegalArgumentException("Invalid parameters"); } List<ErrorLogger.ErrorObject> errors = new ArrayList<>(); File assetMapFile=null, packingListFile=null, compositionPlaylistFile=null; for(String arg : args) { File inputFile = new File(arg); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.Unknown, 0L, resourceByteRangeProvider.getResourceSize()); PayloadRecord.PayloadAssetType payloadAssetType = IMPValidator.getPayloadType(payloadRecord); payloadRecord = new PayloadRecord(bytes, payloadAssetType, 0L, resourceByteRangeProvider.getResourceSize()); switch (payloadAssetType) { case PackingList: packingListFile = inputFile; logger.info(String.format("File %s was identified as a PackingList document.", packingListFile.getName())); errors.addAll(validatePKL(payloadRecord)); break; case AssetMap: assetMapFile = inputFile; logger.info(String.format("File %s was identified as a AssetMap document.", assetMapFile.getName())); errors.addAll(validateAssetMap(payloadRecord)); break; case CompositionPlaylist: compositionPlaylistFile = inputFile; logger.info(String.format("File %s was identified as a CompositionPlaylist document.", compositionPlaylistFile.getName())); errors.addAll(validateCPL(payloadRecord)); break; default: throw new IllegalArgumentException(String.format("UnsupportedSequence AssetType for file %s", inputFile.getName())); } } if(assetMapFile != null && packingListFile != null){ ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetMapFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1); PayloadRecord assetMapPayloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.AssetMap, 0L, resourceByteRangeProvider.getResourceSize()); resourceByteRangeProvider = new FileByteRangeProvider(packingListFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1); PayloadRecord packingListPayloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.PackingList, 0L, resourceByteRangeProvider.getResourceSize()); List<PayloadRecord> packingListPayloadRecords = new ArrayList<>(); packingListPayloadRecords.add(packingListPayloadRecord); errors.addAll(IMPValidator.validatePKLAndAssetMap(assetMapPayloadRecord, packingListPayloadRecords)); } if(errors.size() > 0){ long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("AssetMap has %d errors and %d warnings", errors.size() - warningCount, warningCount)); for(ErrorLogger.ErrorObject errorObject : errors){ if(errorObject.getErrorLevel()!= IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if(errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } } else{ logger.info("No errors were detected in the AssetMap Document"); } } /** * A stateless method that validates IndexTable segments within partitions * @param essencesPartitionPayloads - a list of IMF Essence Component partition payloads * @return a list of errors encountered while performing compliance checks on IndexTable segments within partition payloads * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validateIndexTableSegments(List<PayloadRecord> essencesPartitionPayloads) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); for(PayloadRecord payloadRecord : essencesPartitionPayloads){ if(payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format ("Payload asset type is %s, expected asset type %s", payloadRecord .getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); continue; } try { PartitionPack partitionPack = new PartitionPack(new ByteArrayDataProvider(payloadRecord.getPayload())); if (partitionPack.hasIndexTableSegments()) {//logic to provide as an input stream the portion of the archive that contains a Partition ByteProvider imfEssenceComponentByteProvider = new ByteArrayDataProvider(payloadRecord.getPayload()); long numBytesToRead = payloadRecord.getPayload().length; long numBytesRead = 0; while (numBytesRead < numBytesToRead) { KLVPacket.Header header = new KLVPacket.Header(imfEssenceComponentByteProvider, 0); numBytesRead += header.getKLSize(); if (IndexTableSegment.isValidKey(header.getKey())) { new IndexTableSegment(imfEssenceComponentByteProvider, header); } else { imfEssenceComponentByteProvider.skipBytes(header.getVSize()); } numBytesRead += header.getVSize(); } } } catch (MXFException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, e.getMessage()); } } return imfErrorLogger.getErrors(); } /** * A stateless method that will validate an IMF OutputProfileList document * @param opl - a payload record for a OutputProfileList document * @return list of error messages encountered while validating an OutputProfileList document * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validateOPL(PayloadRecord opl) throws IOException{ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); if(opl.getPayloadAssetType() != PayloadRecord.PayloadAssetType.OutputProfileList){ throw new IMFException(String.format("Payload asset type is %s, expected asset type %s", opl .getPayloadAssetType(), PayloadRecord.PayloadAssetType.OutputProfileList.toString())); } try { OutputProfileList.getOutputProfileListType(new ByteArrayByteRangeProvider(opl.getPayload()), imfErrorLogger); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } return imfErrorLogger.getErrors(); } /** * A stateless method, used for IMP containing IAB tracks, that will validate that the index edit rate in the index segment matches the one in the descriptor (according to Section 5.7 of SMPTE ST 2067-201:2019) * @param headerPartitionPayloadRecords - a list of IMF Essence Component partition payloads for header partitions * @param indexSegmentPayloadRecords - a list of IMF Essence Component partition payloads for index partitions * @return list of error messages encountered while validating * @throws IOException - any I/O related error is exposed through an IOException */ public static List<ErrorLogger.ErrorObject> validateIndexEditRate(List<PayloadRecord> headerPartitionPayloadRecords, List<PayloadRecord> indexSegmentPayloadRecords) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> essencesHeaderPartition = Collections.unmodifiableList(headerPartitionPayloadRecords); for(PayloadRecord headerPayloadRecord : essencesHeaderPartition){ if(headerPayloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Payload asset type is %s, expected asset type %s", headerPayloadRecord.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); continue; } HeaderPartition headerPartition = null; try { headerPartition = new HeaderPartition(new ByteArrayDataProvider(headerPayloadRecord.getPayload()), 0L, (long) headerPayloadRecord.getPayload().length, imfErrorLogger); MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); for (PayloadRecord indexPayloadRecord : indexSegmentPayloadRecords) { if (indexPayloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Payload asset type is %s, expected asset type %s", indexPayloadRecord.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); continue; } PartitionPack partitionPack = new PartitionPack(new ByteArrayDataProvider(indexPayloadRecord.getPayload())); if (partitionPack.hasIndexTableSegments()) {//logic to provide as an input stream the portion of the archive that contains a Partition ByteProvider imfEssenceComponentByteProvider = new ByteArrayDataProvider(indexPayloadRecord.getPayload()); long numBytesToRead = indexPayloadRecord.getPayload().length; long numBytesRead = 0; while (numBytesRead < numBytesToRead) { KLVPacket.Header header = new KLVPacket.Header(imfEssenceComponentByteProvider, 0); numBytesRead += header.getKLSize(); if (IndexTableSegment.isValidKey(header.getKey())) { IndexTableSegment indexTableSegment = new IndexTableSegment(imfEssenceComponentByteProvider, header); if (headerPartitionIMF.hasMatchingEssence(HeaderPartition.EssenceTypeEnum.IABEssence)) { IABTrackFileConstraints.checkIndexEditRate(headerPartitionIMF, indexTableSegment, imfErrorLogger); } } else { imfEssenceComponentByteProvider.skipBytes(header.getVSize()); } numBytesRead += header.getVSize(); } } } } catch (IMFException | MXFException e){ if(headerPartition != null) { Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("IMFTrackFile with ID %s has fatal errors", packageUUID.toString()))); } if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } } } return imfErrorLogger.getErrors(); } }
5,033
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/RESTfulInterfaces/PayloadRecord.java
package com.netflix.imflibrary.RESTfulInterfaces; import javax.annotation.Nullable; import java.util.Arrays; /** * An object model for submitting Payloads to Photon */ public class PayloadRecord { private final byte[] payload; private final PayloadAssetType payloadAssetType; private final Long originalFileOffset; private final Long originalSize; /** * A constructor for the Payloads to be passed in to Photon for validation/metadata extraction. * @param payload - a byte[] consisting of the raw bytes of the payload * @param payloadAssetType - a payload asset type to indicate what data is being passed in * @param originalFileOffset - offset of the data in the original asset/file * @param originalSize - size of the payload as read from the original asset/file */ public PayloadRecord(byte[] payload, PayloadAssetType payloadAssetType, @Nullable Long originalFileOffset, @Nullable Long originalSize){ this.payload = Arrays.copyOf(payload, payload.length); this.payloadAssetType = payloadAssetType; this.originalFileOffset = originalFileOffset; this.originalSize = originalSize; } /** * A getter for the Payload raw bytes * @return a byte[] containing the raw bytes that need to be analyzed */ public byte[] getPayload(){ return Arrays.copyOf(payload, payload.length); } /** * A getter for the Payload Asset type * @return the PayloadAssetType of the payload */ public PayloadAssetType getPayloadAssetType(){ return this.payloadAssetType; } /** * Enumerates the different AssetTypes that can be passed to this library for analysis */ public enum PayloadAssetType { CompositionPlaylist("Composition"), PackingList ("PackingList"), AssetMap("AssetMap"), TextPartition("TextPartition"), EssenceFooter4Bytes("EssenceFooter4Bytes"), EssencePartition("EssencePartition"), OutputProfileList("OutputProfileList"), Unknown("Unknown"); private final String assetType; PayloadAssetType(String assetType){ this.assetType = assetType; } /** * A toString() method * @return string representation of this enumeration constant */ public String toString(){ return this.assetType; } } }
5,034
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/RESTfulInterfaces/HeaderPartitionExtractor.java
package com.netflix.imflibrary.RESTfulInterfaces; import com.netflix.imflibrary.exceptions.IMFException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * A thin stateless class that assists in providing the byte offsets for the HeaderPartition within an IMF Track file */ public class HeaderPartitionExtractor { /** * To prevent instantiation */ private HeaderPartitionExtractor() { } /** * A stateless method that will return the size of the RandomIndexPack present within a MXF file. In a typical IMF workflow * this would be the first method that would need to be invoked to perform IMF essence component level validation * @param essenceFooter4Bytes - the last 4 bytes of the MXF file used to infer the size of the RandomIndexPack * @return a long integer value representing the size of the RandomIndexPack */ public static Long getRandomIndexPackSize(PayloadRecord essenceFooter4Bytes){ return IMPValidator.getRandomIndexPackSize(essenceFooter4Bytes); } /** * A stateless method that will read and parse the RandomIndexPack within a MXF file and return the byte offsets * corresponding to the Header partition of the MXF file. In a typical IMF workflow this would be the second method after * {@link #getRandomIndexPackSize(PayloadRecord)} that would need to be invoked to perform IMF essence component * level validation * @param randomIndexPackPayload - a payload containing the raw bytes corresponding to the RandomIndexPack of the MXF file * @param randomIndexPackSize - size of the RandomIndexPack of the MXF file * @return list of long integer values representing the byte offsets of the partitions in the MXF file * @throws IOException - any I/O related error is exposed through an IOException */ public static List<Long> getHeaderPartitionByteOffsets(PayloadRecord randomIndexPackPayload, Long randomIndexPackSize) throws IOException{ List<Long> partitionByteOffsets = IMPValidator.getEssencePartitionOffsets(randomIndexPackPayload, randomIndexPackSize); return partitionByteOffsets.subList(0, 2); } }
5,035
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/app/IMPFixer.java
package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st0429_8.PackingList; import com.netflix.imflibrary.st0429_9.AssetMap; import com.netflix.imflibrary.st0429_9.BasicMapProfileV2MappedFileSet; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import com.netflix.imflibrary.st2067_2.CoreConstraints; import com.netflix.imflibrary.st2067_2.IMFEssenceComponentVirtualTrack; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.writerTools.CompositionPlaylistBuilder_2016; import com.netflix.imflibrary.writerTools.IMPBuilder; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import javax.annotation.Nullable; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; /** * Created by svenkatrav on 9/2/16. */ public class IMPFixer { private static final String CONFORMANCE_LOGGER_PREFIX = "Virtual Track Conformance"; private static final Logger logger = LoggerFactory.getLogger(IMPFixer.class); private static UUID getTrackFileId(PayloadRecord headerPartitionPayloadRecord) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); UUID packageUUID = null; if (headerPartitionPayloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Payload asset type is %s, expected asset type %s", headerPartitionPayloadRecord.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); return packageUUID; } try { HeaderPartition headerPartition = new HeaderPartition(new ByteArrayDataProvider(headerPartitionPayloadRecord.getPayload()), 0L, (long) headerPartitionPayloadRecord.getPayload().length, imfErrorLogger); /** * Add the Top Level Package UUID to the set of TrackFileIDs, this is required to validate that the essences header partition that were passed in * are in fact from the constituent resources of the VirtualTack */ MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); Preface preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; packageUUID = filePackage.getPackageMaterialNumberasUUID(); } catch (IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } catch (MXFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } return packageUUID; } private static Map<UUID, PayloadRecord> getTrackFileIdToHeaderPartitionPayLoadMap(List<PayloadRecord> headerPartitionPayloadRecords) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Map<UUID, PayloadRecord> trackFileIDMap = new HashMap<>(); for (PayloadRecord payloadRecord : headerPartitionPayloadRecords) { if (payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Payload asset type is %s, expected asset type %s", payloadRecord.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); continue; } try { HeaderPartition headerPartition = new HeaderPartition(new ByteArrayDataProvider(payloadRecord.getPayload()), 0L, (long) payloadRecord.getPayload().length, imfErrorLogger); /** * Add the Top Level Package UUID to the set of TrackFileIDs, this is required to validate that the essences header partition that were passed in * are in fact from the constituent resources of the VirtualTack */ MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); Preface preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); trackFileIDMap.put(packageUUID, payloadRecord); } catch (IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } catch (MXFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } return Collections.unmodifiableMap(trackFileIDMap); } private static Boolean isCompositionComplete(ApplicationComposition applicationComposition, Set<UUID> trackFileIDsSet, IMFErrorLogger imfErrorLogger) throws IOException { boolean bComplete = true; for (IMFEssenceComponentVirtualTrack virtualTrack : applicationComposition.getEssenceVirtualTracks()) { for (UUID uuid : virtualTrack.getTrackResourceIds()) { if (!trackFileIDsSet.contains(uuid)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes .IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("CPL resource %s is not present in the package", uuid.toString())); bComplete &= false; } } } return bComplete; } @Nullable private static PayloadRecord getHeaderPartitionPayloadRecord(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException { long archiveFileSize = resourceByteRangeProvider.getResourceSize(); long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; if(rangeStart < 0 ) { return null; } byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssenceFooter4Bytes, rangeStart, rangeEnd); Long randomIndexPackSize = IMPValidator.getRandomIndexPackSize(payloadRecord); rangeStart = archiveFileSize - randomIndexPackSize; rangeEnd = archiveFileSize - 1; if(rangeStart < 0 ) { return null; } byte[] randomIndexPackBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord randomIndexPackPayload = new PayloadRecord(randomIndexPackBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); List<Long> partitionByteOffsets = IMPValidator.getEssencePartitionOffsets(randomIndexPackPayload, randomIndexPackSize); if (partitionByteOffsets.size() >= 2) { rangeStart = partitionByteOffsets.get(0); rangeEnd = partitionByteOffsets.get(1) - 1; byte[] headerPartitionBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord headerParitionPayload = new PayloadRecord(headerPartitionBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); return headerParitionPayload; } return null; } public static List<ErrorLogger.ErrorObject> analyzePackageAndWrite(File rootFile, File targetFile, String versionCPLSchema, Boolean copyTrackfile, Boolean generateHash) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException, NoSuchAlgorithmException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> headerPartitionPayloadRecords = new ArrayList<>(); BasicMapProfileV2MappedFileSet mapProfileV2MappedFileSet = new BasicMapProfileV2MappedFileSet(rootFile); AssetMap assetMap = new AssetMap(new File(mapProfileV2MappedFileSet.getAbsoluteAssetMapURI())); for (AssetMap.Asset packingListAsset : assetMap.getPackingListAssets()) { PackingList packingList = new PackingList(new File(rootFile, packingListAsset.getPath().toString())); Map<UUID, IMPBuilder.IMFTrackFileMetadata> imfTrackFileMetadataMap = new HashMap<>(); for (PackingList.Asset asset : packingList.getAssets()) { File assetFile = new File(rootFile, assetMap.getPath(asset.getUUID()).toString()); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetFile); if (asset.getType().equals(PackingList.Asset.APPLICATION_MXF_TYPE)) { PayloadRecord headerPartitionPayloadRecord = getHeaderPartitionPayloadRecord(resourceByteRangeProvider, new IMFErrorLoggerImpl()); headerPartitionPayloadRecords.add(headerPartitionPayloadRecord); byte[] bytes = headerPartitionPayloadRecord.getPayload(); byte[] hash = asset.getHash(); if( generateHash) { hash = IMFUtils.generateSHA1Hash(resourceByteRangeProvider); } imfTrackFileMetadataMap.put(getTrackFileId(headerPartitionPayloadRecord), new IMPBuilder.IMFTrackFileMetadata(bytes, hash, CompositionPlaylistBuilder_2016.defaultHashAlgorithm, assetFile.getName(), resourceByteRangeProvider.getResourceSize()) ); if(copyTrackfile) { File outputFile = new File(targetFile.toString() + File.separator + assetFile.getName()); Files.copy(assetFile.toPath(), outputFile.toPath(), REPLACE_EXISTING); } } } Map<UUID, PayloadRecord> trackFileIDToHeaderPartitionPayLoadMap = getTrackFileIdToHeaderPartitionPayLoadMap(headerPartitionPayloadRecords); for (PackingList.Asset asset : packingList.getAssets()) { File assetFile = new File(rootFile, assetMap.getPath(asset.getUUID()).toString()); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetFile); if (asset.getType().equals(PackingList.Asset.TEXT_XML_TYPE) && ApplicationComposition.isCompositionPlaylist(resourceByteRangeProvider)) { ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(resourceByteRangeProvider, new IMFErrorLoggerImpl()); if(applicationComposition == null){ continue; } Set<UUID> trackFileIDsSet = trackFileIDToHeaderPartitionPayLoadMap.keySet(); if(versionCPLSchema.equals("")) { String coreConstraintsSchema = applicationComposition.getCoreConstraintsSchema(); if (coreConstraintsSchema.equals(CoreConstraints.NAMESPACE_IMF_2013)) { versionCPLSchema = "2013"; } else if (coreConstraintsSchema.equals(CoreConstraints.NAMESPACE_IMF_2016) || coreConstraintsSchema.equals(CoreConstraints.NAMESPACE_IMF_2020)) { versionCPLSchema = "2016"; } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Input package CoreConstraints Schema %s not supported", applicationComposition.getCoreConstraintsSchema())); } } if(versionCPLSchema.equals("2016")) { imfErrorLogger.addAllErrors(IMPBuilder.buildIMP_2016("IMP", "Netflix", applicationComposition.getEssenceVirtualTracks(), applicationComposition.getEditRate(), "http://www.smpte-ra.org/schemas/2067-21/2016", imfTrackFileMetadataMap, targetFile)); } else if(versionCPLSchema.equals("2013")) { imfErrorLogger.addAllErrors(IMPBuilder.buildIMP_2013("IMP", "Netflix", applicationComposition.getEssenceVirtualTracks(), applicationComposition.getEditRate(), "http://www.smpte-ra.org/schemas/2067-21/2016", imfTrackFileMetadataMap, targetFile)); } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Invalid CPL schema %s for output", versionCPLSchema.equals("2013"))); } } } } return imfErrorLogger.getErrors(); } public static List<ErrorLogger.ErrorObject> validateEssencePartition(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { IMFErrorLogger trackFileErrorLogger = new IMFErrorLoggerImpl(); PayloadRecord headerPartitionPayload = getHeaderPartitionPayloadRecord(resourceByteRangeProvider, trackFileErrorLogger); if(headerPartitionPayload == null) { trackFileErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Failed to get header partition")); } else { List<PayloadRecord> payloadRecords = new ArrayList<>(); payloadRecords.add(headerPartitionPayload); trackFileErrorLogger.addAllErrors(IMPValidator.validateIMFTrackFileHeaderMetadata(payloadRecords)); } return trackFileErrorLogger.getErrors(); } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s input_package_directory output_package_directory [options]%n", IMPFixer.class.getName())); sb.append(String.format("options: %n")); sb.append(String.format("-cs, --cpl-schema VERSION CPL schema version for output IMP, supported values are 2013 or 2016%n")); sb.append(String.format("-nc, --no-copy don't copy track files %n")); sb.append(String.format("-nh, --no-hash No update for trackfile hash in PKL %n")); return sb.toString(); } public static void main(String args[]) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException, NoSuchAlgorithmException { if (args.length < 2) { logger.error(usage()); System.exit(-1); } String inputFileName = args[0]; File inputFile = new File(inputFileName); if (!inputFile.exists()) { logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } String outputFileName = args[1]; File outputFile = new File(outputFileName); if (!outputFile.exists() && !outputFile.mkdir()) { logger.error(String.format("Directory %s cannot be created", outputFile.getAbsolutePath())); System.exit(-1); } String versionCPLSchema = ""; Boolean copyTrackFile = true; Boolean generateHash = true; for(int argIdx = 2; argIdx < args.length; ++argIdx) { String curArg = args[argIdx]; String nextArg = argIdx < args.length - 1 ? args[argIdx + 1] : ""; if(curArg.equalsIgnoreCase("--cpl-schema") || curArg.equalsIgnoreCase("-cs")) { if(nextArg.length() == 0 || nextArg.charAt(0) == '-') { logger.error(usage()); System.exit(-1); } versionCPLSchema = nextArg; argIdx++; } else if(curArg.equalsIgnoreCase("--no-copy") || curArg.equalsIgnoreCase("-nc")) { copyTrackFile = false; } else if(curArg.equalsIgnoreCase("--no-hash") || curArg.equalsIgnoreCase("-nh")) { generateHash = false; } else { logger.error(usage()); System.exit(-1); } } if (!inputFile.exists() || !inputFile.isDirectory()) { logger.error(String.format("Invalid input package path")); System.exit(-1); } else { List<ErrorLogger.ErrorObject> errors = analyzePackageAndWrite(inputFile, outputFile, versionCPLSchema, copyTrackFile, generateHash); if (errors.size() > 0) { logger.info(String.format("IMPWriter encountered errors:")); for (ErrorLogger.ErrorObject errorObject : errors) { if (errorObject.getErrorLevel() != IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if (errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } System.exit(-1); } else { logger.info(String.format("Created %s IMP successfully", outputFile.getName())); } } } }
5,036
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/app/IMFTrackFileReader.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.IndexTableSegment; import com.netflix.imflibrary.st0377.PartitionPack; import com.netflix.imflibrary.st0377.RandomIndexPack; import com.netflix.imflibrary.st0377.StructuralMetadataID; import com.netflix.imflibrary.st0377.header.EssenceContainerData; import com.netflix.imflibrary.st0377.header.FileDescriptor; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.FileDataProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.Utilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; /** * A simple application to exercise the core logic of Photon for reading and validating IMF Track files. */ @ThreadSafe final class IMFTrackFileReader { private final File workingDirectory; private final ResourceByteRangeProvider resourceByteRangeProvider; private volatile RandomIndexPack randomIndexPack = null; private volatile List<PartitionPack> partitionPacks = null; private volatile List<PartitionPack> referencedPartitionPacks = null; private volatile IMFConstraints.HeaderPartitionIMF headerPartition; private volatile List<IndexTableSegment> indexTableSegments = null; private static final Logger logger = LoggerFactory.getLogger(IMFTrackFileReader.class); /** * Lazily creates a model instance corresponding to a st2067-5 compliant MXF file * @param workingDirectory the working directory * @param resourceByteRangeProvider the MXF file represented as a {@link com.netflix.imflibrary.utils.ResourceByteRangeProvider} */ IMFTrackFileReader(File workingDirectory, ResourceByteRangeProvider resourceByteRangeProvider) { this.workingDirectory = workingDirectory; this.resourceByteRangeProvider = resourceByteRangeProvider; } private IMFConstraints.HeaderPartitionIMF getHeaderPartitionIMF(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { if (this.headerPartition == null) { RandomIndexPack randomIndexPack = getRandomIndexPack(imfErrorLogger); List<Long> allPartitionByteOffsets = randomIndexPack.getAllPartitionByteOffsets(); try { setHeaderPartitionIMF(allPartitionByteOffsets.get(0), allPartitionByteOffsets.get(1) - 1, imfErrorLogger); } catch (IMFException e){ throw new IMFException(String.format("Could not set Header Partition"), imfErrorLogger); } } return this.headerPartition; } private HeaderPartition getHeaderPartition(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { try { IMFConstraints.HeaderPartitionIMF headerPartitionIMF = getHeaderPartitionIMF(imfErrorLogger); return headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition(); } catch (IMFException e){ throw new IMFException(String.format("Could not read Header Partition"), imfErrorLogger); } } private void setHeaderPartitionIMF(long inclusiveRangeStart, long inclusiveRangeEnd, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { File fileWithHeaderPartition = this.resourceByteRangeProvider.getByteRange(inclusiveRangeStart, inclusiveRangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithHeaderPartition); HeaderPartition headerPartition = null; try { headerPartition = new HeaderPartition(byteProvider, inclusiveRangeStart, inclusiveRangeEnd - inclusiveRangeStart + 1, imfErrorLogger); //validate header partition MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); this.headerPartition = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); } catch (MXFException | IMFException e){ if(headerPartition == null){ imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("IMFTrackFile has fatal errors"))); } else { Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("IMFTrackFile with ID %s has fatal errors", packageUUID.toString()))); } if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } throw new IMFException(String.format("Fatal errors in the IMFTrackFile's Header Partition"), imfErrorLogger); } } private List<IndexTableSegment> getIndexTableSegments(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { if (this.indexTableSegments == null) { setIndexTableSegments(imfErrorLogger); } return Collections.unmodifiableList(this.indexTableSegments); } private void setIndexTableSegments(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { RandomIndexPack randomIndexPack = getRandomIndexPack(imfErrorLogger); List<IndexTableSegment> indexTableSegments = new ArrayList<>(); List<Long> allPartitionByteOffsets = randomIndexPack.getAllPartitionByteOffsets(); int numPartitions = allPartitionByteOffsets.size(); for (int i=0; i<numPartitions -1; i++) { indexTableSegments.addAll(getIndexTableSegments(allPartitionByteOffsets.get(i), allPartitionByteOffsets.get(i+1) -1)); } indexTableSegments.addAll(getIndexTableSegments( allPartitionByteOffsets.get(numPartitions -1), this.resourceByteRangeProvider.getResourceSize() - 1)); this.indexTableSegments = Collections.unmodifiableList(indexTableSegments); } private List<IndexTableSegment> getIndexTableSegments(long inclusivePartitionStart, long inclusivePartitionEnd) throws IOException { long archiveFileSize = this.resourceByteRangeProvider.getResourceSize(); KLVPacket.Header header; {//logic to provide as an input stream the portion of the archive that contains PartitionPack KLVPacker Header long rangeEnd = inclusivePartitionStart + (KLVPacket.KEY_FIELD_SIZE + KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE) -1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); File fileWithPartitionPackKLVPacketHeader = this.resourceByteRangeProvider.getByteRange(inclusivePartitionStart, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithPartitionPackKLVPacketHeader); header = new KLVPacket.Header(byteProvider, inclusivePartitionStart); } PartitionPack partitionPack; {//logic to provide as an input stream the portion of the archive that contains a PartitionPack long rangeEnd = inclusivePartitionStart + (KLVPacket.KEY_FIELD_SIZE + header.getLSize() + header.getVSize()) -1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); File fileWithPartitionPack = this.resourceByteRangeProvider.getByteRange(inclusivePartitionStart, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithPartitionPack); partitionPack = new PartitionPack(byteProvider, inclusivePartitionStart, false); } List<IndexTableSegment> indexTableSegments = new ArrayList<>(); if (partitionPack.hasIndexTableSegments()) {//logic to provide as an input stream the portion of the archive that contains a Partition long byteOffset = inclusivePartitionStart; long rangeEnd = inclusivePartitionEnd; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); File fileWithPartition = this.resourceByteRangeProvider.getByteRange(inclusivePartitionStart, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithPartition); long numBytesToRead = rangeEnd - inclusivePartitionStart + 1; long numBytesRead = 0; while (numBytesRead < numBytesToRead) { header = new KLVPacket.Header(byteProvider, byteOffset); numBytesRead += header.getKLSize(); if (IndexTableSegment.isValidKey(header.getKey())) { indexTableSegments.add(new IndexTableSegment(byteProvider, header)); } else { byteProvider.skipBytes(header.getVSize()); } numBytesRead += header.getVSize(); byteOffset += numBytesRead; } } return indexTableSegments; } private List<PartitionPack> getReferencedPartitionPacks(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { if (this.referencedPartitionPacks == null) { setReferencedPartitionPacks(imfErrorLogger); } return this.referencedPartitionPacks; } private void setReferencedPartitionPacks(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { List<PartitionPack> allPartitionPacks = getPartitionPacks(imfErrorLogger); HeaderPartition headerPartition = getHeaderPartition(imfErrorLogger); Set<Long> indexSIDs = new HashSet<>(); Set<Long> bodySIDs = new HashSet<>(); for (EssenceContainerData essenceContainerData : headerPartition.getPreface().getContentStorage().getEssenceContainerDataList()) { indexSIDs.add(essenceContainerData.getIndexSID()); bodySIDs.add(essenceContainerData.getBodySID()); } List<PartitionPack> referencedPartitionPacks = new ArrayList<>(); for (PartitionPack partitionPack : allPartitionPacks) { if (partitionPack.hasEssenceContainer()) { if (bodySIDs.contains(partitionPack.getBodySID())) { referencedPartitionPacks.add(partitionPack); } } else if (partitionPack.hasIndexTableSegments()) { if (indexSIDs.contains(partitionPack.getIndexSID())) { referencedPartitionPacks.add(partitionPack); } } else if(partitionPack.getPartitionPackType() == PartitionPack.PartitionPackType.HeaderPartitionPack || partitionPack.getPartitionPackType() == PartitionPack.PartitionPackType.FooterPartitionPack) {//Either of these partitions are important although they might not contain EssenceContainer or IndexTable data referencedPartitionPacks.add(partitionPack); } } this.referencedPartitionPacks = referencedPartitionPacks; } private List<PartitionPack> getPartitionPacks(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { if (this.partitionPacks == null) { setPartitionPacks(imfErrorLogger); } return Collections.unmodifiableList(this.partitionPacks); } List<String> getPartitionPacksType(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { if (this.partitionPacks == null) { setPartitionPacks(imfErrorLogger); } ArrayList<String> partitionPackTypeString = new ArrayList<String>(); for(PartitionPack partitionPack : this.partitionPacks){ partitionPackTypeString.add(partitionPack.getPartitionPackType().getPartitionTypeString()); } return Collections.unmodifiableList(partitionPackTypeString); } private void setPartitionPacks(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { RandomIndexPack randomIndexPack = getRandomIndexPack(imfErrorLogger); List<PartitionPack> partitionPacks = new ArrayList<>(); List<Long> allPartitionByteOffsets = randomIndexPack.getAllPartitionByteOffsets(); for (long offset : allPartitionByteOffsets) { partitionPacks.add(getPartitionPack(offset)); } try { //validate partition packs MXFOperationalPattern1A.checkOperationalPattern1ACompliance(partitionPacks); IMFConstraints.checkIMFCompliance(partitionPacks, imfErrorLogger); } catch (IMFException | MXFException e){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("This IMFTrackFile has fatal errors in the partition packs, please see the errors that follow.")); if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } } //add reference to list of partition packs this.partitionPacks = Collections.unmodifiableList(partitionPacks); } private PartitionPack getPartitionPack(long resourceOffset) throws IOException { long archiveFileSize = this.resourceByteRangeProvider.getResourceSize(); KLVPacket.Header header; {//logic to provide as an input stream the portion of the archive that contains PartitionPack KLVPacker Header long rangeEnd = resourceOffset + (KLVPacket.KEY_FIELD_SIZE + KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE) -1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); File fileWithPartitionPackKLVPacketHeader = this.resourceByteRangeProvider.getByteRange(resourceOffset, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithPartitionPackKLVPacketHeader); header = new KLVPacket.Header(byteProvider, resourceOffset); } PartitionPack partitionPack; {//logic to provide as an input stream the portion of the archive that contains a PartitionPack and next KLV header long rangeEnd = resourceOffset + (KLVPacket.KEY_FIELD_SIZE + header.getLSize() + header.getVSize()) + (KLVPacket.KEY_FIELD_SIZE + KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE) + -1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); File fileWithPartitionPack = this.resourceByteRangeProvider.getByteRange(resourceOffset, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithPartitionPack); partitionPack = new PartitionPack(byteProvider, resourceOffset, true); } return partitionPack; } /** * Returns a model instance corresponding to the RandomIndexPack section of the MXF file * @return a {@link com.netflix.imflibrary.st0377.RandomIndexPack} representation of the random index pack section * @throws IOException - any I/O related error is exposed through an IOException */ RandomIndexPack getRandomIndexPack(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { if (this.randomIndexPack == null) { setRandomIndexPack(imfErrorLogger); } return this.randomIndexPack; } private void setRandomIndexPack(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { long archiveFileSize = this.resourceByteRangeProvider.getResourceSize(); long randomIndexPackSize; {//logic to provide as an input stream the portion of the archive that contains randomIndexPack size long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; File fileWithRandomIndexPackSize = this.resourceByteRangeProvider.getByteRange(rangeStart, rangeEnd, this.workingDirectory); byte[] bytes = Files.readAllBytes(Paths.get(fileWithRandomIndexPackSize.toURI())); randomIndexPackSize = (long)(ByteBuffer.wrap(bytes).getInt()); } //RandomIndexPack size min value = 16 + 4 + 36 + 4 // 16 bytes for the UL, 4 bytes for the overall length of the pack, 3 * 12 bytes since we expect to see atleast 3 partitions, 4 bytes overall length of the pack including the SetKey, Pack Length and SID/Offset fields if(randomIndexPackSize < 60){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("RandomIndexPackSize = %d is smaller than what is required to reliably contain a minimum number of Partition Byte Offsets.", randomIndexPackSize)); throw new MXFException(String.format("RandomIndexPackSize = %d is smaller than what is required to reliably contain a minimum number of Partition Byte Offsets.", randomIndexPackSize), imfErrorLogger); } RandomIndexPack randomIndexPack; {//logic to provide as an input stream the portion of the archive that contains randomIndexPack long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - randomIndexPackSize; if (rangeStart < 0) { throw new MXFException(String.format("RandomIndexPackSize = %d obtained from last 4 bytes of the MXF file is larger than archiveFile size = %d, implying that this file does not contain a RandomIndexPack", randomIndexPackSize, archiveFileSize)); } File fileWithRandomIndexPack = this.resourceByteRangeProvider.getByteRange(rangeStart, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithRandomIndexPack); randomIndexPack = new RandomIndexPack(byteProvider, rangeStart, randomIndexPackSize); } this.randomIndexPack = randomIndexPack; } /** * A method that returns a list of EssenceDescriptor objects referenced by the Source Packages in this HeaderPartition * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return List<InterchangeObjectBO></> corresponding to every EssenceDescriptor in the underlying resource * @throws IOException - any I/O related error will be exposed through an IOException */ List<InterchangeObject.InterchangeObjectBO> getEssenceDescriptors(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { return this.getHeaderPartition(imfErrorLogger).getEssenceDescriptors(); } /** * A method that returns an MXF KLV Header corresponding to an EssenceDescriptor * @param essenceDescriptor corresponding to the essence in the MXF file * @return List<MXFKLVPacket.Header></> corresponding to every EssenceDescriptor in the underlying resource */ KLVPacket.Header getEssenceDescriptorKLVHeader(InterchangeObject.InterchangeObjectBO essenceDescriptor) throws IOException { return essenceDescriptor.getHeader(); } /** * A method that returns a list of MXF KLV Header corresponding to the SubDescriptors in the MXF file * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return List<MXFKLVPacket.Header></> corresponding to every SubDescriptor in the underlying resource * @throws IOException - any I/O related error will be exposed through an IOException */ List<KLVPacket.Header> getSubDescriptors(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { List<InterchangeObject.InterchangeObjectBO> subDescriptors = this.getHeaderPartition(imfErrorLogger).getSubDescriptors(); List<KLVPacket.Header> subDescriptorHeaders = new ArrayList<>(); for(InterchangeObject.InterchangeObjectBO subDescriptorBO : subDescriptors){ if(subDescriptorBO != null) { subDescriptorHeaders.add(subDescriptorBO.getHeader()); } } return subDescriptorHeaders; } /** * A method that returns the MXF KLV header corresponding to an EssenceDescriptor in the MXF file * @param essenceDescriptor corresponding to the essence in the MXF file * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return List<MXFKLVPacket.Header></> corresponding to every SubDescriptor in the underlying resource * @throws IOException - any I/O related error will be exposed through an IOException */ List<KLVPacket.Header> getSubDescriptorKLVHeader(InterchangeObject.InterchangeObjectBO essenceDescriptor, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { List<KLVPacket.Header> subDescriptorHeaders = new ArrayList<>(); List<InterchangeObject.InterchangeObjectBO>subDescriptors = this.getHeaderPartition(imfErrorLogger).getSubDescriptors(essenceDescriptor); for(InterchangeObject.InterchangeObjectBO subDescriptorBO : subDescriptors){ if(subDescriptorBO != null) { subDescriptorHeaders.add(subDescriptorBO.getHeader()); } } return subDescriptorHeaders; } /** * A method to get the EssenceType * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return a String representing the Essence type * @throws IOException - any I/O related error is exposed through an IOException */ HeaderPartition.EssenceTypeEnum getEssenceType(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { Set<HeaderPartition.EssenceTypeEnum> supportedEssenceComponentTypes = new HashSet<>(); supportedEssenceComponentTypes.add(HeaderPartition.EssenceTypeEnum.MainImageEssence); supportedEssenceComponentTypes.add(HeaderPartition.EssenceTypeEnum.MainAudioEssence); supportedEssenceComponentTypes.add(HeaderPartition.EssenceTypeEnum.MarkerEssence); supportedEssenceComponentTypes.add(HeaderPartition.EssenceTypeEnum.IABEssence); List<HeaderPartition.EssenceTypeEnum> supportedEssenceTypesFound = new ArrayList<>(); List<HeaderPartition.EssenceTypeEnum> essenceTypes = this.getHeaderPartitionIMF(imfErrorLogger).getHeaderPartitionOP1A().getHeaderPartition().getEssenceTypes(); for(HeaderPartition.EssenceTypeEnum essenceTypeEnum : essenceTypes){ if(supportedEssenceComponentTypes.contains(essenceTypeEnum)){ supportedEssenceTypesFound.add(essenceTypeEnum); } } if(supportedEssenceTypesFound.size() > 0) { if (supportedEssenceTypesFound.size() > 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("IMFTrack file seems to have multiple supported essence component types %s only 1 is allowed per IMF Core Constraints, returning the first supported EssenceType", Utilities.serializeObjectCollectionToString(supportedEssenceTypesFound))); } return supportedEssenceTypesFound.get(0); } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("IMFTrack file does not seem to have a supported essence component type, essence types supported %n%s, essence types found %n%s" , Utilities.serializeObjectCollectionToString(supportedEssenceComponentTypes), Utilities.serializeObjectCollectionToString(essenceTypes))); return HeaderPartition.EssenceTypeEnum.UnsupportedEssence; } } /** * An accessor for the PrimerPack KLV header * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return a File containing the Primer pack * @throws IOException - any I/O related error is exposed through an IOException */ KLVPacket.Header getPrimerPackHeader(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { return this.getHeaderPartition(imfErrorLogger).getPrimerPack().getHeader(); } /** * A helper method to retrieve a ByteProvider for the KLV packet * * @param header representing the object model of a KLV packet * @return a ByteProvider corresponding to the header * @throws IOException */ ByteProvider getByteProvider(KLVPacket.Header header) throws IOException { File file = this.resourceByteRangeProvider.getByteRange(header.getByteOffset(), header.getByteOffset() + header.getKLSize() + header.getVSize(), this.workingDirectory); return this.getByteProvider(file); } private ByteProvider getByteProvider(File file) throws IOException { ByteProvider byteProvider; Long size = file.length(); if(size <= 0){ throw new IOException(String.format("Range of bytes (%d) has to be +ve and non-zero", size)); } if(size <= Integer.MAX_VALUE) { byte[] bytes = Files.readAllBytes(Paths.get(file.toURI())); byteProvider = new ByteArrayDataProvider(bytes); } else{ byteProvider = new FileDataProvider(file); } return byteProvider; } /** * An accessor that returns a list of InterchangeObjectBO by name * * @param structuralMetadataID of the InterchangeObject requested. * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return a list of interchangeObjectBOs corresponding to the ID. Null if there is no InterchangeObjectBO with the ID * with the name passed in. */ @Nullable List<InterchangeObject.InterchangeObjectBO> getStructuralMetadataByName(StructuralMetadataID structuralMetadataID, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { return this.getHeaderPartition(imfErrorLogger).getStructuralMetadata(structuralMetadataID); } /** * Returns the EditRate as a BigInteger * * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return a BigInteger representing the EditRate of the essence */ BigInteger getEssenceEditRate(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { BigInteger result = BigInteger.valueOf(0); if(!(this.getHeaderPartition(imfErrorLogger).getEssenceDescriptors().size() > 0)){ imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("No EssenceDescriptors were found in " + "the MXF essence Header Partition"))); } InterchangeObject.InterchangeObjectBO essenceDescriptor = this.getHeaderPartition(imfErrorLogger).getEssenceDescriptors().get(0); if(FileDescriptor.FileDescriptorBO.class.isAssignableFrom(essenceDescriptor.getClass())){ FileDescriptor.FileDescriptorBO fileDescriptorBO = (FileDescriptor.FileDescriptorBO) essenceDescriptor; List<Long>list = fileDescriptorBO.getSampleRate(); Long value = list.get(0)/list.get(1); result = BigInteger.valueOf(value); } return result; } /** * Returns the EditRate as a list containing the numerator and denominator * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return editRate of the essence as a List of Long Integers */ List<Long> getEssenceEditRateAsList(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { if(!(this.getHeaderPartition(imfErrorLogger).getEssenceDescriptors().size() > 0)){ throw new MXFException(String.format("No EssenceDescriptors were found in the MXF essence")); } FileDescriptor.FileDescriptorBO fileDescriptorBO = (FileDescriptor.FileDescriptorBO) this.getHeaderPartition(imfErrorLogger).getEssenceDescriptors().get(0); return fileDescriptorBO.getSampleRate(); } /** * Return the duration of the Essence including the source duration of all the Structural Components in the MXF Sequence * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return essenceDuration */ BigInteger getEssenceDuration(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { return this.getHeaderPartition(imfErrorLogger).getEssenceDuration(); } /** * A method to return the TrackFileId which is a UUID identifying the track file * @return UUID identifying the Track File */ UUID getTrackFileId(){ Preface preface = this.headerPartition.getHeaderPartitionOP1A().getHeaderPartition().getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage)genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); return packageUUID; } /** * A getter for the AudioEssence Language * @param imfErrorLogger an error logger for recording any errors - cannot be null * @return a string representing the language code in the Audio Essence * @throws IOException - any I/O related error is exposed through an IOException */ String getAudioEssenceLanguage(@Nonnull IMFErrorLogger imfErrorLogger) throws IOException { return this.getHeaderPartition(imfErrorLogger).getAudioEssenceSpokenLanguage(); } public String toString() { StringBuilder sb = new StringBuilder(); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); try { sb.append(this.getRandomIndexPack(imfErrorLogger)); sb.append(this.getPartitionPacks(imfErrorLogger)); sb.append(this.getReferencedPartitionPacks(imfErrorLogger)); sb.append(this.getIndexTableSegments(imfErrorLogger)); sb.append(this.getHeaderPartitionIMF(imfErrorLogger)); } catch(IOException e) { throw new IMFException(e.getMessage(), imfErrorLogger); } catch (IMFException | MXFException e){ if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } logger.error(Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors())); } return sb.toString(); } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <inputFilePath> <workingDirectory>%n", IMFTrackFileReader.class.getName())); return sb.toString(); } public static void main(String[] args) throws IOException { if (args.length != 2) { logger.error(usage()); throw new IllegalArgumentException("Invalid parameters"); } File inputFile = new File(args[0]); if(!inputFile.exists()){ logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } File workingDirectory = new File(args[1]); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); IMFTrackFileReader imfTrackFileReader = null; IMFTrackFileCPLBuilder imfTrackFileCPLBuilder = null; IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); try { imfTrackFileReader = new IMFTrackFileReader(workingDirectory, resourceByteRangeProvider); imfTrackFileCPLBuilder = new IMFTrackFileCPLBuilder(workingDirectory, inputFile); } catch (IMFException | MXFException e){ if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } imfErrorLogger.addAllErrors(imfErrorLogger.getErrors()); } Set<HeaderPartition.EssenceTypeEnum> supportedEssenceComponentTypes = new HashSet<>(); supportedEssenceComponentTypes.add(HeaderPartition.EssenceTypeEnum.MainImageEssence); supportedEssenceComponentTypes.add(HeaderPartition.EssenceTypeEnum.MainAudioEssence); supportedEssenceComponentTypes.add(HeaderPartition.EssenceTypeEnum.MarkerEssence); if(imfTrackFileReader != null && imfTrackFileCPLBuilder != null && supportedEssenceComponentTypes.contains(imfTrackFileReader.getEssenceType(imfErrorLogger))) { try { for (InterchangeObject.InterchangeObjectBO essenceDescriptor : imfTrackFileReader.getEssenceDescriptors(imfErrorLogger)) { /* create dom */ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); /*Output file containing the RegXML representation of the EssenceDescriptor*/ KLVPacket.Header essenceDescriptorHeader = essenceDescriptor.getHeader(); List<KLVPacket.Header> subDescriptorHeaders = imfTrackFileReader.getSubDescriptorKLVHeader(essenceDescriptor, imfErrorLogger); File outputFile = imfTrackFileCPLBuilder.getEssenceDescriptorAsXMLFile(document, essenceDescriptorHeader, subDescriptorHeaders, imfErrorLogger); logger.info(String.format("The EssenceDescriptor in the IMFTrackFile has been written to a XML document at the following location %s", outputFile.getAbsolutePath())); } } catch (ParserConfigurationException | TransformerException e) { throw new MXFException(e); } } List<ErrorLogger.ErrorObject> errors = imfErrorLogger.getErrors(); if(errors.size() > 0){ long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("IMFTrackFile has %d errors and %d warnings", errors.size() - warningCount, warningCount)); for(ErrorLogger.ErrorObject errorObject : errors){ if(errorObject.getErrorLevel() != IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if(errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } } else{ /*if(imfTrackFileReader != null && imfTrackFileCPLBuilder != null) { logger.info(String.format("%n %s", imfTrackFileReader.toString())); }*/ logger.info("No errors were detected in the IMFTrackFile"); } } }
5,037
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/app/IMFTrackFileCPLBuilder.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.RegXMLLibHelper; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.writerTools.CompositionPlaylistBuilder_2013; import com.netflix.imflibrary.writerTools.IMFCPLObjectFieldsFactory; import com.netflix.imflibrary.writerTools.utils.IMFUUIDGenerator; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import com.sandflow.smpte.klv.Triplet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smpte_ra.schemas._2067_2._2013.ObjectFactory; import org.smpte_ra.schemas._2067_3._2013.BaseResourceType; import org.smpte_ra.schemas._2067_3._2013.CompositionTimecodeType; import org.smpte_ra.schemas._2067_3._2013.ContentKindType; import org.smpte_ra.schemas._2067_3._2013.ContentMaturityRatingType; import org.smpte_ra.schemas._2067_3._2013.ContentVersionType; import org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType; import org.smpte_ra.schemas._2067_3._2013.LocaleType; import org.smpte_ra.schemas._2067_3._2013.SegmentType; import org.smpte_ra.schemas._2067_3._2013.SequenceType; import org.smpte_ra.schemas._2067_3._2013.TrackFileResourceType; import org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; import javax.annotation.concurrent.Immutable; import javax.xml.bind.JAXBElement; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * A class that builds an IMF Composition representation of an IMF Essence */ @Immutable public final class IMFTrackFileCPLBuilder { private static final Logger logger = LoggerFactory.getLogger(IMFTrackFileReader.class); private final IMFTrackFileReader imfTrackFileReader; private final RegXMLLibHelper regXMLLibHelper; private final File workingDirectory; private final org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType cplRoot; private final File mxfFile; private final String fileName; /** * A constructor for the IMFTrackFileCPLBuilder class. This class creates an IMF CPL representation of an IMF Essence * @param workingDirectory - A location on a file system used for processing the essence. * This would also be the location where the CPL representation of the IMFEssence would be written into. * @param essenceFile - File representing an IMF Essence * @throws IOException - any I/O related error will be exposed through an IOException */ public IMFTrackFileCPLBuilder(File workingDirectory, File essenceFile) throws IOException { ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(essenceFile); this.imfTrackFileReader = new IMFTrackFileReader(workingDirectory, resourceByteRangeProvider); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); KLVPacket.Header primerPackHeader = this.imfTrackFileReader.getPrimerPackHeader(imfErrorLogger); this.regXMLLibHelper = new RegXMLLibHelper(primerPackHeader, this.imfTrackFileReader.getByteProvider(primerPackHeader)); this.workingDirectory = workingDirectory; /*Peek into the CompositionPlayListType and recursively construct its constituent fields*/ this.cplRoot = IMFCPLObjectFieldsFactory.constructCompositionPlaylistType_2013(); this.mxfFile = essenceFile; this.fileName = this.mxfFile.getName(); } /** * A template method to get an IMF CPL representation of the IMF Essence that the IMFTrackFileCPLBuilder was * initialized with. * @param imfErrorLogger an error logger for recording any errors - cannot be null * @throws IOException - any I/O related error will be exposed through an IOException */ public File getCompositionPlaylist(IMFErrorLogger imfErrorLogger) throws IOException { this.cplRoot.setId(IMFUUIDGenerator.getInstance().getUrnUUID()); /*CPL Annotation*/ this.cplRoot.getAnnotation().setValue(this.fileName); this.cplRoot.getAnnotation().setLanguage("en");/*Setting language to English which is also the default*/ /*IssueDate*/ this.cplRoot.setIssueDate(IMFUtils.createXMLGregorianCalendar()); /*Issuer*/ this.cplRoot.setIssuer(null); /*Creator*/ this.cplRoot.setCreator(null); /*Content Originator*/ this.cplRoot.setContentOriginator(null); /*Content Title*/ String name = this.fileName.substring(0, this.fileName.lastIndexOf(".")); this.cplRoot.getContentTitle().setValue(name); this.cplRoot.getContentTitle().setLanguage("en"); /*Content Kind*/ String essenceType = this.imfTrackFileReader.getEssenceType(imfErrorLogger).toString(); this.cplRoot.getContentKind().setValue(essenceType); this.cplRoot.getContentKind().setScope("General"); /*Extension Properties*/ buildExtensionProperties(); /*Total Running Time*/ this.cplRoot.setTotalRunningTime(null); /*Build ContentVersionList*/ buildContentVersionList(); /*EssenceDescriptorList*/ List<String> essenceDescriptorIdsList = Collections.synchronizedList(new LinkedList<String>()); buildEssenceDescriptorList(essenceDescriptorIdsList, imfErrorLogger); /*CompositionTimeCode*/ buildCompositionTimeCode(); /*Edit Rate*/ List<Long> list = this.imfTrackFileReader.getEssenceEditRateAsList(imfErrorLogger); this.cplRoot.getEditRate().addAll(list); /*Locale List*/ this.buildLocaleList(); /*Segment List*/ this.buildSegmentList(essenceDescriptorIdsList, imfErrorLogger); /*Signature elements*/ this.buildSignatureElements(); /*This will serialize the CPL and generate its XML representation*/ return this.serializeCPL(); } private File serializeCPL() throws IOException { File outputFile = new File(this.workingDirectory + "/" + this.mxfFile.getName() + ".xml"); IMFUtils.writeCPLToFile(this.cplRoot, outputFile); return outputFile; } private ContentKindType buildContentKindType(String value, String scope){ ContentKindType contentKindType = this.cplRoot.getContentKind(); contentKindType.setValue(value); contentKindType.setScope(scope); return contentKindType; } private void buildContentVersionList(){ /*Content Version List*/ List<ContentVersionType> contentVersionTypeList = this.cplRoot.getContentVersionList().getContentVersion(); ContentVersionType contentVersionType = new ContentVersionType(); /*Content Version Type*/ String uuidString = IMFUUIDGenerator.getInstance().getUrnUUID(); contentVersionType.setId(uuidString); UserTextType userTextType = new UserTextType(); userTextType.setValue(uuidString); userTextType.setLanguage("en"); contentVersionType.setLabelText(userTextType); /*Add the just created ContentVersionType to the list*/ contentVersionTypeList.add(contentVersionType); } private void buildExtensionProperties(){ this.cplRoot.setExtensionProperties(null); } private void buildEssenceDescriptorList(List<String> uuidList, IMFErrorLogger imfErrorLogger) throws IOException{ try { List<EssenceDescriptorBaseType> essenceDescriptorList = this.cplRoot.getEssenceDescriptorList().getEssenceDescriptor(); List<InterchangeObject.InterchangeObjectBO> essenceDescriptors = this.imfTrackFileReader.getEssenceDescriptors(imfErrorLogger); for(InterchangeObject.InterchangeObjectBO essenceDescriptor : essenceDescriptors) { KLVPacket.Header essenceDescriptorHeader = essenceDescriptor.getHeader(); List<KLVPacket.Header> subDescriptorHeaders = this.imfTrackFileReader.getSubDescriptorKLVHeader(essenceDescriptor, imfErrorLogger); /*Create a dom*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); EssenceDescriptorBaseType essenceDescriptorBaseType = new EssenceDescriptorBaseType(); String uuid = IMFUUIDGenerator.getInstance().getUrnUUID(); essenceDescriptorBaseType.setId(uuid); uuidList.add(uuid); DocumentFragment documentFragment = this.getEssenceDescriptorAsDocumentFragment(document, essenceDescriptorHeader, subDescriptorHeaders, imfErrorLogger); Node node = documentFragment.getFirstChild(); essenceDescriptorBaseType.getAny().add(node); essenceDescriptorList.add(essenceDescriptorBaseType); } } catch(ParserConfigurationException e){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, e.getMessage()); throw new IMFException(e); } } private void buildCompositionTimeCode(){ this.cplRoot.setCompositionTimecode(null); } private void buildSampleCompositionTimeCode(IMFErrorLogger imfErrorLogger) throws IOException { /* Following serves as SampleCode to getCompositionPlaylist a CompositionTimecode object*/ CompositionTimecodeType compositionTimecodeType = this.cplRoot.getCompositionTimecode(); compositionTimecodeType.setTimecodeDropFrame(false);/*TimecodeDropFrame set to false by default*/ compositionTimecodeType.setTimecodeRate(this.imfTrackFileReader.getEssenceEditRate(imfErrorLogger)); compositionTimecodeType.setTimecodeStartAddress(IMFUtils.generateTimecodeStartAddress()); } private void buildLocaleList(){ this.cplRoot.setLocaleList(null); } private void buildSampleLocaleList(){ /*Following serves as SampleCode to getCompositionPlaylist a SampleLocaleList*/ List<LocaleType> list = this.cplRoot.getLocaleList().getLocale(); LocaleType localeType = new LocaleType(); /*Locale Annotation*/ localeType.setAnnotation(CompositionPlaylistBuilder_2013.buildCPLUserTextType_2013("Netflix-CustomLocale", "en")); /*Locale Language List*/ LocaleType.LanguageList languageList = new LocaleType.LanguageList(); languageList.getLanguage().add("en"); localeType.setLanguageList(languageList); /*Locale Region List*/ LocaleType.RegionList regionList = new LocaleType.RegionList(); regionList.getRegion().add("US"); localeType.setRegionList(regionList); /*Locale Maturity Rating*/ LocaleType.ContentMaturityRatingList contentMaturityRatingList = new LocaleType.ContentMaturityRatingList(); List<ContentMaturityRatingType> contentMaturityRatingTypes = contentMaturityRatingList.getContentMaturityRating(); ContentMaturityRatingType contentMaturityRatingType = new ContentMaturityRatingType(); contentMaturityRatingType.setAgency("None"); ContentMaturityRatingType.Audience audience = new ContentMaturityRatingType.Audience(); audience.setValue("None"); audience.setScope("General"); contentMaturityRatingType.setAudience(audience); contentMaturityRatingType.setRating("None"); contentMaturityRatingTypes.add(contentMaturityRatingType); localeType.setContentMaturityRatingList(contentMaturityRatingList); list.add(localeType); } private void buildSegmentList(List<String> uuidList, IMFErrorLogger imfErrorLogger) throws IOException { /*Segment Id*/ List<SegmentType>segments = this.cplRoot.getSegmentList().getSegment(); SegmentType segmentType = new SegmentType(); segmentType.setId(IMFUUIDGenerator.getInstance().getUrnUUID()); /*Segment Annotation*/ String name = this.fileName.substring(0, this.fileName.lastIndexOf(".")); String language = this.imfTrackFileReader.getAudioEssenceLanguage(imfErrorLogger) != null ? this.imfTrackFileReader.getAudioEssenceLanguage(imfErrorLogger) : "unknown"; segmentType.setAnnotation(CompositionPlaylistBuilder_2013.buildCPLUserTextType_2013(name, language)); /*Sequence List*/ SegmentType.SequenceList sequenceList = new SegmentType.SequenceList(); int index = 0; SequenceType sequenceType = this.buildSequenceType(uuidList, index, imfErrorLogger); ObjectFactory objectFactory = new ObjectFactory(); JAXBElement<SequenceType> element = null; if(this.imfTrackFileReader.getEssenceType(imfErrorLogger).equals(HeaderPartition.EssenceTypeEnum.MainImageEssence)){ element = objectFactory.createMainImageSequence(sequenceType); } else if(this.imfTrackFileReader.getEssenceType(imfErrorLogger).equals(HeaderPartition.EssenceTypeEnum.MainAudioEssence)){ element = objectFactory.createMainAudioSequence(sequenceType); } else{ String message = String.format("Currently only Audio/Image sequence types are supported"); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } sequenceList.getAny().add(element); segmentType.setSequenceList(sequenceList); /*Add the segment that was built to the list of segments*/ segments.add(segmentType); } private SequenceType buildSequenceType(List<String> uuidList, int index, IMFErrorLogger imfErrorLogger) throws IOException { SequenceType sequenceType = new SequenceType(); /*Id*/ sequenceType.setId(IMFUUIDGenerator.getInstance().getUrnUUID()); /*Track Id*/ String trackId = IMFUUIDGenerator.getInstance().getUrnUUID(); sequenceType.setTrackId(trackId); /*ResourceList*/ sequenceType.setResourceList(buildTrackResourceList(uuidList, index, imfErrorLogger)); return sequenceType; } private SequenceType.ResourceList buildTrackResourceList(List<String> uuidList, int index, IMFErrorLogger imfErrorLogger) throws IOException { SequenceType.ResourceList resourceList = new SequenceType.ResourceList(); List<BaseResourceType> baseResourceTypes = resourceList.getResource(); TrackFileResourceType trackFileResourceType = new TrackFileResourceType(); trackFileResourceType.setId(IMFUUIDGenerator.getInstance().getUrnUUID()); /*Resource Annotation*/ String name = this.fileName.substring(0, this.fileName.lastIndexOf(".")); String language = this.imfTrackFileReader.getAudioEssenceLanguage(imfErrorLogger) != null ? this.imfTrackFileReader.getAudioEssenceLanguage(imfErrorLogger) : "unknown"; trackFileResourceType.setAnnotation(CompositionPlaylistBuilder_2013.buildCPLUserTextType_2013(name, language)); /*Edit Rate*/ trackFileResourceType.getEditRate().addAll(this.imfTrackFileReader.getEssenceEditRateAsList(imfErrorLogger)); /*Intrinsic Duration*/ trackFileResourceType.setIntrinsicDuration(this.imfTrackFileReader.getEssenceDuration(imfErrorLogger)); /*Entry Point*/ trackFileResourceType.setEntryPoint(BigInteger.valueOf(0L)); /*Source Duration*/ trackFileResourceType.setSourceDuration(trackFileResourceType.getIntrinsicDuration());/*Source Duration is set to the same value as the intrinsic duration*/ /*Repeat Count*/ trackFileResourceType.setRepeatCount(BigInteger.valueOf(1)); /*Source Encoding*/ trackFileResourceType.setSourceEncoding(uuidList.get(index));/*For the moment we assume that an EssenceDescriptor reference changes only at the Sequence Level*/ /*Track File Id*/ trackFileResourceType.setTrackFileId("urn" + ":" + "uuid" + ":" + this.imfTrackFileReader.getTrackFileId().toString()); /*Key Id*/ trackFileResourceType.setKeyId(IMFUUIDGenerator.getInstance().getUrnUUID()); /*Hash*/ trackFileResourceType.setHash(IMFUtils.generateSHA1Hash(this.mxfFile)); /*Add the constructed TrackFileResourceType to the ResourceTypes list*/ BaseResourceType baseResourceType = (BaseResourceType)trackFileResourceType; baseResourceTypes.add(baseResourceType); return resourceList; } private void buildSignatureElements(){ /** * For now set the signature related elements to null - TO DO populate accordingly */ this.cplRoot.setSigner(null); this.cplRoot.setSignature(null); } /** * A method that returns a XML file representing a MXF EssenceDescriptor present in the IMF Essence. * * @return An XML DOM Document fragment representing the EssenceDescriptors contained in the MXF file * @throws IOException - any I/O related error will be exposed through an IOException, * @throws MXFException - any MXF standard related non-compliance will be exposed through a MXF exception * @throws TransformerException - any XML transformation critical error will be exposed through a TransformerException */ File getEssenceDescriptorAsXMLFile(Document document, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header>subDescriptors, IMFErrorLogger imfErrorLogger) throws MXFException, IOException, TransformerException { File outputFile = new File(this.workingDirectory + "/" + "EssenceDescriptor.xml"); document.setXmlStandalone(true); DocumentFragment documentFragment = getEssenceDescriptorAsDocumentFragment(document, essenceDescriptor, subDescriptors, imfErrorLogger); document.appendChild(documentFragment); /* write DOM to file */ Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); /*tr.transform( new DOMSource(document), new StreamResult(System.out) );*/ tr.transform( new DOMSource(document), new StreamResult(outputFile) ); return outputFile; } private DocumentFragment getEssenceDescriptorAsDocumentFragment(Document document, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header>subDescriptors, IMFErrorLogger imfErrorLogger) throws MXFException, IOException { document.setXmlStandalone(true); Triplet essenceDescriptorTriplet = this.regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor, this.imfTrackFileReader.getByteProvider(essenceDescriptor)); //DocumentFragment documentFragment = this.regXMLLibHelper.getDocumentFragment(essenceDescriptorTriplet, document); /*Get the Triplets corresponding to the SubDescriptors*/ List<Triplet> subDescriptorTriplets = new ArrayList<>(); for(KLVPacket.Header subDescriptorHeader : subDescriptors){ subDescriptorTriplets.add(this.regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, this.imfTrackFileReader.getByteProvider(subDescriptorHeader))); } return this.regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, imfErrorLogger); } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <inputFilePath> <workingDirectory>%n", IMFTrackFileCPLBuilder.class.getName())); return sb.toString(); } public static void main(String[] args){ if (args.length != 2) { logger.error(usage()); throw new IllegalArgumentException("Invalid parameters"); } File inputFile = new File(args[0]); if(!inputFile.exists()){ logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } File workingDirectory = new File(args[1]); logger.info(String.format("File Name is %s", inputFile.getName())); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); IMFTrackFileReader imfTrackFileReader = new IMFTrackFileReader(workingDirectory, resourceByteRangeProvider); StringBuilder sb = new StringBuilder(); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); try { IMFTrackFileCPLBuilder imfTrackFileCPLBuilder = new IMFTrackFileCPLBuilder(workingDirectory, inputFile); sb.append(imfTrackFileReader.getRandomIndexPack(imfErrorLogger)); logger.info(String.format("%s", sb.toString())); imfTrackFileCPLBuilder.getCompositionPlaylist(imfErrorLogger); } catch(IOException e) { throw new IMFException(e); } List<ErrorLogger.ErrorObject> errors = imfErrorLogger.getErrors(); if(errors.size() > 0){ long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("IMFTrackFile has %d errors and %d warnings", errors.size() - warningCount, warningCount)); for(ErrorLogger.ErrorObject errorObject : errors){ if(errorObject.getErrorLevel() != IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if(errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } } else{ logger.info(imfTrackFileReader.toString()); logger.info("No errors were detected in the IMFTrackFile"); } } }
5,038
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/app/MXFEssenceReader.java
package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.PartitionPack; import com.netflix.imflibrary.st0377.PrimerPack; import com.netflix.imflibrary.st0377.RandomIndexPack; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.FileDataProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.RegXMLLibHelper; import com.sandflow.smpte.klv.Triplet; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class MXFEssenceReader { private final IMFErrorLogger imfErrorLogger; private final ResourceByteRangeProvider resourceByteRangeProvider; private final File workingDirectory; /** * A constructor for the MXFEssenceReader object * @param workingDirectory the working directory * @param resourceByteRangeProvider corresponding to the MXF essence, referred to as the essence in the rest of the documentation */ public MXFEssenceReader(File workingDirectory, ResourceByteRangeProvider resourceByteRangeProvider) { this.imfErrorLogger = new IMFErrorLoggerImpl(); this.workingDirectory = workingDirectory; this.resourceByteRangeProvider = resourceByteRangeProvider; } /** * A method that returns the random index pack in the Essence * @return RandomIndexPack in the essence * @throws IOException - any I/O related error will be exposed through an IOException */ public RandomIndexPack getRandomIndexPack()throws IOException { long archiveFileSize = this.resourceByteRangeProvider.getResourceSize(); long randomIndexPackSize; {//logic to provide as an input stream the portion of the archive that contains randomIndexPack size long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; File fileWithRandomIndexPackSize = this.resourceByteRangeProvider.getByteRange(rangeStart, rangeEnd, this.workingDirectory); byte[] bytes = Files.readAllBytes(Paths.get(fileWithRandomIndexPackSize.toURI())); randomIndexPackSize = (long)(ByteBuffer.wrap(bytes).getInt()); } RandomIndexPack randomIndexPack; {//logic to provide as an input stream the portion of the archive that contains randomIndexPack long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - randomIndexPackSize; if (rangeStart < 0) { throw new MXFException(String.format("randomIndexPackSize = %d obtained from last 4 bytes of the MXF file is larger than archiveFile size = %d, implying that this file does not contain a RandomIndexPack", randomIndexPackSize, archiveFileSize)); } File fileWithRandomIndexPack = this.resourceByteRangeProvider.getByteRange(rangeStart, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithRandomIndexPack); randomIndexPack = new RandomIndexPack(byteProvider, rangeStart, randomIndexPackSize); } return randomIndexPack; } /** * A method that returns an object model of the HeaderPartition in the Essence * @return Header partition in the essence * @throws IOException - any I/O related error will be exposed through an IOException */ public HeaderPartition getHeaderPartition() throws IOException{ RandomIndexPack randomIndexPack = this.getRandomIndexPack(); List<Long> allPartitionByteOffsets = randomIndexPack.getAllPartitionByteOffsets(); long inclusiveRangeStart = allPartitionByteOffsets.get(0); long inclusiveRangeEnd = allPartitionByteOffsets.get(1) - 1; File fileWithHeaderPartition = this.resourceByteRangeProvider.getByteRange(inclusiveRangeStart, inclusiveRangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithHeaderPartition); HeaderPartition headerPartition = new HeaderPartition(byteProvider, inclusiveRangeStart, inclusiveRangeEnd - inclusiveRangeStart + 1, this.imfErrorLogger); return headerPartition; } /** * A method that returns a list of partition packs in the Essence * @return List of partition packs in the essence * @throws IOException - any I/O related error will be exposed through an IOException */ public List<PartitionPack> getPartitionPacks() throws IOException{ RandomIndexPack randomIndexPack = getRandomIndexPack(); List<PartitionPack> partitionPacks = new ArrayList<>(); List<Long> allPartitionByteOffsets = randomIndexPack.getAllPartitionByteOffsets(); for (long offset : allPartitionByteOffsets) { partitionPacks.add(getPartitionPack(offset)); } try { //validate partition packs MXFOperationalPattern1A.checkOperationalPattern1ACompliance(partitionPacks); IMFConstraints.checkIMFCompliance(partitionPacks, imfErrorLogger); } catch (IMFException | MXFException e){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("This IMFTrackFile has fatal errors in the partition packs, please see the errors that follow.")); if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } } return partitionPacks; } /** * A method that returns a list of EssenceDescriptor objects referenced by the Source Packages in the Essence * * @return List of DOM Nodes corresponding to every EssenceDescriptor in the essence * @throws IOException - any I/O related error will be exposed through an IOException */ public List<Node> getEssenceDescriptorsDOMNodes() throws IOException{ try { List<InterchangeObject.InterchangeObjectBO> essenceDescriptors = this.getHeaderPartition().getEssenceDescriptors(); List<Node> essenceDescriptorNodes = new ArrayList<>(); for (InterchangeObject.InterchangeObjectBO essenceDescriptor : essenceDescriptors) { KLVPacket.Header essenceDescriptorHeader = essenceDescriptor.getHeader(); List<KLVPacket.Header> subDescriptorHeaders = this.getSubDescriptorKLVHeader(essenceDescriptor); /*Create a dom*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); DocumentFragment documentFragment = this.getEssenceDescriptorAsDocumentFragment(document, essenceDescriptorHeader, subDescriptorHeaders); Node node = documentFragment.getFirstChild(); essenceDescriptorNodes.add(node); } return essenceDescriptorNodes; } catch(ParserConfigurationException e){ throw new IMFException(e); } } /** * A method that returns a list of EssenceDescriptor objects referenced by the Source Packages in the Essence * * @return List of Object model representations corresponding to every EssenceDescriptor in the essence * @throws IOException - any I/O related error will be exposed through an IOException */ public List<? extends InterchangeObject.InterchangeObjectBO> getEssenceDescriptors() throws IOException{ return this.getHeaderPartition().getEssenceDescriptors(); } /** * A method that returns the EssenceTypes present in an MXF file. * @return a list of essence types present in the MXF file * @throws IOException - any I/O related error will be exposed through an IOException */ public List<HeaderPartition.EssenceTypeEnum> getEssenceTypes() throws IOException{ return this.getHeaderPartition().getEssenceTypes(); } /** * A method that returns the spoken language within this essence provided it is an Audio Essence * @return string representing a spoken language as defined in RFC-5646 * @throws IOException - any I/O related error is exposed through an IOException */ public String getAudioEssenceSpokenLanguage() throws IOException { return this.getHeaderPartition().getAudioEssenceSpokenLanguage(); } private PartitionPack getPartitionPack(long resourceOffset) throws IOException { long archiveFileSize = this.resourceByteRangeProvider.getResourceSize(); KLVPacket.Header header; {//logic to provide as an input stream the portion of the archive that contains PartitionPack KLVPacker Header long rangeEnd = resourceOffset + (KLVPacket.KEY_FIELD_SIZE + KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE) -1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); File fileWithPartitionPackKLVPacketHeader = this.resourceByteRangeProvider.getByteRange(resourceOffset, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithPartitionPackKLVPacketHeader); header = new KLVPacket.Header(byteProvider, resourceOffset); } PartitionPack partitionPack; {//logic to provide as an input stream the portion of the archive that contains a PartitionPack and next KLV header long rangeEnd = resourceOffset + (KLVPacket.KEY_FIELD_SIZE + header.getLSize() + header.getVSize()) + (KLVPacket.KEY_FIELD_SIZE + KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE) + -1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); File fileWithPartitionPack = this.resourceByteRangeProvider.getByteRange(resourceOffset, rangeEnd, this.workingDirectory); ByteProvider byteProvider = this.getByteProvider(fileWithPartitionPack); partitionPack = new PartitionPack(byteProvider, resourceOffset, true); } return partitionPack; } private List<KLVPacket.Header> getSubDescriptorKLVHeader(InterchangeObject.InterchangeObjectBO essenceDescriptor) throws IOException { List<KLVPacket.Header> subDescriptorHeaders = new ArrayList<>(); List<InterchangeObject.InterchangeObjectBO>subDescriptors = this.getHeaderPartition().getSubDescriptors(essenceDescriptor); for(InterchangeObject.InterchangeObjectBO subDescriptorBO : subDescriptors){ if(subDescriptorBO != null) { subDescriptorHeaders.add(subDescriptorBO.getHeader()); } } return subDescriptorHeaders; } private DocumentFragment getEssenceDescriptorAsDocumentFragment(Document document, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header>subDescriptors) throws MXFException, IOException { document.setXmlStandalone(true); PrimerPack primerPack = this.getHeaderPartition().getPrimerPack(); RegXMLLibHelper regXMLLibHelper = new RegXMLLibHelper(primerPack.getHeader(), this.getByteProvider(primerPack.getHeader())); Triplet essenceDescriptorTriplet = regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor, this.getByteProvider(essenceDescriptor)); //DocumentFragment documentFragment = this.regXMLLibHelper.getDocumentFragment(essenceDescriptorTriplet, document); /*Get the Triplets corresponding to the SubDescriptors*/ List<Triplet> subDescriptorTriplets = new ArrayList<>(); for(KLVPacket.Header subDescriptorHeader : subDescriptors){ subDescriptorTriplets.add(regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, this.getByteProvider(subDescriptorHeader))); } return regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, this.imfErrorLogger); } private KLVPacket.Header getPrimerPackHeader() throws IOException { return this.getHeaderPartition().getPrimerPack().getHeader(); } private ByteProvider getByteProvider(KLVPacket.Header header) throws IOException { File file = this.resourceByteRangeProvider.getByteRange(header.getByteOffset(), header.getByteOffset() + header.getKLSize() + header.getVSize(), this.workingDirectory); return this.getByteProvider(file); } private ByteProvider getByteProvider(File file) throws IOException { ByteProvider byteProvider; Long size = file.length(); if(size <= 0){ throw new IOException(String.format("Range of bytes (%d) has to be +ve and non-zero", size)); } if(size <= Integer.MAX_VALUE) { byte[] bytes = Files.readAllBytes(Paths.get(file.toURI())); byteProvider = new ByteArrayDataProvider(bytes); } else{ byteProvider = new FileDataProvider(file); } return byteProvider; } }
5,039
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/app/IMPAnalyzer.java
package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.PartitionPack; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st0429_8.PackingList; import com.netflix.imflibrary.st0429_9.AssetMap; import com.netflix.imflibrary.st0429_9.BasicMapProfileV2MappedFileSet; import com.netflix.imflibrary.st2067_100.OutputProfileList; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.st2067_2.IMFEssenceComponentVirtualTrack; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import static com.netflix.imflibrary.RESTfulInterfaces.IMPValidator.validateAssetMap; import static com.netflix.imflibrary.RESTfulInterfaces.IMPValidator.validateCPL; import static com.netflix.imflibrary.RESTfulInterfaces.IMPValidator.validateOPL; import static com.netflix.imflibrary.RESTfulInterfaces.IMPValidator.validatePKL; /** * Created by svenkatrav on 9/2/16. */ public class IMPAnalyzer { private static final String CONFORMANCE_LOGGER_PREFIX = "Virtual Track Conformance"; private static final Logger logger = LoggerFactory.getLogger(IMPAnalyzer.class); private static UUID getTrackFileId(PayloadRecord payloadRecord, IMFErrorLogger imfErrorLogger) throws IOException { if (payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Payload asset type is %s, expected asset type %s", payloadRecord.getPayloadAssetType(), PayloadRecord.PayloadAssetType.EssencePartition.toString())); return null; } HeaderPartition headerPartition = new HeaderPartition(new ByteArrayDataProvider(payloadRecord.getPayload()), 0L, (long) payloadRecord.getPayload().length, imfErrorLogger); Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); return packageUUID; } private static Boolean isVirtualTrackComplete(IMFEssenceComponentVirtualTrack virtualTrack, Set<UUID> trackFileIDsSet) throws IOException { for (UUID uuid : virtualTrack.getTrackResourceIds()) { if (!trackFileIDsSet.contains(uuid)) { return false; } } return true; } private static Boolean isCompositionComplete(ApplicationComposition applicationComposition, Set<UUID> trackFileIDsSet, IMFErrorLogger imfErrorLogger) throws IOException { boolean bComplete = true; for (IMFEssenceComponentVirtualTrack virtualTrack : applicationComposition.getEssenceVirtualTracks()) { for (UUID uuid : virtualTrack.getTrackResourceIds()) { if (!trackFileIDsSet.contains(uuid)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes .IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("CPL resource %s is not present in the package", uuid.toString())); bComplete &= false; } } } return bComplete; } @Nullable private static PayloadRecord getHeaderPartitionPayloadRecord(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException { long archiveFileSize = resourceByteRangeProvider.getResourceSize(); long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; if(rangeStart < 0 ) { return null; } byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssenceFooter4Bytes, rangeStart, rangeEnd); Long randomIndexPackSize = IMPValidator.getRandomIndexPackSize(payloadRecord); rangeStart = archiveFileSize - randomIndexPackSize; rangeEnd = archiveFileSize - 1; if(rangeStart < 0 ) { return null; } byte[] randomIndexPackBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord randomIndexPackPayload = new PayloadRecord(randomIndexPackBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); List<Long> partitionByteOffsets = IMPValidator.getEssencePartitionOffsets(randomIndexPackPayload, randomIndexPackSize); if (partitionByteOffsets.size() >= 2) { rangeStart = partitionByteOffsets.get(0); rangeEnd = partitionByteOffsets.get(1) - 1; byte[] headerPartitionBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord headerParitionPayload = new PayloadRecord(headerPartitionBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); return headerParitionPayload; } return null; } private static PartitionPack getPartitionPack(ResourceByteRangeProvider resourceByteRangeProvider, long resourceOffset) throws IOException { long archiveFileSize = resourceByteRangeProvider.getResourceSize(); KLVPacket.Header header; {//logic to provide as an input stream the portion of the archive that contains PartitionPack KLVPacker Header long rangeStart = resourceOffset; long rangeEnd = resourceOffset + (KLVPacket.KEY_FIELD_SIZE + KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE) -1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); byte[] bytesWithPartitionPackKLVPacketHeader = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); ByteProvider imfEssenceComponentByteProvider = new ByteArrayDataProvider(bytesWithPartitionPackKLVPacketHeader); header = new KLVPacket.Header(imfEssenceComponentByteProvider, rangeStart); } PartitionPack partitionPack; long rangeStart = resourceOffset; long rangeEnd = resourceOffset + header.getKLSize() + header.getVSize() - 1; rangeEnd = rangeEnd < (archiveFileSize - 1) ? rangeEnd : (archiveFileSize - 1); byte[] partitionBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); partitionPack = new PartitionPack(new ByteArrayDataProvider(partitionBytes)); return partitionPack; } private static List<PayloadRecord> getIndexTablePartitionPayloadRecords(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException { List<PayloadRecord> payloadRecords = new ArrayList<>(); long archiveFileSize = resourceByteRangeProvider.getResourceSize(); long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; if(rangeStart < 0 ) { return payloadRecords; } byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssenceFooter4Bytes, rangeStart, rangeEnd); Long randomIndexPackSize = IMPValidator.getRandomIndexPackSize(payloadRecord); rangeStart = archiveFileSize - randomIndexPackSize; rangeEnd = archiveFileSize - 1; if(rangeStart < 0 ) { return payloadRecords; } byte[] randomIndexPackBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord randomIndexPackPayload = new PayloadRecord(randomIndexPackBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); List<Long> partitionByteOffsets = new ArrayList<>(); partitionByteOffsets.addAll(IMPValidator.getEssencePartitionOffsets(randomIndexPackPayload, randomIndexPackSize)); partitionByteOffsets.add(resourceByteRangeProvider.getResourceSize()); for(int i =0; i < partitionByteOffsets.size() -1; i++) { rangeStart = partitionByteOffsets.get(i); rangeEnd = partitionByteOffsets.get(i+1) - 1; PartitionPack partitionPack = getPartitionPack(resourceByteRangeProvider, rangeStart); //2067-5 section 5.1.1 if (partitionPack.hasEssenceContainer() && partitionPack.hasIndexTableSegments()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Partition %d has both index table and essence", i)); } else if (partitionPack.hasIndexTableSegments()) { byte[] partitionBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord partitionPayloadRecord = new PayloadRecord(partitionBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); payloadRecords.add(partitionPayloadRecord); } } return payloadRecords; } private static List<ErrorLogger.ErrorObject> conformVirtualTrack(ResourceByteRangeProvider cplByteRangeProvider, Composition.VirtualTrack virtualTrack, List<PayloadRecord> headerPartitionPayloadRecords) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); byte[] bytes = cplByteRangeProvider.getByteRangeAsBytes(0, cplByteRangeProvider.getResourceSize() - 1); PayloadRecord cplPayloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, cplByteRangeProvider.getResourceSize()); imfErrorLogger.addAllErrors(IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, virtualTrack, headerPartitionPayloadRecords)); return imfErrorLogger.getErrors(); } public static Map<String, List<ErrorLogger.ErrorObject>> analyzePackage(File rootFile) throws IOException { Map<String, List<ErrorLogger.ErrorObject>> errorMap = new HashMap<>(); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> headerPartitionPayloadRecords = new ArrayList<>(); try { BasicMapProfileV2MappedFileSet mapProfileV2MappedFileSet = new BasicMapProfileV2MappedFileSet(rootFile); imfErrorLogger.addAllErrors(mapProfileV2MappedFileSet.getErrors()); IMFErrorLogger assetMapErrorLogger = new IMFErrorLoggerImpl(); try { AssetMap assetMap = new AssetMap(new File(mapProfileV2MappedFileSet.getAbsoluteAssetMapURI())); assetMapErrorLogger.addAllErrors(assetMap.getErrors()); for (AssetMap.Asset packingListAsset : assetMap.getPackingListAssets()) { IMFErrorLogger packingListErrorLogger = new IMFErrorLoggerImpl(); try { PackingList packingList = new PackingList(new File(rootFile, packingListAsset.getPath().toString())); packingListErrorLogger.addAllErrors(packingList.getErrors()); Map<UUID, PayloadRecord> trackFileIDToHeaderPartitionPayLoadMap = new HashMap<>(); for (PackingList.Asset asset : packingList.getAssets()) { if (asset.getType().equals(PackingList.Asset.APPLICATION_MXF_TYPE)) { URI path = assetMap.getPath(asset.getUUID()); if( path == null) { packingListErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Failed to get path for Asset with ID = %s", asset.getUUID().toString())); continue; } File assetFile = new File(rootFile, assetMap.getPath(asset.getUUID()).toString()); if(!assetFile.exists()) { packingListErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Cannot find asset with path %s ID = %s", assetFile.getAbsolutePath(), asset.getUUID().toString ())); continue; } ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetFile); IMFErrorLogger trackFileErrorLogger = new IMFErrorLoggerImpl(); try { PayloadRecord headerPartitionPayloadRecord = getHeaderPartitionPayloadRecord(resourceByteRangeProvider, trackFileErrorLogger); if (headerPartitionPayloadRecord == null) { trackFileErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Failed to get header partition for %s", assetFile.getPath())); } else { List<PayloadRecord> payloadRecords = new ArrayList<>(); payloadRecords.add(headerPartitionPayloadRecord); trackFileErrorLogger.addAllErrors(IMPValidator.validateIMFTrackFileHeaderMetadata(payloadRecords)); headerPartitionPayloadRecords.add(headerPartitionPayloadRecord); UUID trackFileID = getTrackFileId(headerPartitionPayloadRecord, trackFileErrorLogger); if(trackFileID != null) { trackFileIDToHeaderPartitionPayLoadMap.put(trackFileID, headerPartitionPayloadRecord); if (!trackFileID.equals(asset.getUUID())) { // ST 2067-2:2016 7.3.1: The value of the Id element shall be extracted from the asset as specified in Table 19 for the track file asset trackFileErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("UUID %s in the MXF file is not same as UUID %s of the MXF file in the AssetMap", trackFileID.toString(), asset.getUUID().toString())); } } } List<PayloadRecord> payloadRecords = getIndexTablePartitionPayloadRecords(resourceByteRangeProvider, trackFileErrorLogger); trackFileErrorLogger.addAllErrors(IMPValidator.validateIndexTableSegments(payloadRecords)); } catch( MXFException e) { trackFileErrorLogger.addAllErrors(e.getErrors()); } catch( IMFException e) { trackFileErrorLogger.addAllErrors(e.getErrors()); } finally { errorMap.put(assetFile.getName(), trackFileErrorLogger.getErrors()); } } } List<ApplicationComposition> applicationCompositionList = analyzeApplicationCompositions( rootFile, assetMap, packingList, headerPartitionPayloadRecords, packingListErrorLogger, errorMap, trackFileIDToHeaderPartitionPayLoadMap); analyzeOutputProfileLists( rootFile, assetMap, packingList, applicationCompositionList, packingListErrorLogger, errorMap); } catch (IMFException e) { packingListErrorLogger.addAllErrors(e.getErrors()); } finally { errorMap.put(packingListAsset.getPath().toString(), packingListErrorLogger.getErrors()); } } } catch (IMFException e) { assetMapErrorLogger.addAllErrors(e.getErrors()); } finally { errorMap.put(BasicMapProfileV2MappedFileSet.ASSETMAP_FILE_NAME, assetMapErrorLogger.getErrors()); } } catch (IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); errorMap.put(rootFile.getName(), imfErrorLogger.getErrors()); } return errorMap; } public static List<ErrorLogger.ErrorObject> validateEssencePartition(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { IMFErrorLogger trackFileErrorLogger = new IMFErrorLoggerImpl(); List<PayloadRecord> headerPartitionPayloadRecords = new ArrayList<>(); PayloadRecord headerPartitionPayload = getHeaderPartitionPayloadRecord(resourceByteRangeProvider, trackFileErrorLogger); if(headerPartitionPayload == null) { trackFileErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Failed to get header partition")); } else { headerPartitionPayloadRecords.add(headerPartitionPayload); trackFileErrorLogger.addAllErrors(IMPValidator.validateIMFTrackFileHeaderMetadata(headerPartitionPayloadRecords)); } // Validate index table segments List<PayloadRecord> indexSegmentPayloadRecords = getIndexTablePartitionPayloadRecords(resourceByteRangeProvider, trackFileErrorLogger); trackFileErrorLogger.addAllErrors(IMPValidator.validateIndexTableSegments(indexSegmentPayloadRecords)); trackFileErrorLogger.addAllErrors(IMPValidator.validateIndexEditRate(headerPartitionPayloadRecords, indexSegmentPayloadRecords)); return trackFileErrorLogger.getErrors(); } public static List<OutputProfileList> analyzeOutputProfileLists(File rootFile, AssetMap assetMap, PackingList packingList, List<ApplicationComposition> applicationCompositionList, IMFErrorLogger packingListErrorLogger, Map<String, List<ErrorLogger.ErrorObject>> errorMap) throws IOException { List<OutputProfileList> outputProfileListTypeList = new ArrayList<>(); for (PackingList.Asset asset : packingList.getAssets()) { if (asset.getType().equals(PackingList.Asset.TEXT_XML_TYPE)) { URI path = assetMap.getPath(asset.getUUID()); if( path == null) { packingListErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Failed to get path for Asset with ID = %s", asset.getUUID().toString())); continue; } File assetFile = new File(rootFile, assetMap.getPath(asset.getUUID()).toString()); if(!assetFile.exists()) { packingListErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Cannot find asset with path %s ID = %s", assetFile.getAbsolutePath(), asset.getUUID().toString())); continue; } ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetFile); if (OutputProfileList.isOutputProfileList(resourceByteRangeProvider)) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); try { OutputProfileList outputProfileListType = OutputProfileList.getOutputProfileListType(resourceByteRangeProvider, imfErrorLogger); if(outputProfileListType == null) { continue; } if(!outputProfileListType.getId().equals(asset.getUUID())) { // ST 2067-2:2016 7.3.1: The value of the Id element shall be extracted from the asset as specified in Table 19 for the OPL asset imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("UUID %s in the OPL is not same as UUID %s of the OPL in the AssetMap", outputProfileListType.getId().toString(), asset.getUUID().toString())); } outputProfileListTypeList.add(outputProfileListType); Optional<ApplicationComposition> optional = applicationCompositionList.stream().filter(e -> e.getUUID().equals(outputProfileListType.getCompositionPlaylistId())).findAny(); if(!optional.isPresent()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_OPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("Failed to get application composition with ID = %s for OutputProfileList with ID %s", outputProfileListType.getCompositionPlaylistId().toString(), outputProfileListType.getId().toString())); continue; } imfErrorLogger.addAllErrors(outputProfileListType.applyOutputProfileOnComposition(optional.get())); } catch (IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } finally { errorMap.put(assetFile.getName(), imfErrorLogger.getErrors()); } } } } return outputProfileListTypeList; } public static List<ApplicationComposition> analyzeApplicationCompositions( File rootFile, AssetMap assetMap, PackingList packingList, List<PayloadRecord> headerPartitionPayloadRecords, IMFErrorLogger packingListErrorLogger, Map<String, List<ErrorLogger.ErrorObject>> errorMap, Map<UUID, PayloadRecord> trackFileIDToHeaderPartitionPayLoadMap) throws IOException { List<ApplicationComposition> applicationCompositionList = new ArrayList<>(); for (PackingList.Asset asset : packingList.getAssets()) { if (asset.getType().equals(PackingList.Asset.TEXT_XML_TYPE)) { URI path = assetMap.getPath(asset.getUUID()); if( path == null) { packingListErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Failed to get path for Asset with ID = %s", asset.getUUID().toString())); continue; } File assetFile = new File(rootFile, assetMap.getPath(asset.getUUID()).toString()); if(!assetFile.exists()) { packingListErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Cannot find asset with path %s ID = %s", assetFile.getAbsolutePath(), asset.getUUID().toString())); continue; } ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetFile); if (ApplicationComposition.isCompositionPlaylist(resourceByteRangeProvider)) { IMFErrorLogger compositionErrorLogger = new IMFErrorLoggerImpl(); IMFErrorLogger compositionConformanceErrorLogger = new IMFErrorLoggerImpl(); PayloadRecord cplPayloadRecord = new PayloadRecord(resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1), PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); try { ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(resourceByteRangeProvider, compositionErrorLogger); if(applicationComposition == null) { continue; } if(!applicationComposition.getUUID().equals(asset.getUUID())) { // ST 2067-2:2016 7.3.1: The value of the Id element shall be extracted from the asset as specified in Table 19 for the CPL asset compositionErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("UUID %s in the CPL is not same as UUID %s of the CPL in the AssetMap", applicationComposition.getUUID().toString(), asset.getUUID().toString())); } applicationCompositionList.add(applicationComposition); Set<UUID> trackFileIDsSet = trackFileIDToHeaderPartitionPayLoadMap .keySet(); try { if (!isCompositionComplete(applicationComposition, trackFileIDsSet, compositionConformanceErrorLogger)) { for (IMFEssenceComponentVirtualTrack virtualTrack : applicationComposition.getEssenceVirtualTracks()) { Set<UUID> trackFileIds = virtualTrack.getTrackResourceIds(); List<PayloadRecord> trackHeaderPartitionPayloads = new ArrayList<>(); for (UUID trackFileId : trackFileIds) { if (trackFileIDToHeaderPartitionPayLoadMap.containsKey(trackFileId)) trackHeaderPartitionPayloads.add (trackFileIDToHeaderPartitionPayLoadMap.get(trackFileId)); } if (isVirtualTrackComplete(virtualTrack, trackFileIDsSet)) { compositionConformanceErrorLogger.addAllErrors(IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, virtualTrack, trackHeaderPartitionPayloads)); } else if (trackHeaderPartitionPayloads.size() != 0) { compositionConformanceErrorLogger.addAllErrors(IMPValidator.conformVirtualTracksInCPL(cplPayloadRecord, trackHeaderPartitionPayloads, false)); } } } else { List<PayloadRecord> cplHeaderPartitionPayloads = applicationComposition.getEssenceVirtualTracks() .stream() .map(IMFEssenceComponentVirtualTrack::getTrackResourceIds) .flatMap(Set::stream) .map( e -> trackFileIDToHeaderPartitionPayLoadMap.get(e)) .collect(Collectors.toList()); compositionConformanceErrorLogger.addAllErrors(IMPValidator.areAllVirtualTracksInCPLConformed(cplPayloadRecord, cplHeaderPartitionPayloads)); } } catch (IMFException e) { compositionConformanceErrorLogger.addAllErrors(e.getErrors()); } finally { errorMap.put(assetFile.getName() + " " + CONFORMANCE_LOGGER_PREFIX, compositionConformanceErrorLogger.getErrors()); } } catch (IMFException e) { compositionErrorLogger.addAllErrors(e.getErrors()); } finally { errorMap.put(assetFile.getName(), compositionErrorLogger.getErrors()); } } } } return applicationCompositionList; } public static List<ErrorLogger.ErrorObject> analyzeFile(File inputFile) throws IOException { IMFErrorLogger errorLogger = new IMFErrorLoggerImpl(); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); if(inputFile.getName().lastIndexOf('.') > 0) { String extension = inputFile.getName().substring(inputFile.getName().lastIndexOf('.')+1); if(extension.equalsIgnoreCase("mxf")) { errorLogger.addAllErrors(validateEssencePartition(resourceByteRangeProvider)); return errorLogger.getErrors(); } } byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.Unknown, 0L, resourceByteRangeProvider.getResourceSize()); PayloadRecord.PayloadAssetType payloadAssetType = IMPValidator.getPayloadType(payloadRecord); payloadRecord = new PayloadRecord(bytes, payloadAssetType, 0L, resourceByteRangeProvider.getResourceSize()); switch (payloadAssetType) { case PackingList: errorLogger.addAllErrors(validatePKL(payloadRecord)); break; case AssetMap: errorLogger.addAllErrors(validateAssetMap(payloadRecord)); break; case CompositionPlaylist: errorLogger.addAllErrors(validateCPL(payloadRecord)); break; case OutputProfileList: errorLogger.addAllErrors(validateOPL(payloadRecord)); break; default: errorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Unknown AssetType")); } return errorLogger.getErrors(); } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <package_directory>%n", IMPAnalyzer.class.getName())); sb.append(String.format("%s <cpl_file>%n", IMPAnalyzer.class.getName())); sb.append(String.format("%s <asset_map_file>%n", IMPAnalyzer.class.getName())); sb.append(String.format("%s <pkl_file>%n", IMPAnalyzer.class.getName())); sb.append(String.format("%s <mxf_file>%n", IMPAnalyzer.class.getName())); return sb.toString(); } private static void logErrors(String file, List<ErrorLogger.ErrorObject> errors) { if(errors.size()>0) { long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("%s has %d errors and %d warnings", file, errors.size() - warningCount, warningCount)); for (ErrorLogger.ErrorObject errorObject : errors) { if (errorObject.getErrorLevel() != IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error("\t\t" + errorObject.toString()); } else if (errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn("\t\t" + errorObject.toString()); } } } else { logger.info(String.format("%s has no errors or warnings", file)); } } public static void main(String args[]) throws IOException { if (args.length != 1) { logger.error(usage()); System.exit(-1); } String inputFileName = args[0]; File inputFile = new File(inputFileName); if(!inputFile.exists()){ logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } if(inputFile.isDirectory()) { logger.info("==========================================================================" ); logger.info(String.format("Analyzing IMF package %s", inputFile.getName())); logger.info("=========================================================================="); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); for(Map.Entry<String, List<ErrorLogger.ErrorObject>> entry: errorMap.entrySet()) { if(!entry.getKey().contains(CONFORMANCE_LOGGER_PREFIX)) { logErrors(entry.getKey(), entry.getValue()); } } logger.info("\n\n\n"); logger.info("==========================================================================" ); logger.info("Virtual Track Conformance" ); logger.info("=========================================================================="); for(Map.Entry<String, List<ErrorLogger.ErrorObject>> entry: errorMap.entrySet()) { if(entry.getKey().contains(CONFORMANCE_LOGGER_PREFIX)) { logErrors(entry.getKey(), entry.getValue()); } } } else { logger.info("==========================================================================\n" ); logger.info(String.format("Analyzing file %s", inputFile.getName())); logger.info("==========================================================================\n"); List<ErrorLogger.ErrorObject>errors = analyzeFile(inputFile); logErrors(inputFile.getName(), errors); } } }
5,040
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/ApplicationCompositionFactory.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * This class provides a factory method to construct ApplicationComposition based on CPL ApplicationIdentification. */ public class ApplicationCompositionFactory { private static final Set<String> namespacesApplication2Composition = Collections.unmodifiableSet(new HashSet<String>() {{ add("http://www.smpte-ra.org/schemas/2067-20/2013"); add("http://www.smpte-ra.org/schemas/2067-20/2016"); }}); private static final Set<String> namespacesApplication2EComposition = Collections.unmodifiableSet(new HashSet<String>() {{ add("http://www.smpte-ra.org/schemas/2067-21/2014"); add("http://www.smpte-ra.org/schemas/2067-21/2016"); add("http://www.smpte-ra.org/ns/2067-21/2020"); }}); private static final Set<String> namespacesApplication2E2021Composition = Collections.unmodifiableSet(new HashSet<String>() {{ add("http://www.smpte-ra.org/ns/2067-21/2021"); }}); private static final Set<String> namespacesApplication5Composition = Collections.unmodifiableSet(new HashSet<String>() {{ add("http://www.smpte-ra.org/ns/2067-50/2017"); }}); public enum ApplicationCompositionType { APPLICATION_2_COMPOSITION_TYPE(Application2Composition.class, namespacesApplication2Composition), APPLICATION_2E_COMPOSITION_TYPE(Application2ExtendedComposition.class, namespacesApplication2EComposition), APPLICATION_5_COMPOSITION_TYPE(Application5Composition.class, namespacesApplication5Composition), APPLICATION_2E2021_COMPOSITION_TYPE(Application2E2021.class, namespacesApplication2E2021Composition), APPLICATION_UNSUPPORTED_COMPOSITION_TYPE(ApplicationUnsupportedComposition.class, Collections.unmodifiableSet(new HashSet<>())); private Set<String> nameSpaceSet; private Class<?> clazz; ApplicationCompositionType(Class<?> clazz, Set<String> nameSpaceSet) { this.nameSpaceSet = nameSpaceSet; this.clazz = clazz; } public Class<?> getClazz() { return clazz; } public Set<String> getNameSpaceSet() { return nameSpaceSet; } public static ApplicationCompositionType fromApplicationID(String applicationIdentification) { for(ApplicationCompositionType applicationCompositionType : ApplicationCompositionType.values()) { if(applicationCompositionType.getNameSpaceSet().contains(applicationIdentification)) { return applicationCompositionType; } } return APPLICATION_UNSUPPORTED_COMPOSITION_TYPE; } } public static ApplicationComposition getApplicationComposition(File inputFile, IMFErrorLogger imfErrorLogger) throws IOException { return getApplicationComposition(new FileByteRangeProvider(inputFile), imfErrorLogger); } public static ApplicationComposition getApplicationComposition(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException { return getApplicationComposition(resourceByteRangeProvider, imfErrorLogger, new HashSet<>()); } public static ApplicationComposition getApplicationComposition(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger, Set<String> homogeneitySelectionSet) throws IOException { ApplicationComposition composition = null; Class<?> clazz = null; try { IMFCompositionPlaylistType imfCompositionPlaylistType = IMFCompositionPlaylistType.getCompositionPlayListType(resourceByteRangeProvider, imfErrorLogger); if (imfCompositionPlaylistType.getApplicationIdentificationSet().size() == 0) { clazz = Application2ExtendedComposition.class; imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Missing ApplicationIdentification in CPL")); Constructor<?> constructor = clazz.getConstructor(IMFCompositionPlaylistType.class, Set.class); composition = (ApplicationComposition) constructor.newInstance(imfCompositionPlaylistType, homogeneitySelectionSet); imfErrorLogger.addAllErrors(composition.getErrors()); } else { for (String applicationIdentification : imfCompositionPlaylistType.getApplicationIdentificationSet()) { ApplicationCompositionType applicationCompositionType = ApplicationCompositionType.fromApplicationID(applicationIdentification); clazz = applicationCompositionType.getClazz(); Constructor<?> constructor = clazz.getConstructor(IMFCompositionPlaylistType.class, Set.class); composition = (ApplicationComposition) constructor.newInstance(imfCompositionPlaylistType, homogeneitySelectionSet); imfErrorLogger.addAllErrors(composition.getErrors()); } } } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); return null; } catch(NoSuchMethodException|IllegalAccessException|InstantiationException| InvocationTargetException e){ if(e instanceof InvocationTargetException ) { Throwable ex = InvocationTargetException.class.cast(e).getTargetException(); if(ex instanceof IMFException) { imfErrorLogger.addAllErrors(IMFException.class.cast(ex).getErrors()); return null; } } imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.INTERNAL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format(String.format("No matching constructor for class %s", clazz != null ? clazz.getSimpleName(): "ApplicationComposition"))); return null; } return composition; } }
5,041
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/CoreConstraints.java
package com.netflix.imflibrary.st2067_2; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; public final class CoreConstraints { private CoreConstraints() {} // Prevent instantiation. This class is constants and utilities only // SMPTE ST 2067-2 version namespaces public static final String NAMESPACE_IMF_2013 = "http://www.smpte-ra.org/schemas/2067-2/2013"; public static final String NAMESPACE_IMF_2016 = "http://www.smpte-ra.org/schemas/2067-2/2016"; public static final String NAMESPACE_IMF_2020 = "http://www.smpte-ra.org/ns/2067-2/2020"; static final List<String> SUPPORTED_NAMESPACES = Collections.unmodifiableList(Arrays.asList( NAMESPACE_IMF_2013, NAMESPACE_IMF_2016, NAMESPACE_IMF_2020)); /** * @deprecated Remove once all deprecated, package-based, 'getCoreConstraintsVersion' methods are removed. */ @Deprecated static String packageFromSchema(String coreConstraintsSchema) { if (coreConstraintsSchema.equals(NAMESPACE_IMF_2013)) return "org.smpte_ra.schemas._2067_3._2013"; else if (coreConstraintsSchema.equals(NAMESPACE_IMF_2016)) return "org.smpte_ra.schemas.st2067_2_2016"; else if (coreConstraintsSchema.equals(NAMESPACE_IMF_2020)) return "org.smpte_ra.schemas.st2067_2_2020"; else return coreConstraintsSchema; // No mapping, just return the schema value } // Determine the highest Core Constraints version based on the ApplicationIds used @Nullable public static String fromApplicationId(@Nonnull Collection<String> applicationIds) { // NOTE- When adding new namespaces or core constraint versions, be sure that the most recent core constraints // are checked first. That way if there are multiple ApplicationIdentifications, the newest version is returned. if (applicationIds.contains(Application2ExtendedComposition.SCHEMA_URI_APP2E_2020)) { return CoreConstraints.NAMESPACE_IMF_2020; } else if (applicationIds.contains(Application5Composition.SCHEMA_URI_APP5_2017) || applicationIds.contains(Application2ExtendedComposition.SCHEMA_URI_APP2E_2016) || applicationIds.contains(Application2Composition.SCHEMA_URI_APP2_2016)) { return CoreConstraints.NAMESPACE_IMF_2016; } else if (applicationIds.contains(Application2ExtendedComposition.SCHEMA_URI_APP2E_2014) || applicationIds.contains(Application2Composition.SCHEMA_URI_APP2_2013)) { return CoreConstraints.NAMESPACE_IMF_2013; } else { return null; } } // Determine the most recent core constraints version, based on a collection of element namespaces static String fromElementNamespaces(@Nonnull Collection<String> namespaces) { // NOTE- When adding new namespaces or core constraint versions, be sure that the most recent core constraints // are checked first. That way if there are multiple different namespaces, the newest version is returned. if (namespaces.contains(CoreConstraints.NAMESPACE_IMF_2020)) { return CoreConstraints.NAMESPACE_IMF_2020; } else if (namespaces.contains(CoreConstraints.NAMESPACE_IMF_2016)) { return CoreConstraints.NAMESPACE_IMF_2016; } else if (namespaces.contains(CoreConstraints.NAMESPACE_IMF_2013)) { return CoreConstraints.NAMESPACE_IMF_2013; } else { // TODO- Consider identify core constraints based on other namespaces // Example- IABSequence "http://www.smpte-ra.org/ns/2067-201/2019" requires core constraints ST 2067-2:2016 return null; } } }
5,042
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/AbstractApplicationComposition.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.PrimerPack; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st2067_201.IMFIABConstraintsChecker; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.RegXMLLibDictionary; import com.netflix.imflibrary.utils.RegXMLLibHelper; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import com.sandflow.smpte.klv.Triplet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; /** * This class represents a canonical model of the XML type 'CompositionPlaylistType' defined by SMPTE st2067-3, * A Composition object can be constructed from an XML file only if it satisfies all the constraints specified * in st2067-3 and st2067-2. This object model is intended to be agnostic of specific versions of the definitions of a * CompositionPlaylist(st2067-3) and its accompanying Core constraints(st2067-2). */ @Immutable public abstract class AbstractApplicationComposition implements ApplicationComposition { private static final Logger logger = LoggerFactory.getLogger(AbstractApplicationComposition.class); private final Set<String> essenceDescriptorKeyIgnoreSet; private final String coreConstraintsSchema; private final Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap; private final IMFCompositionPlaylistType compositionPlaylistType; private final Map<UUID, List<Node>> essenceDescriptorDomNodeMap; protected final IMFErrorLogger imfErrorLogger; protected final RegXMLLibDictionary regXMLLibDictionary; /** * Constructor for a {@link AbstractApplicationComposition Composition} object from a XML file * * @param compositionPlaylistXMLFile the input XML file that is conformed to schema and constraints specified in st2067-3:2013 and st2067-2:2013 * @throws IOException any I/O related error is exposed through an IOException */ public AbstractApplicationComposition(File compositionPlaylistXMLFile) throws IOException { this(new FileByteRangeProvider(compositionPlaylistXMLFile)); } /** * Constructor for a {@link AbstractApplicationComposition Composition} object from a XML file * * @param resourceByteRangeProvider corresponding to the Composition XML file. * if any {@link IMFErrorLogger.IMFErrors.ErrorLevels#FATAL fatal} errors are encountered * @throws IOException any I/O related error is exposed through an IOException */ public AbstractApplicationComposition(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { this(IMFCompositionPlaylistType.getCompositionPlayListType( resourceByteRangeProvider, new IMFErrorLoggerImpl()), new HashSet<String>()); } /** * Constructor for a {@link AbstractApplicationComposition Composition} object from a XML file * * @param imfCompositionPlaylistType corresponding to the Composition XML file. * if any {@link IMFErrorLogger.IMFErrors.ErrorLevels#FATAL fatal} errors are encountered * @param ignoreSet Set of essence descriptor fields to ignore */ public AbstractApplicationComposition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType, @Nonnull Set<String> ignoreSet) { this(imfCompositionPlaylistType, ignoreSet, new HashSet<>()); } /** * Constructor for a {@link AbstractApplicationComposition Composition} object from a XML file * * @param imfCompositionPlaylistType corresponding to the Composition XML file. * if any {@link IMFErrorLogger.IMFErrors.ErrorLevels#FATAL fatal} errors are encountered * @param ignoreSet Set of essence descriptor fields to ignore * @param homogeneitySelectionSet Set of essence descriptor fields to select in track homogeneity check */ public AbstractApplicationComposition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType, @Nonnull Set<String> ignoreSet, @Nonnull Set<String> homogeneitySelectionSet) { imfErrorLogger = new IMFErrorLoggerImpl(); this.compositionPlaylistType = imfCompositionPlaylistType; this.regXMLLibDictionary = new RegXMLLibDictionary(); this.coreConstraintsSchema = this.compositionPlaylistType.getCoreConstraintsSchema(); this.essenceDescriptorKeyIgnoreSet = Collections.unmodifiableSet(ignoreSet); this.virtualTrackMap = this.getVirtualTracksMap(compositionPlaylistType, imfErrorLogger); Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap= this.getEssenceDescriptorListMap(ignoreSet); imfErrorLogger.addAllErrors(IMFCoreConstraintsChecker.checkVirtualTracks(compositionPlaylistType, this .virtualTrackMap, essenceDescriptorListMap, this.regXMLLibDictionary, homogeneitySelectionSet)); if (IMFCoreConstraintsChecker.hasIABVirtualTracks(compositionPlaylistType, virtualTrackMap)) { List<ErrorLogger.ErrorObject> errors = IMFIABConstraintsChecker.checkIABVirtualTrack(compositionPlaylistType.getEditRate(), virtualTrackMap, essenceDescriptorListMap, this.regXMLLibDictionary, homogeneitySelectionSet); imfErrorLogger.addAllErrors(errors); } if ((compositionPlaylistType.getEssenceDescriptorList() == null) || (compositionPlaylistType.getEssenceDescriptorList().size() < 1)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ESSENCE_DESCRIPTOR_LIST_MISSING, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, "EssenceDescriptorList is either absent or empty."); } this.essenceDescriptorDomNodeMap = Collections.unmodifiableMap(createEssenceDescriptorDomNodeMap()); if (imfErrorLogger.hasFatalErrors()) { throw new IMFException(String.format("Found fatal errors in CompositionPlaylist XML file."), imfErrorLogger); } } /** * A stateless method that reads and parses all the virtual tracks of a Composition * * @param compositionPlaylistType - a CompositionPlaylist object model * @param imfErrorLogger - an object for logging errors * @return a map containing mappings of a UUID to the corresponding Composition.VirtualTrack */ private static Map<UUID, Composition.VirtualTrack> getVirtualTracksMap(@Nonnull IMFCompositionPlaylistType compositionPlaylistType, @Nonnull IMFErrorLogger imfErrorLogger) { Map<UUID, Composition.VirtualTrack> virtualTrackMap = new LinkedHashMap<>(); Map<UUID, List<IMFBaseResourceType>> virtualTrackResourceMap = getVirtualTrackResourceMap(compositionPlaylistType, imfErrorLogger); //process first segment to create virtual track map IMFSegmentType segment = compositionPlaylistType.getSegmentList().get(0); for (IMFSequenceType sequence : segment.getSequenceList()) { UUID uuid = UUIDHelper.fromUUIDAsURNStringToUUID(sequence.getTrackId()); if (virtualTrackMap.get(uuid) == null) { List<? extends IMFBaseResourceType> virtualTrackResourceList = null; if (virtualTrackResourceMap.get(uuid) == null) { virtualTrackResourceList = new ArrayList<IMFBaseResourceType>(); } else { virtualTrackResourceList = virtualTrackResourceMap.get(uuid); } Composition.VirtualTrack virtualTrack = null; if (virtualTrackResourceList.size() != 0) { if (virtualTrackResourceList.get(0) instanceof IMFTrackFileResourceType) { virtualTrack = new IMFEssenceComponentVirtualTrack(uuid, sequence.getType(), (List<IMFTrackFileResourceType>) virtualTrackResourceList, compositionPlaylistType.getEditRate()); } else if (virtualTrackResourceList.get(0) instanceof IMFMarkerResourceType) { virtualTrack = new IMFMarkerVirtualTrack(uuid, sequence.getType(), (List<IMFMarkerResourceType>) virtualTrackResourceList, compositionPlaylistType.getEditRate()); } } virtualTrackMap.put(uuid, virtualTrack); } else { //Section 6.9.3 st2067-3:2016 String message = String.format( "First segment in Composition XML file has multiple occurrences of virtual track UUID %s this is invalid.", uuid); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, message); } } IMFCoreConstraintsChecker.checkSegments(compositionPlaylistType, virtualTrackMap, imfErrorLogger); return virtualTrackMap; } /** * A stateless method that completely reads and parses the resources of all the Composition.VirtualTracks that are a part of the Composition * * @param compositionPlaylistType - a CompositionPlaylist object model * @param imfErrorLogger - an object for logging errors * @return map of VirtualTrack identifier to the list of all the Track's resources, for every Composition.VirtualTrack of the Composition */ private static Map<UUID, List<IMFBaseResourceType>> getVirtualTrackResourceMap(@Nonnull IMFCompositionPlaylistType compositionPlaylistType, @Nonnull IMFErrorLogger imfErrorLogger) { Map<UUID, List<IMFBaseResourceType>> virtualTrackResourceMap = new LinkedHashMap<>(); for (IMFSegmentType segment : compositionPlaylistType.getSegmentList()) { for (IMFSequenceType sequence : segment.getSequenceList()) { UUID uuid = UUIDHelper.fromUUIDAsURNStringToUUID(sequence.getTrackId()); if (virtualTrackResourceMap.get(uuid) == null) { virtualTrackResourceMap.put(uuid, new ArrayList<IMFBaseResourceType>()); } for (IMFBaseResourceType baseResource : sequence.getResourceList()) { /* Ignore track file resource with zero or negative duration */ if (baseResource.getSourceDuration().longValue() <= 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("Resource with zero source duration ignored: VirtualTrackID %s ResourceID %s", uuid.toString(), baseResource.getId())); } else { virtualTrackResourceMap.get(uuid).add(baseResource); } } } } //make virtualTrackResourceMap immutable for (Map.Entry<UUID, List<IMFBaseResourceType>> entry : virtualTrackResourceMap.entrySet()) { List<? extends IMFBaseResourceType> baseResources = entry.getValue(); entry.setValue(Collections.unmodifiableList(baseResources)); } return virtualTrackResourceMap; } /** * A method that returns a string representation of a Composition object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("======= Composition : %s =======%n", this.compositionPlaylistType.getId())); sb.append(this.compositionPlaylistType.getEditRate().toString()); return sb.toString(); } /** * A method that confirms if the inputStream corresponds to a Composition document instance. * * @param resourceByteRangeProvider corresponding to the Composition XML file. * @return a boolean indicating if the input file is a Composition document * @throws IOException - any I/O related error is exposed through an IOException */ public static boolean isCompositionPlaylist(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { return IMFCompositionPlaylistType.isCompositionPlaylist(resourceByteRangeProvider); } /** * Getter for the composition edit rate as specified in the Composition XML file * * @return the edit rate associated with the Composition */ public Composition.EditRate getEditRate() { return this.compositionPlaylistType.getEditRate(); } /** * Getter method for Annotation child element of CompositionPlaylist * * @return value of Annotation child element or null if it is not exist */ public @Nullable String getAnnotation() { return this.compositionPlaylistType.getAnnotation(); } /** * Getter method for Issuer child element of CompositionPlaylist * * @return value of Issuer child element or null if it is not exist */ public @Nullable String getIssuer() { return this.compositionPlaylistType.getIssuer(); } /** * Getter method for Creator child element of CompositionPlaylist * * @return value of Creator child element or null if it is not exist */ public @Nullable String getCreator() { return this.compositionPlaylistType.getCreator(); } /** * Getter method for ContentOriginator child element of CompositionPlaylist * * @return value of ContentOriginator child element or null if it is not exist */ public @Nullable String getContentOriginator() { return this.compositionPlaylistType.getContentOriginator(); } /** * Getter method for ContentTitle child element of CompositionPlaylist * * @return value of ContentTitle child element or null if it is not exist */ public @Nullable String getContentTitle() { return this.compositionPlaylistType.getContentTitle(); } /** * Getter for the virtual track map associated with this Composition * * @return {@link Map Map}&lt;{@link UUID UUID},{@link Composition.VirtualTrack VirtualTrack}&gt;. The UUID key corresponds to VirtualTrackID */ Map<UUID, ? extends Composition.VirtualTrack> getVirtualTrackMap() { return Collections.unmodifiableMap(this.virtualTrackMap); } /** * Getter for the UUID corresponding to this Composition document * * @return the uuid of this Composition object */ public UUID getUUID() { return this.compositionPlaylistType.getId(); } /** * Getter for the CompositionPlaylistType object model of the Composition defined by the st2067-3 schema. * * @return the composition playlist type object model. */ private IMFCompositionPlaylistType getCompositionPlaylistType() { return this.compositionPlaylistType; } /** * Get the Java package string for the Core Constraints version * @deprecated Instead use {@link #getCoreConstraintsSchema()} * * @return package containing the Core Constraints classes */ @Deprecated public String getCoreConstraintsVersion() { return CoreConstraints.packageFromSchema(this.coreConstraintsSchema); } /** * Getter for the Core Constraints schema URI. * @return URI for the Core Constraints schema */ @Nonnull public String getCoreConstraintsSchema() { return this.coreConstraintsSchema; } /** * Getter for the Track file resources in this Composition * * @return a list of track file resources that are a part of this composition or an empty list if there are none * track */ public List<IMFTrackFileResourceType> getTrackFileResources() { List<IMFTrackFileResourceType> trackFileResources = new ArrayList<>(); Iterator iterator = this.getVirtualTrackMap().entrySet().iterator(); while (iterator != null && iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); if (virtualTrack.getResourceList().size() != 0 && virtualTrack.getResourceList().get(0) instanceof IMFTrackFileResourceType) { trackFileResources.addAll(IMFEssenceComponentVirtualTrack.class.cast(virtualTrack).getTrackFileResourceList()); } } return Collections.unmodifiableList(trackFileResources); } /** * Getter for the essence VirtualTracks in this Composition * * @return a list of essence virtual tracks that are a part of this composition or an empty list if there are none * track */ @Nullable public List<IMFEssenceComponentVirtualTrack> getEssenceVirtualTracks() { List<IMFEssenceComponentVirtualTrack> essenceVirtualTracks = new ArrayList<>(); Iterator iterator = this.getVirtualTrackMap().entrySet().iterator(); while (iterator != null && iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); if (virtualTrack.getResourceList().size() != 0 && virtualTrack.getResourceList().get(0) instanceof IMFTrackFileResourceType) { essenceVirtualTracks.add(IMFEssenceComponentVirtualTrack.class.cast(virtualTrack)); } } return Collections.unmodifiableList(essenceVirtualTracks); } /** * Getter for the video VirtualTrack in this Composition * * @return the video virtual track that is a part of this composition or null if there is not video virtual track */ @Nullable public IMFEssenceComponentVirtualTrack getVideoVirtualTrack() { Iterator iterator = this.virtualTrackMap.entrySet().iterator(); while (iterator != null && iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence)) { return IMFEssenceComponentVirtualTrack.class.cast(virtualTrack); } } return null; } /** * Getter for the audio VirtualTracks in this Composition * * @return a list of audio virtual tracks that are a part of this composition or an empty list if there are none */ public List<IMFEssenceComponentVirtualTrack> getAudioVirtualTracks() { List<IMFEssenceComponentVirtualTrack> audioVirtualTracks = new ArrayList<>(); Iterator iterator = this.getVirtualTrackMap().entrySet().iterator(); while (iterator != null && iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)) { audioVirtualTracks.add(IMFEssenceComponentVirtualTrack.class.cast(virtualTrack)); } } return Collections.unmodifiableList(audioVirtualTracks); } /** * Getter for the marker VirtualTrack in this Composition * * @return the marker virtual track that is a part of this composition or null if there is no marker virtual track */ @Nullable public IMFMarkerVirtualTrack getMarkerVirtualTrack() { Iterator iterator = this.virtualTrackMap.entrySet().iterator(); while (iterator != null && iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MarkerSequence)) { return IMFMarkerVirtualTrack.class.cast(virtualTrack); } } return null; } /** * Getter for the errors in Composition * * @return List of errors in Composition. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } public static List<ErrorLogger.ErrorObject> validateCompositionPlaylistSchema(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException, SAXException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); IMFCompositionPlaylistType.getCompositionPlayListType(resourceByteRangeProvider, imfErrorLogger); return imfErrorLogger.getErrors(); } /** * A utility method to retrieve the VirtualTracks within a Composition. * * @return A list of VirtualTracks in the Composition. */ @Nonnull public List<? extends Composition.VirtualTrack> getVirtualTracks() { Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap = this.getVirtualTrackMap(); return new ArrayList<>(virtualTrackMap.values()); } /** * A utility method to retrieve the EssenceDescriptors within a Composition. * * @return A list of EssenceDescriptors in the Composition. */ @Nonnull public List<DOMNodeObjectModel> getEssenceDescriptors() { Map<UUID, DOMNodeObjectModel> essenceDescriptorMap = this.getEssenceDescriptorListMap(); return new ArrayList<>(essenceDescriptorMap.values()); } /** * A utility method to retrieve the EssenceDescriptors within a Composition based on the name. * * @param descriptorName EssenceDescriptor name * @return A list of DOMNodeObjectModels representing EssenceDescriptors with given name. */ public List<DOMNodeObjectModel> getEssenceDescriptors(String descriptorName) { return this.getEssenceDescriptors() .stream().filter(e -> e.getLocalName().equals(descriptorName)) .collect(Collectors.toList()); } /** * A utility method to retrieve the EssenceDescriptor within a Composition for a Resource with given track file ID. * * @param trackFileId the track file id of the resource * @return the DOMNodeObjectModel representing the EssenceDescriptor */ public DOMNodeObjectModel getEssenceDescriptor(UUID trackFileId) { IMFTrackFileResourceType imfTrackFileResourceType = this.getTrackFileResources() .stream() .filter(e -> UUIDHelper.fromUUIDAsURNStringToUUID(e.getTrackFileId()).equals(trackFileId)) .findFirst() .get(); return this.getEssenceDescriptorListMap().get(UUIDHelper.fromUUIDAsURNStringToUUID(imfTrackFileResourceType.getSourceEncoding())); } /** * A utility method to retrieve the UUIDs of the Track files referenced by a Virtual track within a Composition. * * @param virtualTrack - object model of an IMF virtual track {@link Composition.VirtualTrack} * @return A list of TrackFileResourceType objects corresponding to the virtual track in the Composition. */ @Nonnull public static List<ResourceIdTuple> getVirtualTrackResourceIDs(@Nonnull Composition.VirtualTrack virtualTrack) { List<ResourceIdTuple> virtualTrackResourceIDs = new ArrayList<>(); List<? extends IMFBaseResourceType> resourceList = virtualTrack.getResourceList(); if (resourceList != null && resourceList.size() > 0 && virtualTrack.getResourceList().get(0) instanceof IMFTrackFileResourceType) { for (IMFBaseResourceType baseResource : resourceList) { IMFTrackFileResourceType trackFileResource = IMFTrackFileResourceType.class.cast(baseResource); virtualTrackResourceIDs.add(new ResourceIdTuple(UUIDHelper.fromUUIDAsURNStringToUUID(trackFileResource.getTrackFileId()) , UUIDHelper.fromUUIDAsURNStringToUUID(trackFileResource.getSourceEncoding()))); } } return Collections.unmodifiableList(virtualTrackResourceIDs); } /** * This class is a representation of a Resource SourceEncoding element and trackFileId tuple. */ public static final class ResourceIdTuple { private final UUID trackFileId; private final UUID sourceEncoding; private ResourceIdTuple(UUID trackFileId, UUID sourceEncoding) { this.trackFileId = trackFileId; this.sourceEncoding = sourceEncoding; } /** * A getter for the trackFileId referenced by the resource corresponding to this ResourceIdTuple * * @return the trackFileId associated with this ResourceIdTuple */ public UUID getTrackFileId() { return this.trackFileId; } /** * A getter for the source encoding element referenced by the resource corresponding to this ResourceIdTuple * * @return the source encoding element associated with this ResourceIdTuple */ public UUID getSourceEncoding() { return this.sourceEncoding; } } /** * A utility method that will analyze the EssenceDescriptorList in a Composition and construct a HashMap mapping * a UUID to a EssenceDescriptor. * * @param ignoreSet - Set with names of properties to ignore * @return a HashMap mapping the UUID to its corresponding EssenceDescriptor in the Composition */ Map<UUID, DOMNodeObjectModel> getEssenceDescriptorListMap(Set<String> ignoreSet) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Map<UUID, DOMNodeObjectModel> essenceDescriptorMap = new HashMap<>(); if (compositionPlaylistType.getEssenceDescriptorList() != null) { List<IMFEssenceDescriptorBaseType> essenceDescriptors = compositionPlaylistType.getEssenceDescriptorList(); for (IMFEssenceDescriptorBaseType essenceDescriptorBaseType : essenceDescriptors) { try { UUID uuid = essenceDescriptorBaseType.getId(); DOMNodeObjectModel domNodeObjectModel = null; for (Object object : essenceDescriptorBaseType.getAny()) { domNodeObjectModel = new DOMNodeObjectModel((Node) object); if(domNodeObjectModel != null && ignoreSet.size() != 0) { domNodeObjectModel = DOMNodeObjectModel.createDOMNodeObjectModelIgnoreSet(domNodeObjectModel, ignoreSet); } } if (domNodeObjectModel != null) { essenceDescriptorMap.put(uuid, domNodeObjectModel); } } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } } if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Creating essenceDescriptorMap failed", imfErrorLogger); } return Collections.unmodifiableMap(essenceDescriptorMap); } /** * A utility method that will analyze the EssenceDescriptorList in a Composition and construct a HashMap mapping * a UUID to a EssenceDescriptor. * * @return a HashMap mapping the UUID to its corresponding EssenceDescriptor in the Composition */ Map<UUID, DOMNodeObjectModel> getEssenceDescriptorListMap() { return getEssenceDescriptorListMap(new HashSet<>()); } public Map<Set<DOMNodeObjectModel>, ? extends Composition.VirtualTrack> getAudioVirtualTracksMap() { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<? extends Composition.VirtualTrack> audioVirtualTracks = this.getAudioVirtualTracks(); Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap = this.getEssenceDescriptorListMap(); Map<Set<DOMNodeObjectModel>, Composition.VirtualTrack> audioVirtualTrackMap = new HashMap<>(); for (Composition.VirtualTrack audioVirtualTrack : audioVirtualTracks) { Set<DOMNodeObjectModel> set = new HashSet<>(); List<? extends IMFBaseResourceType> resources = audioVirtualTrack.getResourceList(); for (IMFBaseResourceType resource : resources) { IMFTrackFileResourceType trackFileResource = IMFTrackFileResourceType.class.cast(resource); try { set.add(essenceDescriptorListMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(trackFileResource.getSourceEncoding())));//Fetch and add the EssenceDescriptor referenced by the resource via the SourceEncoding element to the ED set. } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } audioVirtualTrackMap.put(set, audioVirtualTrack); } if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Creating Audio Virtual track map failed", imfErrorLogger); } return Collections.unmodifiableMap(audioVirtualTrackMap); } /** * This method can be used to determine if a Composition is conformant. Conformance checks * perform deeper inspection of the Composition and the EssenceDescriptors corresponding to the * resources referenced by the Composition. * * @param headerPartitionTuples list of HeaderPartitionTuples corresponding to the IMF essences referenced in the Composition * @param conformAllVirtualTracksInCpl a boolean that turns on/off conforming all the VirtualTracks in the Composition * @return boolean to indicate of the Composition is conformant or not * @throws IOException - any I/O related error is exposed through an IOException. */ public List<ErrorLogger.ErrorObject> conformVirtualTracksInComposition(List<Composition.HeaderPartitionTuple> headerPartitionTuples, boolean conformAllVirtualTracksInCpl) throws IOException { /* * The algorithm for conformance checking a Composition (CPL) would be * 1) Verify that every EssenceDescriptor element in the EssenceDescriptor list (EDL) is referenced through its id element if conformAllVirtualTracks is enabled * by at least one TrackFileResource within the Virtual tracks in the Composition (see section 6.1.10 of SMPTE st2067-3:2-13). * 2) Verify that all track file resources within a virtual track have a corresponding essence descriptor in the essence descriptor list. * 3) Verify that the EssenceDescriptors in the EssenceDescriptorList element in the Composition are present in * the physical essence files referenced by the resources of a virtual track and are equal. */ /*The following check simultaneously verifies 1) and 2) from above.*/ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Set<UUID> resourceEssenceDescriptorIDsSet = getResourceEssenceDescriptorIdsSet(); Set<UUID> cplEssenceDescriptorIDsSet = getEssenceDescriptorIdsSet(); Iterator cplEssenceDescriptorIDs = cplEssenceDescriptorIDsSet.iterator(); /** * The following checks that at least one of the Virtual Tracks references an EssenceDescriptor in the EDL. This * check should be performed only when we need to conform all the Virtual Tracks in the CPL. */ if (conformAllVirtualTracksInCpl) { while (cplEssenceDescriptorIDs.hasNext()) { UUID cplEssenceDescriptorUUID = (UUID) cplEssenceDescriptorIDs.next(); if (!resourceEssenceDescriptorIDsSet.contains(cplEssenceDescriptorUUID)) { //Section 6.1.10.1 st2067-3:2013 imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptorID %s in the CPL " + "EssenceDescriptorList is not referenced by any resource in any of the Virtual tracks in the CPL, this is invalid.", cplEssenceDescriptorUUID.toString())); } } } if (imfErrorLogger.hasFatalErrors()) { return imfErrorLogger.getErrors(); } Map essenceDescriptorMap = null; Map resourceEssenceDescriptorMap = null; /*The following check verifies 3) from above.*/ try { essenceDescriptorMap = this.getEssenceDescriptorListMap(); } catch(IMFException e) { this.imfErrorLogger.addAllErrors(e.getErrors()); } try { resourceEssenceDescriptorMap = this.getResourcesEssenceDescriptorsMap(headerPartitionTuples); } catch(IMFException e) { this.imfErrorLogger.addAllErrors(e.getErrors()); } if( essenceDescriptorMap == null || resourceEssenceDescriptorMap == null || imfErrorLogger.hasFatalErrors()) { return imfErrorLogger.getErrors(); } imfErrorLogger.addAllErrors(conformEssenceDescriptors(resourceEssenceDescriptorMap, essenceDescriptorMap)); return imfErrorLogger.getErrors(); } private Set<UUID> getEssenceDescriptorIdsSet() { HashSet<UUID> essenceDescriptorIdsSet = new LinkedHashSet<>(); if (compositionPlaylistType.getEssenceDescriptorList() != null) { List<IMFEssenceDescriptorBaseType> essenceDescriptorList = compositionPlaylistType.getEssenceDescriptorList(); for (IMFEssenceDescriptorBaseType essenceDescriptorBaseType : essenceDescriptorList) { UUID sourceEncodingElement = essenceDescriptorBaseType.getId(); /*Construct a set of SourceEncodingElements/IDs corresponding to every EssenceDescriptorBaseType in the EssenceDescriptorList*/ essenceDescriptorIdsSet.add(sourceEncodingElement); } } return essenceDescriptorIdsSet; } private Set<UUID> getResourceEssenceDescriptorIdsSet() { List<Composition.VirtualTrack> virtualTracks = new ArrayList<>(this.getVirtualTrackMap().values()); LinkedHashSet<UUID> resourceSourceEncodingElementsSet = new LinkedHashSet<>(); for (Composition.VirtualTrack virtualTrack : virtualTracks) { List<AbstractApplicationComposition.ResourceIdTuple> resourceIdTuples = this.getVirtualTrackResourceIDs(virtualTrack); for (AbstractApplicationComposition.ResourceIdTuple resourceIdTuple : resourceIdTuples) { /*Construct a set of SourceEncodingElements corresponding to every TrackFileResource of this VirtualTrack*/ resourceSourceEncodingElementsSet.add(resourceIdTuple.getSourceEncoding()); } } return resourceSourceEncodingElementsSet; } public static List<AbstractApplicationComposition.ResourceIdTuple> getResourceIdTuples(List<? extends Composition.VirtualTrack> virtualTracks) { List<AbstractApplicationComposition.ResourceIdTuple> resourceIdTupleList = new ArrayList<>(); for (Composition.VirtualTrack virtualTrack : virtualTracks) { resourceIdTupleList.addAll(getVirtualTrackResourceIDs(virtualTrack)); } return resourceIdTupleList; } private Map<UUID, List<DOMNodeObjectModel>> getResourcesEssenceDescriptorsMap(List<Composition .HeaderPartitionTuple> headerPartitionTuples) throws IOException { int previousNumberOfErrors = imfErrorLogger.getErrors().size(); Map<UUID, List<DOMNodeObjectModel>> resourcesEssenceDescriptorMap = new LinkedHashMap<>(); /*Create a Map of FilePackage UUID which should be equal to the TrackFileId of the resource in the Composition if the asset is referenced and the HeaderPartitionTuple, Map<UUID, HeaderPartitionTuple>*/ Map<UUID, Composition.HeaderPartitionTuple> resourceUUIDHeaderPartitionMap = new HashMap<>(); for (Composition.HeaderPartitionTuple headerPartitionTuple : headerPartitionTuples) { //validate header partition try { MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartitionTuple.getHeaderPartition(), imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); Preface preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); resourceUUIDHeaderPartitionMap.put(packageUUID, headerPartitionTuple); } catch (IMFException | MXFException e){ Preface preface = headerPartitionTuple.getHeaderPartition().getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("IMFTrackFile with ID %s has fatal errors", packageUUID.toString()))); if(e instanceof IMFException){ IMFException imfException = (IMFException)e; imfErrorLogger.addAllErrors(imfException.getErrors()); } else if(e instanceof MXFException){ MXFException mxfException = (MXFException)e; imfErrorLogger.addAllErrors(mxfException.getErrors()); } } } if(imfErrorLogger.hasFatalErrors(previousNumberOfErrors, imfErrorLogger.getNumberOfErrors())){ throw new IMFException(String.format("Fatal errors were detected in the IMFTrackFiles"), imfErrorLogger); } List<Composition.VirtualTrack> virtualTracks = new ArrayList<>(this.getVirtualTrackMap().values()); /*Go through all the Virtual Tracks in the Composition and construct a map of Resource Source Encoding Element and a list of DOM nodes representing every EssenceDescriptor in the HeaderPartition corresponding to that Resource*/ for (Composition.VirtualTrack virtualTrack : virtualTracks) { List<AbstractApplicationComposition.ResourceIdTuple> resourceIdTuples = this.getVirtualTrackResourceIDs(virtualTrack);/*Retrieve a list of ResourceIDTuples corresponding to this virtual track*/ for (AbstractApplicationComposition.ResourceIdTuple resourceIdTuple : resourceIdTuples) { try { Composition.HeaderPartitionTuple headerPartitionTuple = resourceUUIDHeaderPartitionMap.get(resourceIdTuple.getTrackFileId()); if (headerPartitionTuple != null) { /*Create a DOM Node representation of the EssenceDescriptors present in this header partition corresponding to an IMFTrackFile*/ List<Node> essenceDescriptorDOMNodes = getEssenceDescriptorDOMNodes(headerPartitionTuple); List<DOMNodeObjectModel> domNodeObjectModels = new ArrayList<>(); for (Node node : essenceDescriptorDOMNodes) { try { domNodeObjectModels.add(new DOMNodeObjectModel(node)); } catch( IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } resourcesEssenceDescriptorMap.put(resourceIdTuple.getSourceEncoding(), domNodeObjectModels); } } catch( IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } } if( imfErrorLogger.hasFatalErrors(previousNumberOfErrors, imfErrorLogger.getNumberOfErrors())) { throw new IMFException("Failed to get Essence Descriptor for a resource", this.imfErrorLogger); } if (resourcesEssenceDescriptorMap.entrySet().size() == 0) { String message = "Composition does not refer to a single IMFEssence represented by the HeaderPartitions " + "that were passed in."; this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, this.imfErrorLogger); } return Collections.unmodifiableMap(resourcesEssenceDescriptorMap); } private List<Node> getEssenceDescriptorDOMNodes(Composition.HeaderPartitionTuple headerPartitionTuple) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<InterchangeObject.InterchangeObjectBO> essenceDescriptors = headerPartitionTuple.getHeaderPartition().getEssenceDescriptors(); List<Node> essenceDescriptorNodes = new ArrayList<>(); for (InterchangeObject.InterchangeObjectBO essenceDescriptor : essenceDescriptors) { try { KLVPacket.Header essenceDescriptorHeader = essenceDescriptor.getHeader(); List<KLVPacket.Header> subDescriptorHeaders = this.getSubDescriptorKLVHeader(headerPartitionTuple.getHeaderPartition(), essenceDescriptor); /*Create a dom*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); DocumentFragment documentFragment = this.getEssenceDescriptorAsDocumentFragment(document, headerPartitionTuple, essenceDescriptorHeader, subDescriptorHeaders); Node node = documentFragment.getFirstChild(); essenceDescriptorNodes.add(node); } catch (ParserConfigurationException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.INTERNAL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, e.getMessage()); } } if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Failed to get Essence Descriptor for a resource", imfErrorLogger); } return essenceDescriptorNodes; } private List<KLVPacket.Header> getSubDescriptorKLVHeader(HeaderPartition headerPartition, InterchangeObject.InterchangeObjectBO essenceDescriptor) { List<KLVPacket.Header> subDescriptorHeaders = new ArrayList<>(); List<InterchangeObject.InterchangeObjectBO> subDescriptors = headerPartition.getSubDescriptors(essenceDescriptor); for (InterchangeObject.InterchangeObjectBO subDescriptorBO : subDescriptors) { if (subDescriptorBO != null) { subDescriptorHeaders.add(subDescriptorBO.getHeader()); } } return Collections.unmodifiableList(subDescriptorHeaders); } private DocumentFragment getEssenceDescriptorAsDocumentFragment(Document document, Composition.HeaderPartitionTuple headerPartitionTuple, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header> subDescriptors) throws MXFException, IOException { document.setXmlStandalone(true); PrimerPack primerPack = headerPartitionTuple.getHeaderPartition().getPrimerPack(); ResourceByteRangeProvider resourceByteRangeProvider = headerPartitionTuple.getResourceByteRangeProvider(); RegXMLLibHelper regXMLLibHelper = new RegXMLLibHelper(primerPack.getHeader(), getByteProvider(resourceByteRangeProvider, primerPack.getHeader())); Triplet essenceDescriptorTriplet = regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor, getByteProvider(resourceByteRangeProvider, essenceDescriptor)); //DocumentFragment documentFragment = this.regXMLLibHelper.getDocumentFragment(essenceDescriptorTriplet, document); /*Get the Triplets corresponding to the SubDescriptors*/ List<Triplet> subDescriptorTriplets = new ArrayList<>(); for (KLVPacket.Header subDescriptorHeader : subDescriptors) { subDescriptorTriplets.add(regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, this.getByteProvider(resourceByteRangeProvider, subDescriptorHeader))); } return regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, this.imfErrorLogger); } private ByteProvider getByteProvider(ResourceByteRangeProvider resourceByteRangeProvider, KLVPacket.Header header) throws IOException { byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(header.getByteOffset(), header.getByteOffset() + header.getKLSize() + header.getVSize()); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); return byteProvider; } private List<IMFErrorLogger.ErrorObject> conformEssenceDescriptors(Map<UUID, List<DOMNodeObjectModel>> essenceDescriptorsMap, Map<UUID, DOMNodeObjectModel> eDLMap) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); /** * An exhaustive compare of the eDLMap and essenceDescriptorsMap is required to ensure that the essence descriptors * in the EssenceDescriptorList and the EssenceDescriptors in the physical essence files corresponding to the * same source encoding element as indicated in the TrackFileResource and EDL are a good match. */ /** * The Maps passed in have the DOMObjectModel for every EssenceDescriptor in the EssenceDescriptorList in the CPL and * the essence descriptor in each of the essences referenced from every track file resource within each virtual track. */ /** * The following check ensures that we do not have a Track Resource that does not have a corresponding EssenceDescriptor element in the CPL's EDL */ Iterator<Map.Entry<UUID, List<DOMNodeObjectModel>>> essenceDescriptorsMapIterator = essenceDescriptorsMap.entrySet().iterator(); while (essenceDescriptorsMapIterator.hasNext()) { UUID sourceEncodingElement = essenceDescriptorsMapIterator.next().getKey(); if (!eDLMap.keySet().contains(sourceEncodingElement)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with Source Encoding " + "Element %s in a track does not have a corresponding entry in the CPL's EDL.", sourceEncodingElement.toString())); } } Set<String> ignoreSet = new HashSet<String>(); //ignoreSet.add("InstanceUID"); //ignoreSet.add("InstanceID"); //ignoreSet.add("EssenceLength"); //ignoreSet.add("AlternativeCenterCuts"); //ignoreSet.add("GroupOfSoundfieldGroupsLinkID"); // PHDRMetadataTrackSubDescriptor is not present in SMPTE registries and cannot be serialized ignoreSet.add("PHDRMetadataTrackSubDescriptor"); /** * The following check ensures that we have atleast one EssenceDescriptor in a TrackFile that equals the corresponding EssenceDescriptor element in the CPL's EDL */ Iterator<Map.Entry<UUID, List<DOMNodeObjectModel>>> iterator = essenceDescriptorsMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<UUID, List<DOMNodeObjectModel>> entry = (Map.Entry<UUID, List<DOMNodeObjectModel>>) iterator.next(); List<DOMNodeObjectModel> domNodeObjectModels = entry.getValue(); DOMNodeObjectModel referenceDOMNodeObjectModel = eDLMap.get(entry.getKey()); if (referenceDOMNodeObjectModel == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with Source Encoding " + "Element %s in a track does not have a corresponding entry in the CPL's Essence Descriptor List.", entry.getKey().toString())); } else { referenceDOMNodeObjectModel = DOMNodeObjectModel.createDOMNodeObjectModelIgnoreSet(eDLMap.get(entry.getKey()), ignoreSet); boolean intermediateResult = false; List<DOMNodeObjectModel> domNodeObjectModelsIgnoreSet = new ArrayList<>(); for (DOMNodeObjectModel domNodeObjectModel : domNodeObjectModels) { domNodeObjectModel = DOMNodeObjectModel.createDOMNodeObjectModelIgnoreSet(domNodeObjectModel, ignoreSet); domNodeObjectModelsIgnoreSet.add(domNodeObjectModel); intermediateResult |= referenceDOMNodeObjectModel.equals(domNodeObjectModel); } if (!intermediateResult) { DOMNodeObjectModel matchingDOMNodeObjectModel = DOMNodeObjectModel.getMatchingDOMNodeObjectModel(referenceDOMNodeObjectModel, domNodeObjectModelsIgnoreSet); imfErrorLogger.addAllErrors(DOMNodeObjectModel.getNamespaceURIMismatchErrors(referenceDOMNodeObjectModel, matchingDOMNodeObjectModel)); String domNodeName = referenceDOMNodeObjectModel.getLocalName(); List<DOMNodeObjectModel> domNodeObjectModelList = domNodeObjectModelsIgnoreSet.stream().filter( e -> e.getLocalName().equals(domNodeName)).collect(Collectors.toList()); if(domNodeObjectModelList.size() != 0) { DOMNodeObjectModel diffCPLEssenceDescriptor = referenceDOMNodeObjectModel.removeNodes(domNodeObjectModelList.get(0)); DOMNodeObjectModel diffTrackFileEssenceDescriptor = domNodeObjectModelList.get(0).removeNodes(referenceDOMNodeObjectModel); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with Id %s in the CPL's " + "EssenceDescriptorList doesn't match any EssenceDescriptors within the IMFTrackFile resource that references it, " + "%n%n EssenceDescriptor in CPL EssenceDescriptorList with mismatching fields is as follows %n%s, %n%nEssenceDescriptor found in the " + "TrackFile resource with mismatching fields is as follows %n%s%n%n", entry.getKey().toString(), diffCPLEssenceDescriptor.toString(), diffTrackFileEssenceDescriptor.toString())); } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with Id %s in the CPL's " + "EssenceDescriptorList doesn't match any EssenceDescriptors within the IMFTrackFile resource that references it, " + "%n%n EssenceDescriptor in CPL EssenceDescriptorList is as follows %n%s, %n%nEssenceDescriptors found in the TrackFile resource %n%s%n%n", entry.getKey().toString(), referenceDOMNodeObjectModel.toString(), Utilities.serializeObjectCollectionToString(domNodeObjectModelsIgnoreSet))); } } } } return imfErrorLogger.getErrors(); } public @Nullable CompositionImageEssenceDescriptorModel getCompositionImageEssenceDescriptorModel() { CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel = null; DOMNodeObjectModel imageEssencedescriptorDOMNode = this.getEssenceDescriptor( this.getVideoVirtualTrack().getTrackResourceIds().iterator().next()); if (imageEssencedescriptorDOMNode != null) { UUID imageEssenceDescriptorID = this.getEssenceDescriptorListMap().entrySet().stream().filter(e -> e.getValue().equals(imageEssencedescriptorDOMNode)).map(e -> e.getKey()).findFirst() .get(); imageEssenceDescriptorModel = new CompositionImageEssenceDescriptorModel(imageEssenceDescriptorID, imageEssencedescriptorDOMNode, regXMLLibDictionary); } return imageEssenceDescriptorModel; } private Map<UUID, List<Node>> createEssenceDescriptorDomNodeMap() { final Map<UUID, List<Node>> essenceDescriptorDomNodeMap = new HashMap<>(); if (compositionPlaylistType.getEssenceDescriptorList() != null) { Map<UUID, UUID> essenceDescriptorIdToTrackFileIdMap = new HashMap<>(); for(ResourceIdTuple resourceIdTuple : getResourceIdTuples(this.getVirtualTracks())) { essenceDescriptorIdToTrackFileIdMap.put(resourceIdTuple.getSourceEncoding(), resourceIdTuple.getTrackFileId()); } for(IMFEssenceDescriptorBaseType imfEssenceDescriptorBaseType : compositionPlaylistType.getEssenceDescriptorList()) { if(essenceDescriptorIdToTrackFileIdMap.containsKey(imfEssenceDescriptorBaseType.getId())) { essenceDescriptorDomNodeMap.put(essenceDescriptorIdToTrackFileIdMap.get(imfEssenceDescriptorBaseType.getId()), imfEssenceDescriptorBaseType.getAny().stream().map(e -> (Node) e).collect(Collectors.toList())); } } } return essenceDescriptorDomNodeMap; } public Map<UUID, List<Node>> getEssenceDescriptorDomNodeMap() { return this.essenceDescriptorDomNodeMap; } }
5,043
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFBaseResourceType.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import java.math.BigInteger; import java.util.List; /** * A class that models an IMF Base Resource. */ public abstract class IMFBaseResourceType { protected final String id; protected final Composition.EditRate editRate; protected final BigInteger intrinsicDuration; protected final BigInteger entryPoint; protected final BigInteger sourceDuration; protected final BigInteger repeatCount; protected final IMFErrorLoggerImpl imfErrorLogger; public IMFBaseResourceType(String id, List<Long> editRate, BigInteger intrinsicDuration, BigInteger entryPoint, BigInteger sourceDuration, BigInteger repeatCount) { imfErrorLogger = new IMFErrorLoggerImpl(); this.id = id; Composition.EditRate rate = null; try { rate = new Composition.EditRate(editRate); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } this.editRate = rate; this.intrinsicDuration = intrinsicDuration; this.entryPoint = (entryPoint != null)? entryPoint: BigInteger.ZERO; this.sourceDuration = (sourceDuration != null) ? sourceDuration: this.intrinsicDuration.subtract(this.entryPoint); this.repeatCount = (repeatCount != null)? repeatCount: BigInteger.ONE; if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Failed to create IMFBaseResourceType", imfErrorLogger); } } /** * Getter for the Resource ID * @return a string representing the urn:uuid of the Resource */ public String getId(){ return this.id; } /** * Getter for the EditRate of the Resource * @return a Composition.EditRate object of the Resource */ public Composition.EditRate getEditRate(){ return this.editRate; } /** * Getter for the IntrinsicDuration of the Resource * @return a BigInteger representing the Resource's IntrinsicDuration */ public BigInteger getIntrinsicDuration(){ return this.intrinsicDuration; } /** * Getter for the EntryPoint of the Resource * @return a BigInteger representing the Resource's EntryPoint */ public BigInteger getEntryPoint(){ return this.entryPoint; } /** * Getter for the SourceDuration of the Resource * @return a BigInteger representing the Resource's SourceDuration */ public BigInteger getSourceDuration(){ return this.sourceDuration; } /** * Getter for the RepeatCount of the Resource * @return a BigInteger representing the Resource's RepeatCount */ public BigInteger getRepeatCount(){ return this.repeatCount; } /** * Getter for the Resource Duration * @return a Long integer representing this Resource's duration on the timeline * in units of the Resource Edit Rate */ public long getDuration(){ return this.getSourceDuration().longValue() * this.getRepeatCount().longValue(); } /** * A method to determine the equivalence of any two Base Resource. * @param other - the object to compare against * @return boolean indicating if the two Base Resources are equivalent/representing the same timeline */ public boolean equivalent(IMFBaseResourceType other) { if(other == null){ return false; } boolean result = true; //Compare the following fields of the base resources that have to be equal //for the 2 resources to be considered equivalent/representing the same timeline. result &= editRate.equals(other.getEditRate()); result &= entryPoint.equals(other.getEntryPoint()); result &= intrinsicDuration.equals(other.getIntrinsicDuration()); result &= sourceDuration.equals(other.getSourceDuration()); result &= repeatCount.equals(other.getRepeatCount()); return result; } }
5,044
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/Composition.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import javax.annotation.concurrent.Immutable; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; /** * This class represents a canonical model of the XML type 'CompositionPlaylistType' defined by SMPTE st2067-3, * A Composition object can be constructed from an XML file only if it satisfies all the constraints specified * in st2067-3 and st2067-2. This object model is intended to be agnostic of specific versions of the definitions of a * CompositionPlaylist(st2067-3) and its accompanying Core constraints(st2067-2). */ @Immutable public final class Composition { private static final Logger logger = LoggerFactory.getLogger(Composition.class); private Composition() { } /** * This class is an immutable implementation of a rational number described as a ratio of two longs and used to hold * non-integer frame rate values */ @Immutable public static final class EditRate { private final Long numerator; private final Long denominator; private final IMFErrorLogger imfErrorLogger; /** * Constructor for the rational frame rate number. * * @param numbers the input list of numbers. The first number in the list is treated as the numerator and the * second as * the denominator. Construction succeeds only if the list has exactly two numbers */ public EditRate(List<Long> numbers) { Long denominator = 1L; Long numerator = 1L; imfErrorLogger = new IMFErrorLoggerImpl(); if (numbers.size() != 2) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.NON_FATAL, String.format( "Input list is expected to contain 2 numbers representing numerator and denominator " + "respectively, found %d numbers in list %s", numbers.size(), Arrays.toString(numbers.toArray()))); } else if (numbers.get(0) == 0 || numbers.get(1) == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.NON_FATAL, String.format( "Input list is expected to contain 2 non-zero numbers representing numerator and denominator " + "of the EditRate respectively, found Numerator %d, Denominator %d", numbers.get(0), numbers.get(1))); } else { numerator = numbers.get(0); denominator = numbers.get(1); } if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Failed to create IMFBaseResourceType", imfErrorLogger); } this.numerator = numerator; this.denominator = denominator; } /** * Constructor for the rational frame rate number * @param numerator a long integer representing the numerator component of the EditRate * @param denominator a long integer representing the denominator component of the EditRate */ public EditRate(Long numerator, Long denominator){ this(new ArrayList<Long>(){{add(numerator); add(denominator);}}); } /** * Getter for the frame rate numerator * * @return a long value corresponding to the frame rate numerator */ public Long getNumerator() { return this.numerator; } /** * Getter for the frame rate denominator * * @return a long value corresponding to the frame rate denominator */ public Long getDenominator() { return this.denominator; } /** * A method that returns a string representation of a Composition object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("=================== EditRate =====================\n"); sb.append(String.format("numerator = %d, denominator = %d%n", this.numerator, this.denominator)); return sb.toString(); } /** * Overridden equals method. * * @param object the EditRate to be compared with. * @return boolean false if the object is null or is not an instance of the EditRate class. */ @Override public boolean equals(Object object) { if (object == null || !(object instanceof EditRate)) { return false; } EditRate other = (EditRate) object; return ((this.getNumerator().equals(other.getNumerator())) && (this.getDenominator().equals(other.getDenominator()))); } /** * A Java compliant implementation of the hashCode() method * * @return integer containing the hash code corresponding to this object */ @Override public int hashCode() { int hash = 1; hash = hash * 31 + this.numerator.hashCode(); /*Numerator can be used since it is non-null*/ hash = hash * 31 + this.denominator.hashCode();/*Another field that is indicated to be non-null*/ return hash; } } /** * This class enumerates various types of {@link org.smpte_ra.schemas._2067_3._2013.SequenceType Sequence} that are valid in * Composition document that is compliant with st2067-2:2013. Such types are mostly defined in Section 6.3 of st2067-2:2013 */ public static enum SequenceTypeEnum { MarkerSequence("MarkerSequence"), MainImageSequence("MainImageSequence"), MainAudioSequence("MainAudioSequence"), SubtitlesSequence("SubtitlesSequence"), HearingImpairedCaptionsSequence("HearingImpairedCaptionsSequence"), VisuallyImpairedTextSequence("VisuallyImpairedTextSequence"), CommentarySequence("CommentarySequence"), KaraokeSequence("KaraokeSequence"), ForcedNarrativeSequence("ForcedNarrativeSequence"), AncillaryDataSequence("AncillaryDataSequence"), IABSequence("IABSequence"), UnsupportedSequence("UnsupportedSequence"); private final String name; private SequenceTypeEnum(String name) { this.name = name; } /** * A getter for the SequenceTypeEnum given a string that represents the name of a SequenceTypeEnum * * @param name the string that should represent the SequenceTypeEnum * @return the SequenceTypeEnum value corresponding to the name that was passed */ public static SequenceTypeEnum getSequenceTypeEnum(String name) { switch (name) { case "MarkerSequence": return MarkerSequence; case "MainImageSequence": return MainImageSequence; case "MainAudioSequence": return MainAudioSequence; case "SubtitlesSequence": return SubtitlesSequence; case "HearingImpairedCaptionsSequence": return HearingImpairedCaptionsSequence; case "VisuallyImpairedTextSequence": return VisuallyImpairedTextSequence; case "CommentarySequence": return CommentarySequence; case "KaraokeSequence": return KaraokeSequence; case "ForcedNarrativeSequence": return ForcedNarrativeSequence; case "AncillaryDataSequence": return AncillaryDataSequence; case "IABSequence": return IABSequence; case "UnsupportedSequence": default: return UnsupportedSequence; } } /** * An override of the toString() method * * @return a string representing the SequenceTypeEnum */ @Override public String toString() { return this.name; } } /** * The class is an immutable implementation of the virtual track concept defined in Section 6.9.3 of st2067-3:2013. A * virtual track is characterized by its UUID, the type of sequence and a list of UUIDs of the * IMF track files that comprise it. */ @Immutable public abstract static class VirtualTrack { protected final UUID trackID; protected final SequenceTypeEnum sequenceTypeEnum; protected final List<? extends IMFBaseResourceType> resources; protected final Composition.EditRate compositionEditRate; /** * Constructor for a VirtualTrack object * * @param trackID the UUID associated with this VirtualTrack object * @param sequenceTypeEnum the type of the associated sequence * @param resources the resource list of the Virtual Track * @param compositionEditRate the edit rate of the composition */ public VirtualTrack(UUID trackID, SequenceTypeEnum sequenceTypeEnum, List<? extends IMFBaseResourceType> resources, Composition.EditRate compositionEditRate) { this.trackID = trackID; this.sequenceTypeEnum = sequenceTypeEnum; this.resources = resources; this.compositionEditRate = compositionEditRate; } /** * Getter for the sequence type associated with this VirtualTrack object * * @return the sequence type associated with this VirtualTrack object as an enum */ public SequenceTypeEnum getSequenceTypeEnum() { return this.sequenceTypeEnum; } /** * Getter for the UUID associated with this VirtualTrack object * * @return the UUID associated with the Virtual track */ public UUID getTrackID() { return this.trackID; } /** * Getter for the Resources of the Virtual Track * * @return an unmodifiable list of resources of the Virtual Track */ public List<? extends IMFBaseResourceType> getResourceList() { return Collections.unmodifiableList(this.resources); } /** * A method to return the duration of this VirtualTrack * @return a long integer representing the duration of this VirtualTrack in Track Edit Rate units */ public long getDurationInTrackEditRateUnits(){ long duration = 0L; for(IMFBaseResourceType imfBaseResourceType : this.resources){ // Only handle TrackFileResource sequences currently if (imfBaseResourceType instanceof IMFTrackFileResourceType) { duration += imfBaseResourceType.getSourceDuration().longValue() * imfBaseResourceType.getRepeatCount().longValue(); } } return duration; } /** * A method to return the duration of this VirtualTrack * @return a long integer representing the duration of this VirtualTrack in Composition Edit Rate units */ public long getDuration(){ long duration = getDurationInTrackEditRateUnits(); Composition.EditRate resourceEditRate = this.resources.get(0).getEditRate();//Resources of this virtual track should all have the same edit rate we enforce that check during IMFCoreConstraintsChecker.checkVirtualTracks() long durationInCompositionEditUnits = Math.round((double) duration * (((double)this.compositionEditRate.getNumerator()/this.compositionEditRate.getDenominator()) / ((double)resourceEditRate.getNumerator()/resourceEditRate.getDenominator()))); return durationInCompositionEditUnits; } /** * A method to determine the equivalence of any 2 virtual tracks. * * @param other - the object to compare against * @return boolean indicating if the 2 virtual tracks are equivalent or represent the same timeline */ public boolean equivalent(Composition.VirtualTrack other) { if (other == null || (!this.getSequenceTypeEnum().equals(other.getSequenceTypeEnum())) || (this.resources.size() == 0 || other.resources.size() == 0)) { return false; } List<? extends IMFBaseResourceType> otherResourceList = other.resources; boolean result = false; if(this instanceof IMFEssenceComponentVirtualTrack){ if(this.getDuration() != other.getDuration()){ return false; } IMFEssenceComponentVirtualTrack thisVirtualTrack = IMFEssenceComponentVirtualTrack.class.cast(this); IMFEssenceComponentVirtualTrack otherVirtualTrack = IMFEssenceComponentVirtualTrack.class.cast(other); List<IMFTrackFileResourceType> normalizedResourceList = this.normalizeResourceList(thisVirtualTrack.getTrackFileResourceList()); List<IMFTrackFileResourceType> normalizedOtherResourceList = this.normalizeResourceList(otherVirtualTrack.getTrackFileResourceList()); if(normalizedResourceList.size() != normalizedOtherResourceList.size()){ return false; } result = normalizedResourceList.get(0).equivalent(normalizedOtherResourceList.get(0)); for (int i = 1; i < normalizedResourceList.size(); i++) { IMFBaseResourceType thisResource = normalizedResourceList.get(i); IMFBaseResourceType otherResource = normalizedOtherResourceList.get(i); result &= thisResource.equivalent(otherResource); } } else{ result = this.resources.get(0).equivalent(otherResourceList.get(0)); for (int i = 1; i < this.resources.size(); i++) { IMFBaseResourceType thisResource = this.resources.get(i); IMFBaseResourceType otherResource = otherResourceList.get(i); result &= thisResource.equivalent(otherResource); } } return result; } private List<IMFTrackFileResourceType> normalizeResourceList(List<IMFTrackFileResourceType> resourceList){ List<IMFTrackFileResourceType> normalizedResourceList = new ArrayList<>(); IMFTrackFileResourceType prev = resourceList.get(0); for(int i=1; i< resourceList.size(); i++){ IMFTrackFileResourceType curr = IMFTrackFileResourceType.class.cast(resourceList.get(i)); if(curr.getTrackFileId().equals(prev.getTrackFileId()) && curr.getEditRate().equals(prev.getEditRate()) && curr.getEntryPoint().longValue() == (prev.getEntryPoint().longValue() + prev.getSourceDuration().longValue())){ //Candidate for normalization - We could create one resource representing the timelines of prev and curr List<Long> editRate = new ArrayList<>(); editRate.add(prev.getEditRate().getNumerator()); editRate.add(prev.getEditRate().getDenominator()); if(prev.getRepeatCount().longValue() > 1) { BigInteger newRepeatCount = new BigInteger(String.format("%d", prev.getRepeatCount().longValue() - 1L)); IMFTrackFileResourceType modifiedPrevTrackFileResourceType = new IMFTrackFileResourceType(prev.getId(), prev.getTrackFileId(), editRate, prev.getIntrinsicDuration(), prev.getEntryPoint(), prev.getSourceDuration(), newRepeatCount, prev.getSourceEncoding(), prev.getHash(), prev.getHashAlgorithm()); normalizedResourceList.add(modifiedPrevTrackFileResourceType); } BigInteger newSourceDuration = new BigInteger(String.format("%d", curr.getSourceDuration().longValue() + prev.getSourceDuration().longValue())); IMFTrackFileResourceType mergedTrackFileResourceType = new IMFTrackFileResourceType(prev.getId(), prev.getTrackFileId(), editRate, prev.getIntrinsicDuration(), prev.getEntryPoint(), newSourceDuration, new BigInteger("1"), prev.getSourceEncoding(), prev.getHash(), prev.getHashAlgorithm()); prev = mergedTrackFileResourceType; if(curr.getRepeatCount().longValue() > 1) { BigInteger newRepeatCount = new BigInteger(String.format("%d", curr.getRepeatCount().longValue() - 1L)); editRate = new ArrayList<>(); editRate.add(curr.getEditRate().getNumerator()); editRate.add(curr.getEditRate().getDenominator()); IMFTrackFileResourceType modifiedCurrTrackFileResourceType = new IMFTrackFileResourceType(curr.getId(), curr.getTrackFileId(), editRate, curr.getIntrinsicDuration(), curr.getEntryPoint(), curr.getSourceDuration(), newRepeatCount, curr.getSourceEncoding(), curr.getHash(), curr.getHashAlgorithm()); //We are replacing prev here so add the mergedTrackFileResourceType, modifiedCurrTrackFileResourceType will be added when we process the last resource in the list normalizedResourceList.add(prev); prev = modifiedCurrTrackFileResourceType; } } else{//prev and curr cannot be merged as they either point to different resources or do not represent continuous timeline normalizedResourceList.add(prev); prev = curr; } } normalizedResourceList.add(prev);//Add the track file resource pointed to by prev return Collections.unmodifiableList(normalizedResourceList); } } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <inputFilePath>%n", Composition.class.getName())); return sb.toString(); } public static void main(String args[]) throws IOException, SAXException, JAXBException { if (args.length != 1) { logger.error(usage()); throw new IllegalArgumentException("Invalid parameters"); } File inputFile = new File(args[0]); if(!inputFile.exists()){ logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject>errors = IMPValidator.validateCPL(payloadRecord); if(errors.size() > 0){ long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("CompositionPlaylist Document has %d errors and %d warnings", errors.size() - warningCount, warningCount)); for(ErrorLogger.ErrorObject errorObject : errors){ if(errorObject.getErrorLevel() != IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if(errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } } else{ logger.info("No errors were detected in the CompositionPlaylist Document."); } } /** * An object model for a HeaderPartition and access to the raw bytes corresponding to the HeaderPartition */ public static class HeaderPartitionTuple { private final HeaderPartition headerPartition; private final ResourceByteRangeProvider resourceByteRangeProvider; public HeaderPartitionTuple(HeaderPartition headerPartition, ResourceByteRangeProvider resourceByteRangeProvider){ this.headerPartition = headerPartition; this.resourceByteRangeProvider = resourceByteRangeProvider; } /** * A getter for the resourceByteRangeProvider object corresponding to this HeaderPartition to allow * access to the raw bytes * @return ResourceByteRangeProvider object corresponding to this HeaderPartition */ public ResourceByteRangeProvider getResourceByteRangeProvider(){ return this.resourceByteRangeProvider; } /** * A getter for the HeaderPartition object corresponding to a resource referenced from the Composition * @return HeaderPartition of a certain resource in the Composition */ public HeaderPartition getHeaderPartition(){ return this.headerPartition; } } }
5,045
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFSegmentType.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; /** * A class that models Segment structure of an IMF Composition Playlist. */ @Immutable final class IMFSegmentType { protected final String id; protected final List<IMFSequenceType> sequenceList; public IMFSegmentType(String id, List<IMFSequenceType> sequenceList){ this.id = id; this.sequenceList = Collections.unmodifiableList(sequenceList); } /** * Getter for the Segment ID * @return a string representing the urn:uuid of the segment */ public String getId(){ return this.id; } /** * Getter for the Sequence list * @return a list containing all the sequences of the Segment */ public List<IMFSequenceType> getSequenceList(){ return this.sequenceList; } }
5,046
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFCompositionPlaylistType.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; /** * A class that models an IMF Composition Playlist structure. */ @Immutable final class IMFCompositionPlaylistType { private final UUID id; private final Composition.EditRate editRate; private final String annotation; private final String issuer; private final String creator; private final String contentOriginator; private final String contentTitle; private final List<IMFSegmentType> segmentList; private final List<IMFEssenceDescriptorBaseType> essenceDescriptorList; private final IMFErrorLogger imfErrorLogger; private final String coreConstraintsSchema; private final Set<String> applicationIdSet; /** * @deprecated * This constructor is the legacy constructor, it uses a single String for the application id * but a CPL may declare that it conforms to multiple application ids. * The constructor using a Set should be preferred. */ @Deprecated public IMFCompositionPlaylistType(String id, List<Long> editRate, String annotation, String issuer, String creator, String contentOriginator, String contentTitle, List<IMFSegmentType> segmentList, List<IMFEssenceDescriptorBaseType> essenceDescriptorList, String coreConstraintsSchema, String applicationId) { this(id, editRate, annotation, issuer, creator, contentOriginator, contentTitle, segmentList, essenceDescriptorList, coreConstraintsSchema, (applicationId == null ? new HashSet<>() : new HashSet<String>(Arrays.asList(applicationId)))); } public IMFCompositionPlaylistType(String id, List<Long> editRate, String annotation, String issuer, String creator, String contentOriginator, String contentTitle, List<IMFSegmentType> segmentList, List<IMFEssenceDescriptorBaseType> essenceDescriptorList, String coreConstraintsSchema, @Nonnull Set<String> applicationIds) { this.id = UUIDHelper.fromUUIDAsURNStringToUUID(id); Composition.EditRate rate = null; imfErrorLogger = new IMFErrorLoggerImpl(); try { rate = new Composition.EditRate(editRate); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } this.editRate = rate; this.annotation = annotation; this.issuer = issuer; this.creator = creator; this.contentOriginator = contentOriginator; this.contentTitle = contentTitle; this.segmentList = Collections.unmodifiableList(segmentList); this.essenceDescriptorList = Collections.unmodifiableList(essenceDescriptorList); this.coreConstraintsSchema = coreConstraintsSchema; this.applicationIdSet = Collections.unmodifiableSet(applicationIds); if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("Failed to create IMFBaseResourceType", imfErrorLogger); } } private static final Set<String> supportedCPLSchemaURIs = Collections.unmodifiableSet(new HashSet<String>() {{ add("http://www.smpte-ra.org/schemas/2067-3/2013"); add("http://www.smpte-ra.org/schemas/2067-3/2016"); }}); @Nonnull private static final String getCompositionNamespaceURI(ResourceByteRangeProvider resourceByteRangeProvider, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { String result = ""; try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1);) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, exception.getMessage())); } @Override public void error(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, exception.getMessage())); } @Override public void fatalError(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, exception.getMessage())); } }); Document document = documentBuilder.parse(inputStream); //obtain root node NodeList nodeList = null; for (String cplNamespaceURI : supportedCPLSchemaURIs) { nodeList = document.getElementsByTagNameNS(cplNamespaceURI, "CompositionPlaylist"); if (nodeList != null && nodeList.getLength() == 1) { result = cplNamespaceURI; break; } } } catch (ParserConfigurationException | SAXException e) { String message = String.format("Error occurred while trying to determine the Composition Playlist " + "Namespace URI, XML document appears to be invalid. Error Message : %s", e.getMessage()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } if (result.isEmpty()) { String message = String.format("Please check the CPL document and namespace URI, currently we only " + "support the following schema URIs %s", Utilities.serializeObjectCollectionToString (supportedCPLSchemaURIs)); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } return result; } /** * A method that confirms if the inputStream corresponds to a Composition document instance. * * @param resourceByteRangeProvider corresponding to the Composition XML file. * @return a boolean indicating if the input file is a Composition document * @throws IOException - any I/O related error is exposed through an IOException */ public static boolean isCompositionPlaylist(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1);) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); //obtain root node NodeList nodeList = null; for (String cplNamespaceURI : supportedCPLSchemaURIs) { nodeList = document.getElementsByTagNameNS(cplNamespaceURI, "CompositionPlaylist"); if (nodeList != null && nodeList.getLength() == 1) { return true; } } } catch (ParserConfigurationException | SAXException e) { return false; } return false; } public static IMFCompositionPlaylistType getCompositionPlayListType(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException { // Determine which version of the CPL namespace is being used String cplNamespace = getCompositionNamespaceURI(resourceByteRangeProvider, imfErrorLogger); if (cplNamespace.equals("http://www.smpte-ra.org/schemas/2067-3/2013")) { org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType jaxbCpl = CompositionModel_st2067_2_2013.unmarshallCpl(resourceByteRangeProvider, imfErrorLogger); return CompositionModel_st2067_2_2013.getCompositionPlaylist(jaxbCpl, imfErrorLogger); } else if (cplNamespace.equals("http://www.smpte-ra.org/schemas/2067-3/2016")) { org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType jaxbCpl = CompositionModel_st2067_2_2016.unmarshallCpl(resourceByteRangeProvider, imfErrorLogger); return CompositionModel_st2067_2_2016.getCompositionPlaylist(jaxbCpl, imfErrorLogger); } else { String message = String.format("Please check the CPL document and namespace URI, currently we " + "only support the following schema URIs %s", supportedCPLSchemaURIs); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } } /** * Getter for the Composition Playlist ID * @return a string representing the urn:uuid of the Composition Playlist */ public UUID getId(){ return this.id; } /** * Getter for the EditRate of the Composition Playlist * @return a Composition.EditRate object of the Composition Playlist */ public Composition.EditRate getEditRate(){ return this.editRate; } /** * Getter for the Composition Playlist annotation * @return a string representing annotation of the Composition Playlist */ public String getAnnotation(){ return this.annotation; } /** * Getter for the Composition Playlist issuer * @return a string representing issuer of the Composition Playlist */ public String getIssuer(){ return this.issuer; } /** * Getter for the Composition Playlist creator * @return a string representing creator of the Composition Playlist */ public String getCreator(){ return this.creator; } /** * Getter for the Composition Playlist contentOriginator * @return a string representing contentOriginator of the Composition Playlist */ public String getContentOriginator(){ return this.contentOriginator; } /** * Getter for the Composition Playlist contentTitle * @return a string representing contentTitle of the Composition Playlist */ public String getContentTitle(){ return this.contentTitle; } /** * Getter for the SegmentList of the Composition Playlist * @return a string representing the SegmentList of the Composition Playlist */ public List<IMFSegmentType> getSegmentList(){ return this.segmentList; } /** * Getter for the EssenceDescriptorlist of the Composition Playlist * @return a string representing the EssenceDescriptorlist of the Composition Playlist */ public List<IMFEssenceDescriptorBaseType> getEssenceDescriptorList(){ return this.essenceDescriptorList; } /** * Getter for the CoreConstraints URI corresponding to this CompositionPlaylist * * @return the uri for the CoreConstraints schema for this CompositionPlaylist */ @Nonnull public String getCoreConstraintsSchema() { return this.coreConstraintsSchema; } /** * Getter for the ApplicationIdentification corresponding to this CompositionPlaylist * * @return a string representing ApplicationIdentification for this CompositionPlaylist * * @deprecated * A CPL may declare multiple Application identifiers, the getter that returns a Set should be used instead. */ @Deprecated public String getApplicationIdentification() { if (this.applicationIdSet.size() > 0) { return this.applicationIdSet.iterator().next(); } else { return ""; } } /** * Getter for the ApplicationIdentification Set corresponding to this CompositionPlaylist * * @return a set of all the strings representing ApplicationIdentification for this CompositionPlaylist */ public Set<String> getApplicationIdentificationSet() { return this.applicationIdSet; } }
5,047
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFMarkerType.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import javax.annotation.concurrent.Immutable; import java.math.BigInteger; /** * A class that models an IMF MarkerType. */ @Immutable public final class IMFMarkerType { private final String annotation; private final IMFMarkerType.Label label; private final BigInteger offset; public IMFMarkerType(String annotation, IMFMarkerType.Label label, BigInteger offset) { this.annotation = annotation; this.label = label; this.offset = offset; } /** * Getter for the Annotation of the Marker * @return a Annotation of the Marker */ public String getAnnotation(){ return this.annotation; } /** * Getter for the Label of the Marker * @return a Label of the Marker */ public IMFMarkerType.Label getLabel(){ return this.label; } /** * Getter for the Offset of the Marker * @return a BigInteger representing the Marker's Offset */ public BigInteger getOffset(){ return this.offset; } /** * A method to determine the equivalence of any two Markers. * @param other - the object to compare against * @return boolean indicating if the two Markers are equivalent/representing the same timeline */ public boolean equivalent(IMFMarkerType other) { if(other == null){ return false; } boolean result = true; result &= offset.equals(other.getOffset()); result &= label.equivalent(other.getLabel()); return result; } @Immutable public static final class Label { private final String value; private final String scope; public Label(String value, String scope) { this.value = value; this.scope = scope; } /** * Getter for the Value of the Label * * @return a String representing the Label value */ public String getValue() { return value; } /** * Getter for the Scope of the Label * * @return a String representing the Label Scope */ public String getScope() { return scope; } /** * A method to determine the equivalence of any two Labels. * * @param other - the object to compare against * @return boolean indicating if the two Labels are equivalent */ public boolean equivalent(Label other) { if (other == null) { return false; } boolean result = true; result &= value.equals(other.getValue()); result &= scope.equals(other.getScope()); return result; } } }
5,048
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/CompositionModel_st2067_2_2016.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.writerTools.CompositionPlaylistBuilder_2016; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.w3c.dom.Element; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * A class that models aspects of a Composition such as a VirtualTrack, TrackResources etc. compliant with the 2016 CompositionPlaylist specification st2067-3:2016. * Used for converting a specific JAXB class (org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType) into the canonical, version-independent, class IMFCompositionPlaylistType */ final class CompositionModel_st2067_2_2016 { //To prevent instantiation private CompositionModel_st2067_2_2016(){ } /** * Converts a CompositionPlaylist from a JAXB object, into a version-independent model * @param compositionPlaylistType - a CompositionPlaylist object model * @param imfErrorLogger - an object for logging errors * @return A canonical, version-independent, instance of IMFCompositionPlaylistType */ @Nonnull public static IMFCompositionPlaylistType getCompositionPlaylist (@Nonnull org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType compositionPlaylistType, @Nonnull IMFErrorLogger imfErrorLogger) { // Parse each Segment List<IMFSegmentType> segmentList = compositionPlaylistType.getSegmentList().getSegment().stream() .map(segment -> parseSegment(segment, compositionPlaylistType.getEditRate(), imfErrorLogger)) .collect(Collectors.toList()); // Parse the EssenceDescriptors, if present List<IMFEssenceDescriptorBaseType> essenceDescriptorList = Collections.emptyList(); if (compositionPlaylistType.getEssenceDescriptorList() != null) { essenceDescriptorList = compositionPlaylistType.getEssenceDescriptorList().getEssenceDescriptor().stream() .map(ed -> parseEssenceDescriptor(ed, imfErrorLogger)) .collect(Collectors.toList()); } // Parse the ApplicationIdentification values Set<String> applicationIDs = parseApplicationIds(compositionPlaylistType, imfErrorLogger); // Identify the Core Constraints version String coreConstraintsSchema = CoreConstraints.fromApplicationId(applicationIDs); if (coreConstraintsSchema == null) { // Get the namespaces of each Sequence being used Set<String> sequenceNamespaces = compositionPlaylistType.getSegmentList().getSegment().get(0) .getSequenceList().getAny().stream().filter(JAXBElement.class::isInstance) .map(je -> ((JAXBElement<?>) je).getName().getNamespaceURI()).collect(Collectors.toSet()); // Find the Core Constraints version, based on the namespaces of the Sequences coreConstraintsSchema = CoreConstraints.fromElementNamespaces(sequenceNamespaces); // If all else fails, assume the minimum version applicable to this CPL version if (coreConstraintsSchema == null) coreConstraintsSchema = CoreConstraints.NAMESPACE_IMF_2016; } return new IMFCompositionPlaylistType( compositionPlaylistType.getId(), compositionPlaylistType.getEditRate(), (compositionPlaylistType.getAnnotation() == null ? null : compositionPlaylistType.getAnnotation().getValue()), (compositionPlaylistType.getIssuer() == null ? null : compositionPlaylistType.getIssuer().getValue()), (compositionPlaylistType.getCreator() == null ? null : compositionPlaylistType.getCreator().getValue()), (compositionPlaylistType.getContentOriginator() == null ? null : compositionPlaylistType.getContentOriginator().getValue()), (compositionPlaylistType.getContentTitle() == null ? null : compositionPlaylistType.getContentTitle().getValue()), segmentList, essenceDescriptorList, coreConstraintsSchema, applicationIDs ); } @Nonnull static org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType unmarshallCpl(@Nonnull ResourceByteRangeProvider resourceByteRangeProvider, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1)) { // Validate the document against the CPL schemas, when unmarshalling Schema schema = ValidationSchema.INSTANCE; ValidationEventHandlerImpl validationEventHandlerImpl = new ValidationEventHandlerImpl(true); Unmarshaller unmarshaller = CompositionPlaylistType2016_Context.INSTANCE.createUnmarshaller(); unmarshaller.setEventHandler(validationEventHandlerImpl); unmarshaller.setSchema(schema); JAXBElement<org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType> jaxbCpl = unmarshaller.unmarshal(new StreamSource(inputStream), org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.class); // Report any schema validation errors that occurred during unmarshalling if (validationEventHandlerImpl.hasErrors()) { validationEventHandlerImpl.getErrors().stream() .map(e -> new ErrorLogger.ErrorObject( IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, e.getValidationEventSeverity(), "Line Number : " + e.getLineNumber().toString() + " - " + e.getErrorMessage())) .forEach(imfErrorLogger::addError); throw new IMFException(validationEventHandlerImpl.toString(), imfErrorLogger); } return jaxbCpl.getValue(); } catch(JAXBException e) { throw new IMFException("Error when unmarshalling org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType", e, imfErrorLogger); } } // Parse the list of ApplicationIdentification values @Nonnull private static Set<String> parseApplicationIds(@Nonnull org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType compositionPlaylistType, @Nonnull IMFErrorLogger imfErrorLogger) { if (compositionPlaylistType.getExtensionProperties() == null) return Collections.emptySet(); return compositionPlaylistType.getExtensionProperties().getAny().stream() .filter(JAXBElement.class::isInstance).map(JAXBElement.class::cast) .filter(extProp -> extProp.getName().getLocalPart().equals("ApplicationIdentification")).map(JAXBElement::getValue) .filter(List.class::isInstance).map(appIdList -> (List<?>) appIdList) .findAny().orElse(Collections.emptyList()).stream().map(Object::toString).collect(Collectors.toSet()); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2016.EssenceDescriptorBaseType // Into a canonical, version-independent, instance of IMFEssenceDescriptorBaseType @Nonnull private static IMFEssenceDescriptorBaseType parseEssenceDescriptor(@Nonnull org.smpte_ra.schemas._2067_3._2016.EssenceDescriptorBaseType essenceDescriptor, @Nonnull IMFErrorLogger imfErrorLogger) { return new IMFEssenceDescriptorBaseType(essenceDescriptor.getId(), essenceDescriptor.getAny()); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2016.SegmentType // Into a canonical, version-independent, instance of IMFSegmentType @Nonnull private static IMFSegmentType parseSegment(@Nonnull org.smpte_ra.schemas._2067_3._2016.SegmentType segment, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { List<IMFSequenceType> sequenceList = new ArrayList<IMFSequenceType>(); // Parse the Marker Sequence org.smpte_ra.schemas._2067_3._2016.SequenceType markerSequence = segment.getSequenceList().getMarkerSequence(); if (markerSequence != null) { sequenceList.add(parseMarkerSequence(markerSequence, cplEditRate, imfErrorLogger)); } /* Parse rest of the sequences */ for (Object object : segment.getSequenceList().getAny()) { // Ignore unrecognized Sequence types if(!(object instanceof JAXBElement)){ String details = ""; if(object instanceof Element) { Element element = Element.class.cast(object); details = "Tag: " + element.getTagName() + " URI: " + element.getNamespaceURI(); } imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.NON_FATAL, String.format("Unsupported sequence type or schema %s", details)); continue; } // Get the JAXB SequenceType object JAXBElement jaxbElement = (JAXBElement)(object); org.smpte_ra.schemas._2067_3._2016.SequenceType sequence = (org.smpte_ra.schemas._2067_3._2016.SequenceType) jaxbElement.getValue(); // Determine the type of Sequence being parsed Composition.SequenceTypeEnum sequenceType = Composition.SequenceTypeEnum.getSequenceTypeEnum(jaxbElement.getName().getLocalPart()); // Parse the Sequence sequenceList.add(parseSequence(sequence, cplEditRate, sequenceType, imfErrorLogger)); } return new IMFSegmentType(segment.getId(), sequenceList); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2016.SequenceType // Into a canonical, version-independent, instance of IMFSequenceType @Nonnull private static IMFSequenceType parseMarkerSequence(@Nonnull org.smpte_ra.schemas._2067_3._2016.SequenceType markerSequence, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { List<IMFBaseResourceType> sequenceResources = new ArrayList<>(); for (org.smpte_ra.schemas._2067_3._2016.BaseResourceType resource : markerSequence.getResourceList().getResource()) { if (resource instanceof org.smpte_ra.schemas._2067_3._2016.MarkerResourceType) { try { IMFMarkerResourceType markerResource = parseMarkerResource( (org.smpte_ra.schemas._2067_3._2016.MarkerResourceType) resource, cplEditRate, imfErrorLogger); sequenceResources.add(markerResource); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, "Unsupported Resource type in Marker Sequence"); } } return new IMFSequenceType(markerSequence.getId(), markerSequence.getTrackId(), Composition.SequenceTypeEnum.MarkerSequence, sequenceResources); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2016.SequenceType // Into a canonical, version-independent, instance of IMFSequenceType @Nonnull private static IMFSequenceType parseSequence(@Nonnull org.smpte_ra.schemas._2067_3._2016.SequenceType sequence, @Nonnull List<Long> cplEditRate, Composition.SequenceTypeEnum sequenceType, @Nonnull IMFErrorLogger imfErrorLogger) { List<IMFBaseResourceType> sequenceResources = new ArrayList<>(); for (org.smpte_ra.schemas._2067_3._2016.BaseResourceType resource : sequence.getResourceList().getResource()) { if(resource instanceof org.smpte_ra.schemas._2067_3._2016.TrackFileResourceType) { try { IMFTrackFileResourceType trackFileResource = parseTrackFileResource( (org.smpte_ra.schemas._2067_3._2016.TrackFileResourceType) resource, cplEditRate, imfErrorLogger); sequenceResources.add(trackFileResource); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, "Unsupported Resource type"); } } return new IMFSequenceType(sequence.getId(), sequence.getTrackId(), sequenceType, sequenceResources); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2016.MarkerResourceType // Into a canonical, version-independent, instance of IMFMarkerResourceType @Nonnull private static IMFMarkerResourceType parseMarkerResource(@Nonnull org.smpte_ra.schemas._2067_3._2016.MarkerResourceType markerResource, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { // Parse each Marker within the MarkerResource List<IMFMarkerType> markerList = new ArrayList<IMFMarkerType>(); for (org.smpte_ra.schemas._2067_3._2016.MarkerType marker : markerResource.getMarker()) { markerList.add(new IMFMarkerType(marker.getAnnotation() == null ? null : marker .getAnnotation().getValue(), new IMFMarkerType.Label(marker.getLabel().getValue(), marker.getLabel().getScope()), marker.getOffset())); } return new IMFMarkerResourceType( markerResource.getId(), markerResource.getEditRate().size() != 0 ? markerResource.getEditRate() : cplEditRate, markerResource.getIntrinsicDuration(), markerResource.getEntryPoint(), markerResource.getSourceDuration(), markerResource.getRepeatCount(), markerList); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2016.TrackFileResourceType // Into a canonical, version-independent, instance of IMFTrackFileResourceType @Nonnull private static IMFTrackFileResourceType parseTrackFileResource(@Nonnull org.smpte_ra.schemas._2067_3._2016.TrackFileResourceType trackFileResource, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { return new IMFTrackFileResourceType( trackFileResource.getId(), trackFileResource.getTrackFileId(), trackFileResource.getEditRate().size() != 0 ? trackFileResource.getEditRate() : cplEditRate, trackFileResource.getIntrinsicDuration(), trackFileResource.getEntryPoint(), trackFileResource.getSourceDuration(), trackFileResource.getRepeatCount(), trackFileResource.getSourceEncoding(), trackFileResource.getHash(), trackFileResource.getHashAlgorithm() == null? CompositionPlaylistBuilder_2016.defaultHashAlgorithm : trackFileResource .getHashAlgorithm().getAlgorithm() ); } // Singleton to allow a JAXBContext configured for 2016 CPLs to be reused and lazy-loaded private static class CompositionPlaylistType2016_Context { static final JAXBContext INSTANCE = createJAXBContext(); private static JAXBContext createJAXBContext() { try { return JAXBContext.newInstance( org.smpte_ra.schemas._2067_3._2016.ObjectFactory.class,// 2016 2016 CPL org.smpte_ra.schemas._2067_2._2016.ObjectFactory.class, // 2016 Core constraints org.smpte_ra.ns._2067_2._2020.ObjectFactory.class, // 2020 Core constraints org.smpte_ra.ns._2067_201._2019.ObjectFactory.class); // IAB plugin } catch(JAXBException e) { throw new IMFException("Failed to create JAXBContext needed by CompositionPlaylistType (2016)", e); } } } // Singleton to allow the CPL validation Schema object to be reused and lazy-loaded private static class ValidationSchema { static final Schema INSTANCE = createValidationSchema(); private static Schema createValidationSchema() { // Load all XSD schemas required to validate a CompositionPlaylist document ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try (InputStream xsd_xmldsig_core = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"); InputStream xsd_dcmlTypes = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd"); InputStream xsd_cpl_2016 = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_3_2016/imf-cpl-20160411.xsd"); InputStream xsd_core_constraints_2016 = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2016/imf-core-constraints-20160411.xsd"); InputStream xsd_core_constraints_2020 = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2020/imf-core-constraints-2020.xsd") ) { // Build a schema from all of the XSD files provided SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); return schemaFactory.newSchema(new StreamSource[]{ new StreamSource(xsd_xmldsig_core), new StreamSource(xsd_dcmlTypes), new StreamSource(xsd_cpl_2016), new StreamSource(xsd_core_constraints_2016), new StreamSource(xsd_core_constraints_2020), }); } catch(IOException | SAXException e) { throw new IMFException("Unable to create CPL validation schema", e); } } } }
5,049
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/AudioContentKind.java
package com.netflix.imflibrary.st2067_2; /** * This enum lists all audio content kinds defined in the following draft specification: * "Interoperable Master Format –Specifying Audio Element and Content Kind in Application #2E Compositions" */ public enum AudioContentKind { PRM("Primary"), DXC("Dialog Composite"), MXC("Music Composite"), FXC("Effects Composite"), NAR("Narration"), DDXC("Dialog Composite (dubbed)"), MEC("Music and Effects Composite"), VO("Voice Over"), HI("Hearing Impaired"), VI("Visually Impaired"), DVS("Descriptive Video Service"), DCM("Director Commentary"), TCM("Technical Commentary"), WCM("Writer's Commentary"), MCM("Composer's Commentary"), CCM("Cast Commentary"), DXS("Dialog Split Track"), MXS("Music Split Track"), FXS("Effects Split Track"), SPRM("Simplified Primary"), OP("Optional Music and Effects"), SOP("Simplified Optional Music and Effects"), Unknown("Unknown"); String description; AudioContentKind(String description) { this.description = description; } /** * Getter for description for the audio content kind * @return a String describing the audio content kind */ public String getDescription() { return description; } /** * This method map audio content kind symbol to corresponding enum * @param value a Symbol representing audio content kind * @return AudioContentKind enumeration for the symbol if present otherwise returns Unknown enumeration */ public static AudioContentKind getAudioContentKindFromSymbol(String value) { if(value == null) { return Unknown; } try { return AudioContentKind.valueOf(value); } catch(IllegalArgumentException e) { return Unknown; } } }
5,050
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFEssenceDescriptorBaseType.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.utils.UUIDHelper; import javax.annotation.concurrent.Immutable; import java.util.List; import java.util.UUID; /** * A class that models a Composition's Essence Descriptor. */ @Immutable public final class IMFEssenceDescriptorBaseType { protected final UUID id; protected final List<Object> any; public IMFEssenceDescriptorBaseType(String id, List<Object> any) { this.id = UUIDHelper.fromUUIDAsURNStringToUUID(id); this.any = any; } /** * Getter for the Sequence ID * @return a string representing the urn:uuid of the Essence Descriptor. */ public UUID getId(){ return this.id; } /** * Getter for the Any property of the Essence Descriptor * @return a List representing Any property of the Essence Descriptor. */ public List<Object> getAny(){ return this.any; } }
5,051
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFCoreConstraintsChecker.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.RegXMLLibDictionary; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * A class that performs CoreConstraints st2067-2 related checks on the elements of a Composition Playlist such as VirtualTracks, Segments, Sequences and Resources. */ final class IMFCoreConstraintsChecker { private static final Set<String> homogeneitySelectionSet = new HashSet<String>(){{ add("CDCIDescriptor"); add("RGBADescriptor"); add("SubDescriptors"); add("JPEG2000SubDescriptor"); add("WAVEPCMDescriptor"); add("StoredWidth"); add("StoredHeight"); add("FrameLayout"); add("SampleRate"); add("PixelLayout"); add("ColorPrimaries"); add("TransferCharacteristic"); add("PictureCompression"); add("ComponentMaxRef"); add("ComponentMinRef"); add("BlackRefLevel"); add("WhiteRefLevel"); add("ColorRange"); add("ColorSiting"); add("ComponentDepth"); add("HorizontalSubsampling"); add("VerticalSubsampling"); add("Xsiz"); add("Ysiz"); add("Csiz"); add("J2CLayout"); add("RGBAComponent"); add("Code"); add("ComponentSize"); add("PictureComponentSizing"); add("J2KComponentSizing"); add("Ssiz"); add("XRSiz"); add("YRSiz"); add("AudioSampleRate"); add("QuantizationBits"); }}; //To prevent instantiation private IMFCoreConstraintsChecker(){ } public static List<ErrorLogger.ErrorObject> checkVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap) { RegXMLLibDictionary regXMLLibDictionary = new RegXMLLibDictionary(); return checkVirtualTracks(compositionPlaylistType, virtualTrackMap, essenceDescriptorListMap, regXMLLibDictionary); } public static List<ErrorLogger.ErrorObject> checkVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap, RegXMLLibDictionary regXMLLibDictionary) { return checkVirtualTracks(compositionPlaylistType, virtualTrackMap, essenceDescriptorListMap, regXMLLibDictionary, new HashSet<>()); } /** * Checks that there is only one video track and at least one audio track and that * for each virtual track in the given virtual track map that: * - the track is made of supported sequences * - the CPL edit rate matches one of the MainImageSequence edit rate * - the resources are valid see checkVirtualTrackResourceList * - each resource has a corresponding essence descriptor * - the CPL and descriptor rates match * - the descriptors are homogeneous * * @param compositionPlaylistType CPL object * @param virtualTrackMap map of tracks indexed by UUID * @param essenceDescriptorListMap map of essence descriptors in the CPL * @param regXMLLibDictionary helper for producing XML representation of descriptors * @param homogeneitySelectionSet set of strings for which homogenity has to be checked * @return a list of errors */ public static List<ErrorLogger.ErrorObject> checkVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap, RegXMLLibDictionary regXMLLibDictionary, Set<String> homogeneitySelectionSet){ boolean foundMainImageEssence = false; int numberOfMainImageEssences = 0; boolean foundMainAudioEssence = false; IMFErrorLogger imfErrorLogger =new IMFErrorLoggerImpl(); Iterator iterator = virtualTrackMap.entrySet().iterator(); while(iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); List<? extends IMFBaseResourceType> virtualTrackResourceList = virtualTrack.getResourceList(); imfErrorLogger.addAllErrors(checkVirtualTrackResourceList(virtualTrack.getTrackID(), virtualTrackResourceList)); if (!(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MarkerSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence) || (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.ForcedNarrativeSequence) && compositionPlaylistType.getCoreConstraintsSchema().equals(CoreConstraints.NAMESPACE_IMF_2020)) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.IABSequence))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("CPL has a Sequence of type %s which is not fully supported sequence type in Photon", virtualTrack.getSequenceTypeEnum().toString())); continue; } if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence)) { foundMainImageEssence = true; numberOfMainImageEssences++; Composition.EditRate compositionEditRate = compositionPlaylistType.getEditRate(); for (IMFBaseResourceType baseResourceType : virtualTrackResourceList) { Composition.EditRate trackResourceEditRate = baseResourceType.getEditRate(); //Section 6.4 st2067-2:2016 if (trackResourceEditRate != null && !trackResourceEditRate.equals(compositionEditRate)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("This Composition is invalid since the CompositionEditRate %s is not the same as atleast one of the MainImageSequence's Resource EditRate %s. Please refer to st2067-2:2013 Section 6.4", compositionEditRate.toString(), trackResourceEditRate.toString())); } } } else if(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)){ foundMainAudioEssence = true; } if((virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence) || (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.ForcedNarrativeSequence) && compositionPlaylistType.getCoreConstraintsSchema().equals(CoreConstraints.NAMESPACE_IMF_2020)) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.IABSequence)) && compositionPlaylistType.getEssenceDescriptorList() != null && compositionPlaylistType.getEssenceDescriptorList().size() > 0) { List<DOMNodeObjectModel> virtualTrackEssenceDescriptors = new ArrayList<>(); String refSourceEncodingElement = ""; String essenceDescriptorField = ""; String otherEssenceDescriptorField = ""; Composition.EditRate essenceEditRate = null; for(IMFBaseResourceType imfBaseResourceType : virtualTrackResourceList){ IMFTrackFileResourceType imfTrackFileResourceType = IMFTrackFileResourceType.class.cast(imfBaseResourceType); DOMNodeObjectModel domNodeObjectModel = essenceDescriptorListMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(imfTrackFileResourceType.getSourceEncoding())); //Section 6.8 st2067-2:2016 if(domNodeObjectModel == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by a " + "VirtualTrack Resource does not have a corresponding EssenceDescriptor in the EssenceDescriptorList in the CPL", imfTrackFileResourceType.getSourceEncoding())); } else { if (!refSourceEncodingElement.equals(imfTrackFileResourceType.getSourceEncoding())) { refSourceEncodingElement = imfTrackFileResourceType.getSourceEncoding(); //Section 6.3.1 and 6.3.2 st2067-2:2016 Edit Rate check if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence) || (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.ForcedNarrativeSequence) && compositionPlaylistType.getCoreConstraintsSchema().equals(CoreConstraints.NAMESPACE_IMF_2020))) { essenceDescriptorField = "SampleRate"; } else if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.IABSequence)) { essenceDescriptorField = "SampleRate"; otherEssenceDescriptorField = "AudioSampleRate"; } String sampleRate = domNodeObjectModel.getFieldAsString(essenceDescriptorField); if(sampleRate == null && !otherEssenceDescriptorField.isEmpty()) { sampleRate = domNodeObjectModel.getFieldAsString(otherEssenceDescriptorField); } if (sampleRate != null) { Long numerator = 0L; Long denominator = 0L; String[] sampleRateElements = (sampleRate.contains(" ")) ? sampleRate.split(" ") : sampleRate.contains("/") ? sampleRate.split("/") : new String[2]; if (sampleRateElements.length == 2) { numerator = Long.valueOf(sampleRateElements[0]); denominator = Long.valueOf(sampleRateElements[1]); } else if (sampleRateElements.length == 1) { numerator = Long.valueOf(sampleRateElements[0]); denominator = 1L; } List<Long> editRate = new ArrayList<>(); Integer sampleRateToEditRateScale = 1; if(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence)) { CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel = new CompositionImageEssenceDescriptorModel(UUIDHelper.fromUUIDAsURNStringToUUID (imfTrackFileResourceType.getSourceEncoding()), domNodeObjectModel, regXMLLibDictionary); sampleRateToEditRateScale = imageEssenceDescriptorModel.getFrameLayoutType().equals(GenericPictureEssenceDescriptor.FrameLayoutType.SeparateFields) ? 2 : 1; } editRate.add(numerator / sampleRateToEditRateScale); editRate.add(denominator); essenceEditRate = new Composition.EditRate(editRate); } } if (essenceEditRate == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s has a Resource represented by ID %s that seems to refer to a EssenceDescriptor in the CPL's EssenceDescriptorList represented by the ID %s " + "which does not have a value set for the field %s, however the Resource Edit Rate is %s" , compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), imfBaseResourceType.getId(), imfTrackFileResourceType.getSourceEncoding(), essenceDescriptorField, imfBaseResourceType.getEditRate().toString())); } else if (!essenceEditRate.equals(imfBaseResourceType.getEditRate())) { //Section 6.3.1 and 6.3.2 st2067-2:2016 imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s has a Resource represented by ID %s that refers to a EssenceDescriptor in the CPL's EssenceDescriptorList represented by the ID %s " + "whose indicated %s value is %s, however the Resource Edit Rate is %s" , compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), imfBaseResourceType.getId(), imfTrackFileResourceType.getSourceEncoding(), essenceDescriptorField, essenceEditRate.toString(), imfBaseResourceType.getEditRate().toString())); } virtualTrackEssenceDescriptors.add(domNodeObjectModel); } } //Section 6.8 st2067-2:2016 if(!(virtualTrackEssenceDescriptors.size() > 0)){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the resources comprising the VirtualTrack represented by ID %s seem to refer to EssenceDescriptor/s in the CPL's EssenceDescriptorList that are absent", compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString())); } else if( virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.IABSequence)){ boolean isVirtualTrackHomogeneous = true; Set<String> homogeneitySelectionSetAll = new HashSet<>(homogeneitySelectionSet); homogeneitySelectionSetAll.addAll(IMFCoreConstraintsChecker.homogeneitySelectionSet); if (isCDCIEssenceDescriptor(virtualTrackEssenceDescriptors.get(0))) { homogeneitySelectionSetAll.add("CodingEquations"); } DOMNodeObjectModel refDOMNodeObjectModel = virtualTrackEssenceDescriptors.get(0).createDOMNodeObjectModelSelectionSet(virtualTrackEssenceDescriptors.get(0), homogeneitySelectionSetAll); for (int i = 1; i < virtualTrackEssenceDescriptors.size(); i++) { DOMNodeObjectModel other = virtualTrackEssenceDescriptors.get(i).createDOMNodeObjectModelSelectionSet(virtualTrackEssenceDescriptors.get(i), homogeneitySelectionSetAll); isVirtualTrackHomogeneous &= refDOMNodeObjectModel.equals(other); } List<DOMNodeObjectModel> modelsIgnoreSet = new ArrayList<>(); if (!isVirtualTrackHomogeneous) { for(int i = 1; i< virtualTrackEssenceDescriptors.size(); i++){ DOMNodeObjectModel other = virtualTrackEssenceDescriptors.get(i).createDOMNodeObjectModelSelectionSet(virtualTrackEssenceDescriptors.get(i), homogeneitySelectionSetAll); modelsIgnoreSet.add(other); imfErrorLogger.addAllErrors(DOMNodeObjectModel.getNamespaceURIMismatchErrors(refDOMNodeObjectModel, other)); } //Section 6.2 st2067-2:2016 imfErrorLogger.addAllErrors(refDOMNodeObjectModel.getErrors()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s is not homogeneous based on a comparison of the EssenceDescriptors referenced by its resources in the Essence Descriptor List, " + "the EssenceDescriptors corresponding to this VirtualTrack in the EssenceDescriptorList are as follows %n%n%s", compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), Utilities.serializeObjectCollectionToString(modelsIgnoreSet))); } } } } //TODO : Add a check to ensure that all the VirtualTracks have the same duration. //Section 6.3.1 st2067-2:2016 and Section 6.9.3 st2067-3:2016 if(!foundMainImageEssence){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s does not contain a single image essence in its first segment, exactly one is required", compositionPlaylistType.getId().toString())); } else{ if(numberOfMainImageEssences > 1){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s seems to contain %d image essences in its first segment, exactly one is required", compositionPlaylistType.getId().toString(), numberOfMainImageEssences)); } } //Section 6.3.2 st2067-2:2016 and Section 6.9.3 st2067-3:2016 //Section 6.3.2 st2067-2:2020 allows CPLs without Audio Virtual Tracks if(!foundMainAudioEssence && (compositionPlaylistType.getCoreConstraintsSchema().equals(CoreConstraints.NAMESPACE_IMF_2013) || compositionPlaylistType.getCoreConstraintsSchema().equals(CoreConstraints.NAMESPACE_IMF_2016))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s does not contain a single audio essence in its first segment, one or more is required", compositionPlaylistType.getId().toString())); } return imfErrorLogger.getErrors(); } public static boolean hasIABVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap){ boolean foundIABEssence = false; IMFErrorLogger imfErrorLogger =new IMFErrorLoggerImpl(); Iterator iterator = virtualTrackMap.entrySet().iterator(); while(iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); List<? extends IMFBaseResourceType> virtualTrackResourceList = virtualTrack.getResourceList(); List<ErrorLogger.ErrorObject> errors = checkVirtualTrackResourceList(virtualTrack.getTrackID(), virtualTrackResourceList); imfErrorLogger.addAllErrors(errors); if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.IABSequence)) { foundIABEssence = true; } } return foundIABEssence; } /** * Checks that for each segment that: * - all tracks in the segment are in the reference track map * - the reference track map and the segment have the same number of tracks * - it has an integer duration when expressed in the CPL edit rate * - all its sequences have the same duration * * @param compositionPlaylistType the playlist from which segments are to be checked * @param virtualTrackMap a map of all the virtual tracks in a segment against which checks will be made * @param imfErrorLogger the logger object in which error messages are added **/ public static void checkSegments(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, Composition.VirtualTrack> virtualTrackMap, @Nullable IMFErrorLogger imfErrorLogger) { for (IMFSegmentType segment : compositionPlaylistType.getSegmentList()) { Set<UUID> trackIDs = new HashSet<>(); /* TODO: Add check for Marker sequence */ Set<Long> sequencesDurationSet = new HashSet<>(); double compositionEditRate = (double)compositionPlaylistType.getEditRate().getNumerator()/compositionPlaylistType.getEditRate().getDenominator(); for (IMFSequenceType sequence : segment.getSequenceList()) { UUID uuid = UUIDHelper.fromUUIDAsURNStringToUUID(sequence.getTrackId()); trackIDs.add(uuid); if (virtualTrackMap.get(uuid) == null) { //Section 6.9.3 st2067-3:2016 String message = String.format( "Segment represented by the ID %s in the Composition represented by ID %s contains virtual track represented by ID %s, which does not appear in all the segments of the Composition, this is invalid", segment.getId(), compositionPlaylistType.getId().toString(), uuid); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, message); } List<? extends IMFBaseResourceType> resources = sequence.getResourceList(); Long sequenceDurationInCompositionEditUnits = 0L; Long sequenceDuration = 0L; //Based on Section 6.2 and 6.3 in st2067-2:2016 All resources of either an Image Sequence or an Audio Sequence have to be of the same EditRate, hence we can sum the source durations of all the resources //of a virtual track to get its duration in resource edit units. for(IMFBaseResourceType imfBaseResourceType : resources){ sequenceDuration += imfBaseResourceType.getDuration(); } //Section 7.3 st2067-3:2016 long compositionEditRateNumerator = compositionPlaylistType.getEditRate().getNumerator(); long compositionEditRateDenominator = compositionPlaylistType.getEditRate().getDenominator(); long resourceEditRateNumerator = resources.get(0).getEditRate().getNumerator(); long resourceEditRateDenominator = resources.get(0).getEditRate().getDenominator(); long sequenceDurationInCompositionEditRateReminder = (sequenceDuration * compositionEditRateNumerator * resourceEditRateDenominator) % (compositionEditRateDenominator * resourceEditRateNumerator); Double sequenceDurationDoubleValue = ((double)sequenceDuration * compositionEditRateNumerator * resourceEditRateDenominator) / (compositionEditRateDenominator * resourceEditRateNumerator); //Section 7.3 st2067-3:2016 if(sequenceDurationInCompositionEditRateReminder != 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Segment represented by the Id %s in the Composition represented by ID %s has a sequence represented by ID %s, whose duration represented in Composition Edit Units is (%f) is not an integer" , segment.getId(), compositionPlaylistType.getId().toString(), sequence.getId(), sequenceDurationDoubleValue)); } sequenceDurationInCompositionEditUnits = Math.round(sequenceDurationDoubleValue); sequencesDurationSet.add(sequenceDurationInCompositionEditUnits); } //Section 7.2 st2067-3:2016 if(sequencesDurationSet.size() > 1){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Segment represented by the Id %s seems to have sequences that are not of the same duration, following sequence durations were computed based on the information in the Sequence List for this Segment, %s represented in Composition Edit Units", segment.getId(), Utilities.serializeObjectCollectionToString(sequencesDurationSet))); } //Section 6.9.3 st2067-3:2016 if (trackIDs.size() != virtualTrackMap.size()) { String message = String.format( "Number of distinct virtual trackIDs in a segment = %s, different from first segment %d", trackIDs.size(), virtualTrackMap.size()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, message); } } } /** * Checks within a list of Resources that * - each resource has a valid duration (positive and less than the intrinsic duration), including for marker resources * - all resources use the same edit rate * * @param trackID the track ID of the track to which the resources belong, used for logging * @param virtualBaseResourceList the list of resources, including marker resources * @return a list of errors */ public static List<ErrorLogger.ErrorObject> checkVirtualTrackResourceList(UUID trackID, List<? extends IMFBaseResourceType> virtualBaseResourceList){ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); //Section 6.9.3 st2067-3:2016 if(virtualBaseResourceList == null || virtualBaseResourceList.size() == 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s does not have any associated resources this is invalid", trackID.toString())); return imfErrorLogger.getErrors(); } Set<Composition.EditRate> editRates = new HashSet<>(); Composition.EditRate baseResourceEditRate = null; for(IMFBaseResourceType baseResource : virtualBaseResourceList){ long compositionPlaylistResourceIntrinsicDuration = baseResource.getIntrinsicDuration().longValue(); long compositionPlaylistResourceEntryPoint = (baseResource.getEntryPoint() == null) ? 0L : baseResource.getEntryPoint().longValue(); //Check to see if the Resource's source duration value is in the valid range as specified in st2067-3:2013 section 6.11.6 if(baseResource.getSourceDuration() != null){ if(baseResource.getSourceDuration().longValue() < 0 || baseResource.getSourceDuration().longValue() > (compositionPlaylistResourceIntrinsicDuration - compositionPlaylistResourceEntryPoint)){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has a resource with ID %s, that has an invalid source duration value %d, should be in the range [0,%d]", trackID.toString(), baseResource.getId(), baseResource.getSourceDuration().longValue(), (compositionPlaylistResourceIntrinsicDuration - compositionPlaylistResourceEntryPoint))); } } //Check to see if the Marker Resource's intrinsic duration value is in the valid range as specified in st2067-3:2013 section 6.13 if (baseResource instanceof IMFMarkerResourceType) { IMFMarkerResourceType markerResource = IMFMarkerResourceType.class.cast(baseResource); List<IMFMarkerType> markerList = markerResource.getMarkerList(); for (IMFMarkerType marker : markerList) { if (marker.getOffset().longValue() >= markerResource.getIntrinsicDuration().longValue()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has a " + "resource with ID %s, that has a marker %s, that has an invalid offset " + "value %d, should be in the range [0,%d] ", trackID.toString(), markerResource.getId(), marker.getLabel().getValue(), marker .getOffset().longValue(), markerResource.getIntrinsicDuration().longValue()-1)); } } } baseResourceEditRate = baseResource.getEditRate(); if(baseResourceEditRate != null){ editRates.add(baseResourceEditRate); } } //Section 6.2, 6.3.1 and 6.3.2 st2067-2:2016 if(editRates.size() > 1){ StringBuilder editRatesString = new StringBuilder(); Iterator iterator = editRates.iterator(); while(iterator.hasNext()){ editRatesString.append(iterator.next().toString()); editRatesString.append(String.format("%n")); } imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has resources with inconsistent editRates %s", trackID.toString(), editRatesString.toString())); } return imfErrorLogger.getErrors(); } private static boolean isCDCIEssenceDescriptor(DOMNodeObjectModel domNodeObjectModel) { return domNodeObjectModel.getLocalName().equals("CDCIDescriptor"); } }
5,052
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/ApplicationUnsupportedComposition.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import javax.annotation.Nonnull; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * A class that models Composition with Application 2 constraints from 2067-20 specification */ public class ApplicationUnsupportedComposition extends AbstractApplicationComposition { private static final Set<String> ignoreSet = Collections.unmodifiableSet(new HashSet<String>() {{ add("SignalStandard"); add("ActiveFormatDescriptor"); add("VideoLineMap"); add("AlphaTransparency"); add("PixelLayout"); add("ActiveHeight"); add("ActiveWidth"); add("ActiveXOffset"); add("ActiveYOffset"); }}); public ApplicationUnsupportedComposition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType) { this(imfCompositionPlaylistType, new HashSet<>()); } public ApplicationUnsupportedComposition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType, Set<String> homogeneitySelectionSet) { super(imfCompositionPlaylistType, ignoreSet, homogeneitySelectionSet); for(String appString: imfCompositionPlaylistType.getApplicationIdentificationSet()) { if (ApplicationCompositionType.fromApplicationID(appString).equals(ApplicationCompositionType.APPLICATION_UNSUPPORTED_COMPOSITION_TYPE)){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("Application ID %s is not fully supported", appString)); } } } public ApplicationCompositionType getApplicationCompositionType() { return ApplicationCompositionType.APPLICATION_UNSUPPORTED_COMPOSITION_TYPE; } }
5,053
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFTrackFileResourceType.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.math.BigInteger; import java.util.Arrays; import java.util.List; /** * A class that models TrackFile Resource structure of an IMF Composition Playlist. */ @Immutable public final class IMFTrackFileResourceType extends IMFBaseResourceType { private final String trackFileId; private final String sourceEncoding; private final byte[] hash; private final String hashAlgorithm; public IMFTrackFileResourceType(String id, String trackFileId, List<Long> editRate, BigInteger intrinsicDuration, BigInteger entryPoint, BigInteger sourceDuration, BigInteger repeatCount, String sourceEncoding, byte[] hash, String hashAlgorithm ) { super(id, editRate, intrinsicDuration, entryPoint, sourceDuration, repeatCount); this.trackFileId = trackFileId; this.sourceEncoding = sourceEncoding; this.hash = (hash == null) ? null : Arrays.copyOf(hash, hash.length); this.hashAlgorithm = hashAlgorithm; } /** * Getter for the Track Resource's track file Id * @return a string representing the urn:uuid of the Track Resource's track file Id */ public String getTrackFileId(){ return this.trackFileId; } /** * Getter for the SourceEncoding of the Track's Resource * @return a String representing the Track Resource's SourceEncoding */ public String getSourceEncoding(){ return this.sourceEncoding; } /** * Getter for the Hash of this Resource * @return a byte[] copy of the hash */ @Nullable public byte[] getHash(){ return (this.hash == null) ? null : Arrays.copyOf(this.hash, this.hash.length); } /** * Getter for the HashAlgorithm used in creating the hash of this resource * @return a String representing the HashAlgorithm */ @Nullable public String getHashAlgorithm(){ return this.hashAlgorithm; } /** * A method to determine the equivalence of any 2 TrackFileResource. * @param other - the object to compare against * @return boolean indicating if the 2 TrackFileResources are equivalent/representing the same timeline */ @Override public boolean equivalent(IMFBaseResourceType other) { if(other == null || !(other instanceof IMFTrackFileResourceType)){ return false; } IMFTrackFileResourceType otherTrackFileResource = IMFTrackFileResourceType.class.cast(other); boolean result = true; //Compare the following fields of the track file resources that have to be equal //for the 2 resources to be considered equivalent/representing the same timeline. result &= super.equivalent( otherTrackFileResource ); result &= trackFileId.equals(otherTrackFileResource.getTrackFileId()); return result; } }
5,054
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/Application2E2021.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.Colorimetry; import com.netflix.imflibrary.Colorimetry.ColorModel; import com.netflix.imflibrary.Colorimetry.Quantization; import com.netflix.imflibrary.Colorimetry.Sampling; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.Fraction; import com.netflix.imflibrary.JPEG2000; import javax.annotation.Nonnull; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Arrays; import static com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.FrameLayoutType; /** * A class that models Composition with Application 2Extended constraints from * 2067-21 specification */ public class Application2E2021 extends AbstractApplicationComposition { private static String APP_STRING = ApplicationCompositionType.APPLICATION_2E2021_COMPOSITION_TYPE.toString(); static class CharacteristicsSet { private Integer maxWidth; private Integer maxHeight; private HashSet<Colorimetry> colorSystems; private HashSet<Integer> bitDepths; private HashSet<FrameLayoutType> frameStructures; private HashSet<Fraction> frameRates; private HashSet<Sampling> samplings; private HashSet<Quantization> quantizations; private HashSet<ColorModel> colorModels; /* Stereoscopic images are not supported */ public CharacteristicsSet(Integer maxWidth, Integer maxHeight, List<Colorimetry> colorSystems, List<Integer> bitDepths, List<FrameLayoutType> frameStructures, List<Fraction> frameRates, List<Sampling> samplings, List<Quantization> quantizations, List<ColorModel> colorModels) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.colorSystems = new HashSet<Colorimetry>(colorSystems); this.bitDepths = new HashSet<Integer>(bitDepths); this.frameStructures = new HashSet<FrameLayoutType>(frameStructures); this.frameRates = new HashSet<Fraction>(frameRates); this.samplings = new HashSet<Sampling>(samplings); this.quantizations = new HashSet<Quantization>(quantizations); this.colorModels = new HashSet<ColorModel>(colorModels); } public boolean has(Integer width, Integer height, Colorimetry colorSystem, Integer bitDepth, FrameLayoutType frameStructure, Fraction frameRate, Sampling sampling, Quantization quantization, ColorModel colorModel) { return width <= this.maxWidth && height <= this.maxHeight && this.colorSystems.contains(colorSystem) && this.bitDepths.contains(bitDepth) && this.frameStructures.contains(frameStructure) && this.frameRates.contains(frameRate) && this.samplings.contains(sampling) && this.quantizations.contains(quantization) && this.colorModels.contains(colorModel); } } static final Fraction[] FPS_HD = { new Fraction(25), new Fraction(30), new Fraction(30000, 1001) }; static final Fraction[] FPS_UHD = { new Fraction(24), new Fraction(24000, 1001), new Fraction(25), new Fraction(30), new Fraction(30000, 1001), new Fraction(50), new Fraction(60), new Fraction(60000, 1001) }; static final Fraction[] FPS_4K = { new Fraction(24), new Fraction(24000, 1001), new Fraction(25), new Fraction(30), new Fraction(30000, 1001), new Fraction(50), new Fraction(60), new Fraction(60000, 1001), new Fraction(120) }; /* Table 3 at SMPTE ST 2067-21:2023 */ static final CharacteristicsSet[] IMAGE_CHARACTERISTICS = { new CharacteristicsSet( 1920, 1080, Arrays.asList(Colorimetry.Color1, Colorimetry.Color2, Colorimetry.Color3), Arrays.asList(8, 10), Arrays.asList(FrameLayoutType.SeparateFields), Arrays.asList(FPS_HD), Arrays.asList(Sampling.Sampling422), Arrays.asList(Quantization.QE1), Arrays.asList(ColorModel.YUV) ), new CharacteristicsSet( 1920, 1080, Arrays.asList(Colorimetry.Color1, Colorimetry.Color2, Colorimetry.Color3), Arrays.asList(8, 10), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_HD), Arrays.asList(Sampling.Sampling422), Arrays.asList(Quantization.QE1), Arrays.asList(ColorModel.YUV) ), new CharacteristicsSet( 1920, 1080, Arrays.asList(Colorimetry.Color1, Colorimetry.Color2, Colorimetry.Color3), Arrays.asList(8, 10), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_HD), Arrays.asList(Sampling.Sampling444), Arrays.asList(Quantization.QE1), Arrays.asList(ColorModel.YUV, ColorModel.RGB) ), new CharacteristicsSet( 3840, 2160, Arrays.asList(Colorimetry.Color4), Arrays.asList(8, 10), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_UHD), Arrays.asList(Sampling.Sampling422), Arrays.asList(Quantization.QE1), Arrays.asList(ColorModel.YUV) ), new CharacteristicsSet( 3840, 2160, Arrays.asList(Colorimetry.Color3), Arrays.asList(8, 10, 12, 16), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_UHD), Arrays.asList(Sampling.Sampling422), Arrays.asList(Quantization.QE1), Arrays.asList(ColorModel.YUV) ), new CharacteristicsSet( 3840, 2160, Arrays.asList(Colorimetry.Color5, Colorimetry.Color8), Arrays.asList(10, 12), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_UHD), Arrays.asList(Sampling.Sampling422), Arrays.asList(Quantization.QE1), Arrays.asList(ColorModel.YUV) ), new CharacteristicsSet( 3840, 2160, Arrays.asList(Colorimetry.Color7), Arrays.asList(10, 12, 16), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_UHD), Arrays.asList(Sampling.Sampling422), Arrays.asList(Quantization.QE1), Arrays.asList(ColorModel.YUV) ), new CharacteristicsSet( 4096, 3112, Arrays.asList(Colorimetry.Color3), Arrays.asList(8, 10, 12, 16), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_4K), Arrays.asList(Sampling.Sampling444), Arrays.asList(Quantization.QE1, Quantization.QE2), Arrays.asList(ColorModel.RGB) ), new CharacteristicsSet( 4096, 3112, Arrays.asList(Colorimetry.Color5, Colorimetry.Color8), Arrays.asList(10, 12), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_4K), Arrays.asList(Sampling.Sampling444), Arrays.asList(Quantization.QE1, Quantization.QE2), Arrays.asList(ColorModel.RGB) ), new CharacteristicsSet( 4096, 3112, Arrays.asList(Colorimetry.Color6, Colorimetry.Color7), Arrays.asList(10, 12, 16), Arrays.asList(FrameLayoutType.FullFrame), Arrays.asList(FPS_4K), Arrays.asList(Sampling.Sampling444), Arrays.asList(Quantization.QE1, Quantization.QE2), Arrays.asList(ColorModel.RGB) ) }; private static final Set<String> ignoreSet = Collections.unmodifiableSet(new HashSet<String>(){{ add("SignalStandard"); add("ActiveFormatDescriptor"); add("VideoLineMap"); add("AlphaTransparency"); add("PixelLayout"); add("ActiveHeight"); add("ActiveWidth"); add("ActiveXOffset"); add("ActiveYOffset"); }}); public Application2E2021(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType) { this(imfCompositionPlaylistType, new HashSet<>()); } public Application2E2021(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType, Set<String> homogeneitySelectionSet) { super(imfCompositionPlaylistType, ignoreSet, homogeneitySelectionSet); try { CompositionImageEssenceDescriptorModel imageDescriptorModel = getCompositionImageEssenceDescriptorModel(); if (imageDescriptorModel != null) { imfErrorLogger.addAllErrors(imageDescriptorModel.getErrors()); Application2Composition.validateGenericPictureEssenceDescriptor( imageDescriptorModel, ApplicationCompositionType.APPLICATION_2E2021_COMPOSITION_TYPE, imfErrorLogger ); Application2E2021.validateImageCharacteristics(imageDescriptorModel, imfErrorLogger); } } catch (Exception e) { imfErrorLogger.addError( IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format( "Exception in validating EssenceDescriptors in APPLICATION_2E_COMPOSITION_TYPE: %s ", e.getMessage())); } } public static boolean isValidJ2KProfile(CompositionImageEssenceDescriptorModel imageDescriptor) { UL essenceCoding = imageDescriptor.getPictureEssenceCodingUL(); Integer width = imageDescriptor.getStoredWidth(); Integer height = imageDescriptor.getStoredHeight(); if (JPEG2000.isAPP2HT(essenceCoding)) return true; if (JPEG2000.isIMF4KProfile(essenceCoding)) return width > 2048 && width <= 4096 && height > 0 && height <= 3112; if (JPEG2000.isIMF2KProfile(essenceCoding)) return width > 0 && width <= 2048 && height > 0 && height <= 1556; if (JPEG2000.isBroadcastProfile(essenceCoding)) return width > 0 && width <= 3840 && height > 0 && height <= 2160; return false; } public static void validateImageCharacteristics(CompositionImageEssenceDescriptorModel imageDescriptor, IMFErrorLogger logger) { // J2K profiles if (!isValidJ2KProfile(imageDescriptor)) { logger.addError( IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, "Invalid JPEG 2000 profile"); } boolean isValid = false; for (CharacteristicsSet imgCharacteristicsSet : IMAGE_CHARACTERISTICS) { isValid = imgCharacteristicsSet.has( imageDescriptor.getStoredWidth(), imageDescriptor.getStoredHeight(), imageDescriptor.getColor(), imageDescriptor.getPixelBitDepth(), imageDescriptor.getFrameLayoutType(), imageDescriptor.getSampleRate(), imageDescriptor.getSampling(), imageDescriptor.getQuantization(), imageDescriptor.getColorModel() ); if (isValid) break; } if (!isValid) { logger.addError( IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format( "Invalid image characteristics per %s", APP_STRING ) ); } } public ApplicationCompositionType getApplicationCompositionType() { return ApplicationCompositionType.APPLICATION_2E2021_COMPOSITION_TYPE; } }
5,055
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/Application2Composition.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.Colorimetry; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.st0422.JP2KContentKind; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.Fraction; import javax.annotation.Nonnull; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.UUID; import static com.netflix.imflibrary.Colorimetry.CodingEquation; import static com.netflix.imflibrary.Colorimetry.ColorModel; import static com.netflix.imflibrary.Colorimetry.ColorPrimaries; import static com.netflix.imflibrary.Colorimetry.Quantization; import static com.netflix.imflibrary.Colorimetry.Sampling; import static com.netflix.imflibrary.Colorimetry.TransferCharacteristic; import static com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.FrameLayoutType; /** * A class that models Composition with Application 2 constraints from 2067-20 specification */ public class Application2Composition extends AbstractApplicationComposition { public static final String SCHEMA_URI_APP2_2013 = "http://www.smpte-ra.org/schemas/2067-20/2013"; public static final String SCHEMA_URI_APP2_2016 = "http://www.smpte-ra.org/schemas/2067-20/2016"; public static final UL JPEG2000PICTURECODINGSCHEME = UL.fromULAsURNStringToUL("urn:smpte:ul:060e2b34.04010107.04010202.03010000"); public static final Integer MAX_IMAGE_FRAME_WIDTH = 1920; public static final Integer MAX_IMAGE_FRAME_HEIGHT = 1080; public static final Set<Fraction>progressiveSampleRateSupported = Collections.unmodifiableSet(new HashSet<Fraction>() {{ add(new Fraction(24)); add(new Fraction(25)); add(new Fraction(30)); add(new Fraction(50)); add(new Fraction(60)); add(new Fraction(24000, 1001)); add(new Fraction(30000, 1001)); add(new Fraction(60000, 1001)); }}); public static final Set<Fraction>interlaceSampleRateSupported = Collections.unmodifiableSet(new HashSet<Fraction>() {{ add(new Fraction(50)); add(new Fraction(60)); add(new Fraction(60000, 1001)); }}); public static final Set<Integer>bitDepthsSupported = Collections.unmodifiableSet(new HashSet<Integer>() {{ add(8); add(10); }}); private static final Set<String> ignoreSet = Collections.unmodifiableSet(new HashSet<String>() {{ add("SignalStandard"); add("ActiveFormatDescriptor"); add("VideoLineMap"); add("AlphaTransparency"); add("PixelLayout"); add("ActiveHeight"); add("ActiveWidth"); add("ActiveXOffset"); add("ActiveYOffset"); }}); public Application2Composition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType) { this(imfCompositionPlaylistType, new HashSet<>()); } public Application2Composition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType, Set<String> homogeneitySelectionSet) { super(imfCompositionPlaylistType, ignoreSet, homogeneitySelectionSet); try { CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel = getCompositionImageEssenceDescriptorModel(); if (imageEssenceDescriptorModel != null) { imfErrorLogger.addAllErrors(imageEssenceDescriptorModel.getErrors()); Application2Composition.validateGenericPictureEssenceDescriptor(imageEssenceDescriptorModel, ApplicationCompositionType.APPLICATION_2_COMPOSITION_TYPE, imfErrorLogger); Application2Composition.validateImageCharacteristics(imageEssenceDescriptorModel, ApplicationCompositionType.APPLICATION_2_COMPOSITION_TYPE, imfErrorLogger); } } catch (Exception e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Exception in validating EssenceDescriptors in APPLICATION_2_COMPOSITION_TYPE: %s ", e.getMessage())); } } public static void validateGenericPictureEssenceDescriptor(CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel, ApplicationCompositionFactory.ApplicationCompositionType applicationCompositionType, IMFErrorLogger imfErrorLogger) { UUID imageEssenceDescriptorID = imageEssenceDescriptorModel.getImageEssencedescriptorID(); ColorModel colorModel = imageEssenceDescriptorModel.getColorModel(); if( colorModel.equals(ColorModel.Unknown)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has Invalid color components as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); return; } Integer componentDepth = imageEssenceDescriptorModel.getComponentDepth(); if (colorModel.equals(ColorModel.YUV) && componentDepth == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing component depth required per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } Integer storedWidth = imageEssenceDescriptorModel.getStoredWidth(); Integer storedHeight = imageEssenceDescriptorModel.getStoredHeight(); if ((storedWidth <= 0) || (storedHeight <= 0)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid storedWidth(%d) or storedHeight(%d) as per %s", imageEssenceDescriptorID.toString(), storedWidth, storedHeight, applicationCompositionType.toString())); } Integer sampleWidth = imageEssenceDescriptorModel.getSampleWidth(); Integer sampleHeight = imageEssenceDescriptorModel.getSampleHeight(); if ((sampleWidth != null && !sampleWidth.equals(storedWidth)) || (sampleHeight != null && !sampleHeight.equals(storedHeight))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid sampleWidth(%d) or sampleHeight(%d) as per %s", imageEssenceDescriptorID.toString(), sampleWidth != null ? sampleWidth : 0, sampleHeight != null ? sampleHeight : 0, applicationCompositionType.toString())); } if( imageEssenceDescriptorModel.getStoredOffset() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s invalid StoredOffset as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } ColorPrimaries colorPrimaries = imageEssenceDescriptorModel.getColorPrimaries(); if(colorPrimaries.equals(ColorPrimaries.Unknown)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid ColorPrimaries as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } TransferCharacteristic transferCharacteristic = imageEssenceDescriptorModel.getTransferCharacteristic(); if(transferCharacteristic.equals(TransferCharacteristic.Unknown)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid TransferCharacteristic as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } CodingEquation codingEquation = imageEssenceDescriptorModel.getCodingEquation(); if(codingEquation.equals(CodingEquation.Unknown)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid CodingEquation as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } Colorimetry color = imageEssenceDescriptorModel.getColor(); if(color.equals(Colorimetry.Unknown)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid ColorPrimaries(%s)-TransferCharacteristic(%s)-CodingEquation(%s) combination as per %s", imageEssenceDescriptorID.toString(), colorPrimaries.name(), transferCharacteristic.name(), codingEquation.name(), applicationCompositionType.toString())); } FrameLayoutType frameLayoutType = imageEssenceDescriptorModel.getFrameLayoutType(); UL essenceContainerFormatUL = imageEssenceDescriptorModel.getEssenceContainerFormatUL(); if(essenceContainerFormatUL != null) { JP2KContentKind contentKind = JP2KContentKind.valueOf(essenceContainerFormatUL.getULAsBytes()[14]); if ((frameLayoutType.equals(FrameLayoutType.FullFrame) && !contentKind.equals(JP2KContentKind.P1)) || (frameLayoutType.equals(FrameLayoutType.SeparateFields) && !contentKind.equals(JP2KContentKind.I1))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid JPEG-2000 ContentKind (%s) indicated by the ContainerFormat as per %s", imageEssenceDescriptorID.toString(), contentKind, applicationCompositionType.toString())); } } } public static void validateImageCharacteristics(CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel, ApplicationCompositionFactory.ApplicationCompositionType applicationCompositionType, IMFErrorLogger imfErrorLogger) { UUID imageEssenceDescriptorID = imageEssenceDescriptorModel.getImageEssencedescriptorID(); ColorModel colorModel = imageEssenceDescriptorModel.getColorModel(); if( !colorModel.equals(ColorModel.RGB) && !colorModel.equals(ColorModel.YUV)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has Invalid color components as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); return; } //storedWidth Integer storedWidth = imageEssenceDescriptorModel.getStoredWidth(); if (storedWidth > MAX_IMAGE_FRAME_WIDTH) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid StoredWidth(%d) as per %s", imageEssenceDescriptorID.toString(), storedWidth, applicationCompositionType.toString())); } //storedHeight Integer storedHeight = imageEssenceDescriptorModel.getStoredHeight(); if (storedHeight > MAX_IMAGE_FRAME_HEIGHT) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid storedHeight(%d) as per %s", imageEssenceDescriptorID.toString(), storedHeight, applicationCompositionType.toString())); } //PixelBitDepth Integer pixelBitDepth = imageEssenceDescriptorModel.getPixelBitDepth(); if( !(pixelBitDepth.equals(8) || pixelBitDepth.equals(10))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s invalid PixelBitDepth(%d) as per %s", imageEssenceDescriptorID.toString(), pixelBitDepth, applicationCompositionType.toString())); } Integer componentDepth = imageEssenceDescriptorModel.getComponentDepth(); if (colorModel.equals(ColorModel.YUV) && !pixelBitDepth.equals(componentDepth)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has a PixelBitDepth(%d) not matching Component Depth (%d) as per %s", imageEssenceDescriptorID.toString(), pixelBitDepth, componentDepth, applicationCompositionType.toString())); } //FrameLayout FrameLayoutType frameLayoutType = imageEssenceDescriptorModel.getFrameLayoutType(); if (!frameLayoutType.equals(FrameLayoutType.FullFrame) && !frameLayoutType.equals(FrameLayoutType.SeparateFields)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid FrameLayout(%s) as per %s", imageEssenceDescriptorID.toString(), frameLayoutType.name(), applicationCompositionType.toString())); } else { //SampleRate Fraction sampleRate = imageEssenceDescriptorModel.getSampleRate(); Set<Fraction> frameRateSupported = frameLayoutType.equals(FrameLayoutType.FullFrame) ? progressiveSampleRateSupported : interlaceSampleRateSupported; if (!frameRateSupported.contains(sampleRate)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has Invalid SampleRate(%s) for frame structure %s as per %s", imageEssenceDescriptorID.toString(), sampleRate.toString(), frameLayoutType.name(), applicationCompositionType.toString())); } } //Sampling Sampling sampling = imageEssenceDescriptorModel.getSampling(); if(frameLayoutType.equals(FrameLayoutType.SeparateFields) && !sampling.equals(Sampling.Sampling422) ) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid combination of FrameLayOut(%s) for Sampling(%s) as per %s", imageEssenceDescriptorID.toString(), frameLayoutType.name(), sampling.name(), applicationCompositionType.toString())); } //Quantization Quantization quantization = imageEssenceDescriptorModel.getQuantization(); Colorimetry color = imageEssenceDescriptorModel.getColor(); if((sampling.equals(Sampling.Sampling422) && !(quantization.equals(Quantization.QE1) && colorModel.equals(ColorModel.YUV))) || (quantization.equals(Quantization.QE2) && !(colorModel.equals(ColorModel.RGB) && color.equals(Colorimetry.Color3)))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid combination of quantization(%s)-Sampling(%s)-colorModel(%s)-color(%s) as per %s", imageEssenceDescriptorID.toString(), quantization.name(), sampling.name(), colorModel.name(), color.name(), applicationCompositionType.toString())); } //Coding UL pictureEssenceCoding = imageEssenceDescriptorModel.getPictureEssenceCodingUL(); if(pictureEssenceCoding.equalsWithMask(JPEG2000PICTURECODINGSCHEME, 0b1111111011111100)) { boolean validProfile = false; if (pictureEssenceCoding.getByte(14) == 0x01) { switch (pictureEssenceCoding.getByte(15)) { case 0x11: /* JPEG2000BroadcastContributionSingleTileProfileLevel1 */ case 0x12: /* JPEG2000BroadcastContributionSingleTileProfileLevel2 */ case 0x13: /* JPEG2000BroadcastContributionSingleTileProfileLevel3 */ case 0x14: /* JPEG2000BroadcastContributionSingleTileProfileLevel4 */ case 0x15: /* JPEG2000BroadcastContributionSingleTileProfileLevel5 */ case 0x16: /* JPEG2000BroadcastContributionMultiTileReversibleProfileLevel6 */ case 0x17: /* JPEG2000BroadcastContributionMultiTileReversibleProfileLevel7 */ validProfile = true; break; default: } } if (! validProfile) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Invalid JPEG 2000 profile: %s", pictureEssenceCoding.toString() )); } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Image codec must be JPEG 2000. Found %s instead.", pictureEssenceCoding.toString() )); } } public ApplicationCompositionType getApplicationCompositionType() { return ApplicationCompositionType.APPLICATION_2_COMPOSITION_TYPE; } }
5,056
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFEssenceComponentVirtualTrack.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.utils.UUIDHelper; import javax.annotation.concurrent.Immutable; import java.util.*; /** * A class that represents Essence Virtual Track. All the resources in this track are of type TrackFileResourceType. */ @Immutable public final class IMFEssenceComponentVirtualTrack extends Composition.VirtualTrack { private final Set<UUID> resourceIds = new HashSet<>(); public IMFEssenceComponentVirtualTrack(UUID trackID, Composition.SequenceTypeEnum sequenceTypeEnum, List<IMFTrackFileResourceType> resourceList, Composition.EditRate compositionEditRate){ super(trackID, sequenceTypeEnum, resourceList, compositionEditRate); for(IMFTrackFileResourceType trackFileResource : resourceList){ this.resourceIds.add(UUIDHelper.fromUUIDAsURNStringToUUID(trackFileResource.getTrackFileId())); } } /** * Getter for the UUIDs of the resources that are a part of this virtual track * @return an unmodifiable set of UUIDs of resources that are a part of this virtual track */ public Set<UUID> getTrackResourceIds() { return Collections.unmodifiableSet(this.resourceIds); } /** * Getter for the resources that are a part of this virtual track * @return an unmodifiable list of resources of type IMFTrackFileResourceType that are a part of this virtual track */ public List<IMFTrackFileResourceType> getTrackFileResourceList() { return (List<IMFTrackFileResourceType>)this.getResourceList(); } }
5,057
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/ApplicationComposition.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.w3c.dom.Node; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * This interface represents a canonical model of the XML type 'CompositionPlaylistType' defined by SMPTE st2067-3, * A Composition object can be constructed from an XML file only if it satisfies all the constraints specified * in st2067-3 and st2067-2. This object model is intended to be agnostic of specific versions of the definitions of a * CompositionPlaylist(st2067-3) and its accompanying Core constraints(st2067-2). */ public interface ApplicationComposition { /** * A method that returns a string representation of a Composition object * * @return string representing the object */ public String toString(); /** * Getter for the composition edit rate as specified in the Composition XML file * * @return the edit rate associated with the Composition */ public Composition.EditRate getEditRate(); /** * Getter method for Annotation child element of CompositionPlaylist * * @return value of Annotation child element or null if it is not exist */ public @Nullable String getAnnotation(); /** * Getter method for Issuer child element of CompositionPlaylist * * @return value of Issuer child element or null if it is not exist */ public @Nullable String getIssuer(); /** * Getter method for Creator child element of CompositionPlaylist * * @return value of Creator child element or null if it is not exist */ public @Nullable String getCreator(); /** * Getter method for ContentOriginator child element of CompositionPlaylist * * @return value of ContentOriginator child element or null if it is not exist */ public @Nullable String getContentOriginator(); /** * Getter method for ContentTitle child element of CompositionPlaylist * * @return value of ContentTitle child element or null if it is not exist */ public @Nullable String getContentTitle(); /** * Getter for the UUID corresponding to this Composition document * * @return the uuid of this Composition object */ public UUID getUUID(); /** * Get the Java package string for the Core Constraints version * @deprecated Instead use {@link #getCoreConstraintsSchema()} * * @return package containing the Core Constraints classes */ @Deprecated public String getCoreConstraintsVersion(); /** * Getter for the Core Constraints schema URI. * @return URI for the Core Constraints schema */ @Nonnull public String getCoreConstraintsSchema(); /** * Getter for the essence VirtualTracks in this Composition * * @return a list of essence virtual tracks that are a part of this composition or an empty list if there are none * track */ @Nullable public List<IMFEssenceComponentVirtualTrack> getEssenceVirtualTracks(); /** * Getter for the video VirtualTrack in this Composition * * @return the video virtual track that is a part of this composition or null if there is not video virtual track */ @Nullable public IMFEssenceComponentVirtualTrack getVideoVirtualTrack(); /** * Getter for the audio VirtualTracks in this Composition * * @return a list of audio virtual tracks that are a part of this composition or an empty list if there are none */ public List<IMFEssenceComponentVirtualTrack> getAudioVirtualTracks(); /** * Getter for the marker VirtualTrack in this Composition * * @return the marker virtual track that is a part of this composition or null if there is no marker virtual track */ @Nullable public IMFMarkerVirtualTrack getMarkerVirtualTrack(); /** * Getter for the errors in Composition * * @return List of errors in Composition. */ public List<ErrorLogger.ErrorObject> getErrors(); /** * A utility method to retrieve the VirtualTracks within a Composition. * * @return A list of VirtualTracks in the Composition. */ @Nonnull public List<? extends Composition.VirtualTrack> getVirtualTracks(); /** * A utility method to retrieve the EssenceDescriptors within a Composition. * * @return A list of EssenceDescriptors in the Composition. */ @Nonnull public List<DOMNodeObjectModel> getEssenceDescriptors(); /** * A utility method to retrieve the EssenceDescriptors within a Composition based on the name. * * @param descriptorName EssenceDescriptor name * @return A list of DOMNodeObjectModels representing EssenceDescriptors with given name. */ @Nonnull List<DOMNodeObjectModel> getEssenceDescriptors(String descriptorName); /** * A utility method to retrieve the EssenceDescriptor within a Composition for a Resource with given track file ID. * * @param trackFileId the track file id of the resource * @return the DOMNodeObjectModel representing the EssenceDescriptor */ @Nullable DOMNodeObjectModel getEssenceDescriptor(UUID trackFileId); public Map<Set<DOMNodeObjectModel>, ? extends Composition.VirtualTrack> getAudioVirtualTracksMap(); /** * This method can be used to determine if a Composition is conformant. Conformance checks * perform deeper inspection of the Composition and the EssenceDescriptors corresponding to the * resources referenced by the Composition. * * @param headerPartitionTuples list of HeaderPartitionTuples corresponding to the IMF essences referenced in the Composition * @param conformAllVirtualTracksInCpl a boolean that turns on/off conforming all the VirtualTracks in the Composition * @return boolean to indicate of the Composition is conformant or not * @throws IOException - any I/O related error is exposed through an IOException. */ public List<ErrorLogger.ErrorObject> conformVirtualTracksInComposition(List<Composition.HeaderPartitionTuple> headerPartitionTuples, boolean conformAllVirtualTracksInCpl) throws IOException; /** * A method to get Application Composition type. * * @return Application Composition Type */ ApplicationCompositionType getApplicationCompositionType(); /** * A method to get Composition image essence descriptor model * * @return Application CompositionImageEssenceDescriptorModel */ @Nullable CompositionImageEssenceDescriptorModel getCompositionImageEssenceDescriptorModel(); /** * A method to get map of essence descriptor dom nodes * * @return Map containing mapping between Track file ID to essence descriptor DOM node list */ public Map<UUID, List<Node>> getEssenceDescriptorDomNodeMap(); /** * A method that confirms if the inputStream corresponds to a Composition document instance. * * @param resourceByteRangeProvider corresponding to the Composition XML file. * @return a boolean indicating if the input file is a Composition document * @throws IOException - any I/O related error is exposed through an IOException */ public static boolean isCompositionPlaylist(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { return AbstractApplicationComposition.isCompositionPlaylist(resourceByteRangeProvider); } }
5,058
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/CompositionImageEssenceDescriptorModel.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.Colorimetry; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.RGBAComponentType; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.Fraction; import com.netflix.imflibrary.utils.RegXMLLibDictionary; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import static com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.*; import static com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.RGBAComponentType.Null; import static com.netflix.imflibrary.Colorimetry.*; /** * Created by svenkatrav on 11/2/16. */ public final class CompositionImageEssenceDescriptorModel { private final UUID imageEssencedescriptorID; private final DOMNodeObjectModel imageEssencedescriptorDOMNode; private final RegXMLLibDictionary regXMLLibDictionary; private final IMFErrorLogger imfErrorLogger; private final ColorModel colorModel; private final FrameLayoutType frameLayoutType; private final Integer storedWidth ; private final Integer storedHeight; private final Fraction sampleRate; private final Integer pixelBitDepth; private final Integer componentDepth; private final Colorimetry.Quantization quantization; private final Colorimetry color; private final Colorimetry.Sampling sampling; private final Integer storedOffset; private final Integer sampleWidth; private final Integer sampleHeight; private final CodingEquation codingEquation; private final TransferCharacteristic transferCharacteristic; private final ColorPrimaries colorPrimaries; private final UL essenceContainerFormatUL; private final UL pictureEssenceCodingUL; // items constrained in 2065-5 private final Integer signalStandard; private final Integer sampledXOffset; private final Integer sampledYOffset; private final Integer displayWidth; private final Integer displayHeight; private final Integer displayXOffset; private final Integer displayYOffset; private final Integer displayF2Offset; private final Fraction imageAspectRatio; private final Integer activeFormatDescriptor; private final Integer alphaTransparency; private final Integer imageAlignmentOffset; private final Integer imageStartOffset; private final Integer imageEndOffset; private final Integer fieldDominance; private final UL codingEquations; private final Integer componentMinRef; private final Integer componentMaxRef; private final Integer alphaMinRef; private final Integer alphaMaxRef; private final Integer scanningDirection; private final String palette; private final String paletteLayout; public CompositionImageEssenceDescriptorModel(@Nonnull UUID imageEssencedescriptorID, @Nonnull DOMNodeObjectModel imageEssencedescriptorDOMNode, @Nonnull RegXMLLibDictionary regXMLLibDictionary) { this.imageEssencedescriptorDOMNode = imageEssencedescriptorDOMNode; this.imageEssencedescriptorID = imageEssencedescriptorID; this.regXMLLibDictionary = regXMLLibDictionary; this.imfErrorLogger = new IMFErrorLoggerImpl(); if (imageEssencedescriptorDOMNode.getLocalName().equals(regXMLLibDictionary.getSymbolNameFromURN(rgbaDescriptorUL))) { this.colorModel = ColorModel.RGB; } else if (imageEssencedescriptorDOMNode.getLocalName().equals(regXMLLibDictionary.getSymbolNameFromURN(cdciDescriptorUL))) { this.colorModel = ColorModel.YUV; } else { this.colorModel = ColorModel.Unknown; } this.frameLayoutType = FrameLayoutType.valueOf(regXMLLibDictionary.getEnumerationValueFromName(frameLayoutTypeUL, getFieldAsString(frameLayoutUL))); Integer storedWidth = getFieldAsInteger(storedWidthUL); storedWidth = storedWidth != null ? storedWidth : -1; this.storedWidth = storedWidth; Integer storedHeight = getFieldAsInteger(storedHeightUL); storedHeight = storedHeight != null ? storedHeight : -1; this.storedHeight = storedHeight; Fraction sampleRate = getFieldAsFraction(sampleRateUL); sampleRate = sampleRate != null ? sampleRate : new Fraction(0); this.sampleRate = sampleRate; this.storedOffset = getFieldAsInteger(storedF2OffsetUL); this.sampleHeight = getFieldAsInteger(sampledHeightUL); this.sampleWidth = getFieldAsInteger(sampledWidthUL); this.componentDepth = getFieldAsInteger(componentDepthUL); this.transferCharacteristic = Colorimetry.TransferCharacteristic.valueOf(imageEssencedescriptorDOMNode.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN (transferCharacteristicUL))); this.colorPrimaries = Colorimetry.ColorPrimaries.valueOf(imageEssencedescriptorDOMNode.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN(colorPrimariesUL))); if(colorModel.equals(ColorModel.YUV)) { this.codingEquation = Colorimetry.CodingEquation.valueOf(imageEssencedescriptorDOMNode.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN(codingEquationsUL))); } else { this.codingEquation = CodingEquation.None; } this.essenceContainerFormatUL = imageEssencedescriptorDOMNode.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN(containerFormatUL)); this.pictureEssenceCodingUL = imageEssencedescriptorDOMNode.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN(GenericPictureEssenceDescriptor.pictureEssenceCodingUL)); // begin Items constrained in ST2065-5 this.signalStandard = getFieldAsInteger(signalStandardUL); this.sampledXOffset = getFieldAsInteger(sampledXOffsetUL); this.sampledYOffset = getFieldAsInteger(sampledYOffsetUL); Integer displayWidth = getFieldAsInteger(displayWidthUL); this.displayWidth = displayWidth != null ? displayWidth : -1; Integer displayHeight = getFieldAsInteger(displayHeightUL); this.displayHeight = displayHeight != null ? displayHeight : -1; this.displayXOffset = getFieldAsInteger(displayXOffsetUL); this.displayYOffset = getFieldAsInteger(displayYOffsetUL); this.displayF2Offset = getFieldAsInteger(displayF2OffsetUL); this.imageAspectRatio = getFieldAsFraction(imageAspectRatioUL); this.activeFormatDescriptor = getFieldAsInteger(activeFormatDescriptorUL); this.alphaTransparency = getFieldAsInteger(alphaTransparencyUL); this.imageAlignmentOffset = getFieldAsInteger(imageAlignmentOffsetUL); this.imageStartOffset = getFieldAsInteger(imageStartOffsetUL); this.imageEndOffset = getFieldAsInteger(imageEndOffsetUL); this.fieldDominance = getFieldAsInteger(fieldDominanceUL); this.codingEquations = imageEssencedescriptorDOMNode.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN(codingEquationsUL)); this.componentMinRef = getFieldAsInteger(componentMinRefUL); this.componentMaxRef = getFieldAsInteger(componentMaxRefUL); this.alphaMinRef = getFieldAsInteger(alphaMinRefUL); this.alphaMaxRef = getFieldAsInteger(alphaMaxRefUL); this.scanningDirection = getFieldAsInteger(scanningDirectionUL); this.palette = getFieldAsString(paletteUL); this.paletteLayout = getFieldAsString(paletteLayoutUL); // end Items constrained in ST2065-5 UL MXFGCFrameWrappedACESPictures = UL.fromULAsURNStringToUL("urn:smpte:ul:060e2b34.0401010d.0d010301.02190100"); // MXF-GC Frame-wrapped ACES Pictures per 2065-5 if(!this.colorModel.equals(ColorModel.Unknown)) { if ((this.essenceContainerFormatUL != null) && getEssenceContainerFormatUL().equals(MXFGCFrameWrappedACESPictures) ) { // App #5 if(colorModel.equals(ColorModel.RGB)) { this.pixelBitDepth = null; this.quantization = Quantization.Unknown; this.color = Colorimetry.valueOf(this.colorPrimaries, this.transferCharacteristic); this.sampling = Sampling.Unknown; parseApp5SubDescriptors(); parseApp5PixelLayout(); parseApp5VideoLineMap(); } else { this.pixelBitDepth = null; this.quantization = Quantization.Unknown; this.color = Colorimetry.Unknown; this.sampling = Sampling.Unknown; } } else { // App #2/#2E this.pixelBitDepth = parsePixelBitDepth(this.colorModel); this.quantization = parseQuantization(this.colorModel, this.pixelBitDepth); Colorimetry color = Colorimetry.valueOf(this.colorPrimaries, this.transferCharacteristic); if((colorModel.equals(ColorModel.YUV) && !color.getCodingEquation().equals(this.codingEquation))) { color = Colorimetry.Unknown; } this.color = color; this.sampling = parseSampling(this.colorModel); } } else { this.pixelBitDepth = null; this.quantization = Quantization.Unknown; this.color = Colorimetry.Unknown; this.sampling = Sampling.Unknown; } } public @Nonnull UUID getImageEssencedescriptorID() { return imageEssencedescriptorID; } public @Nonnull FrameLayoutType getFrameLayoutType() { return frameLayoutType; } public @Nonnull ColorModel getColorModel() { return colorModel; } public @Nonnull Colorimetry getColor() { return color; } public @Nonnull Fraction getSampleRate() { return sampleRate; } public Integer getComponentDepth() { return componentDepth; } public @Nonnull Integer getPixelBitDepth() { return pixelBitDepth; } public @Nonnull Integer getStoredHeight() { return storedHeight; } public @Nonnull Integer getStoredWidth() { return storedWidth; } public @Nonnull Colorimetry.Quantization getQuantization() { return quantization; } public @Nonnull Colorimetry.Sampling getSampling() { return sampling; } public @Nullable Integer getStoredOffset() { return storedOffset; } public @Nullable Integer getSampleHeight() { return sampleHeight; } public @Nullable Integer getSampleWidth() { return sampleWidth; } public @Nonnull List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } public CodingEquation getCodingEquation() { return codingEquation; } public ColorPrimaries getColorPrimaries() { return colorPrimaries; } public TransferCharacteristic getTransferCharacteristic() { return transferCharacteristic; } public @Nullable UL getEssenceContainerFormatUL() { return essenceContainerFormatUL; } public @Nullable UL getPictureEssenceCodingUL() { return pictureEssenceCodingUL; } private @Nullable String getFieldAsString(@Nonnull String urn) { return imageEssencedescriptorDOMNode.getFieldAsString(regXMLLibDictionary.getSymbolNameFromURN(urn)); } private @Nullable Integer getFieldAsInteger(@Nonnull String urn) { return imageEssencedescriptorDOMNode.getFieldAsInteger(regXMLLibDictionary.getSymbolNameFromURN(urn)); } private @Nullable Long getFieldAsLong(@Nonnull String urn) { return imageEssencedescriptorDOMNode.getFieldAsLong(regXMLLibDictionary.getSymbolNameFromURN(urn)); } private @Nullable Fraction getFieldAsFraction(@Nonnull String urn) { return imageEssencedescriptorDOMNode.getFieldAsFraction(regXMLLibDictionary.getSymbolNameFromURN(urn)); } public @Nullable Integer getSignalStandard() { return signalStandard; } public @Nullable Integer getSampledXOffset() { return sampledXOffset; } public @Nullable Integer getSampledYOffset() { return sampledYOffset; } public @Nonnull Integer getDisplayWidth() { return displayWidth; } public @Nonnull Integer getDisplayHeight() { return displayHeight; } public @Nullable Integer getDisplayXOffset() { return displayXOffset; } public @Nullable Integer getDisplayYOffset() { return displayYOffset; } public @Nullable Integer getDisplayF2Offset() { return displayF2Offset; } public @Nullable Fraction getImageAspectRatio() { return imageAspectRatio; } public @Nullable Integer getActiveFormatDescriptor() { return activeFormatDescriptor; } public @Nullable Integer getAlphaTransparency() { return alphaTransparency; } public @Nullable Integer getImageAlignmentOffset() { return imageAlignmentOffset; } public @Nullable Integer getImageStartOffset() { return imageStartOffset; } public @Nullable Integer getImageEndOffset() { return imageEndOffset; } public @Nullable Integer getFieldDominance() { return fieldDominance; } public @Nullable UL getCodingEquations() { return codingEquations; } public @Nullable Integer getComponentMinRef() { return componentMinRef; } public @Nullable Integer getComponentMaxRef() { return componentMaxRef; } public @Nullable Integer getAlphaMinRef() { return alphaMinRef; } public @Nullable Integer getAlphaMaxRef() { return alphaMaxRef; } public @Nullable Integer getScanningDirection() { return scanningDirection; } public @Nullable String getPalette() { return palette; } public @Nullable String getPaletteLayout() { return paletteLayout; } private @Nonnull Integer parsePixelBitDepth(@Nonnull ColorModel colorModel) { Integer refPixelBitDepth = null; DOMNodeObjectModel subDescriptors = imageEssencedescriptorDOMNode.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(subdescriptorsUL)); if (subDescriptors == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing SubDescriptors", imageEssencedescriptorID.toString())); } else { DOMNodeObjectModel jpeg2000SubdescriptorDOMNode = subDescriptors.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(jpeg2000SubDescriptorUL)); if (jpeg2000SubdescriptorDOMNode == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing JPEG2000SubDescriptor in SubDescriptors", imageEssencedescriptorID.toString())); } else { DOMNodeObjectModel j2cLayout = jpeg2000SubdescriptorDOMNode.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(j2cLayoutUL)); if (j2cLayout == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing J2CLayout in JPEG2000SubDescriptor", imageEssencedescriptorID.toString())); } else { List<DOMNodeObjectModel> rgbaComponents = j2cLayout.getDOMNodes(regXMLLibDictionary.getSymbolNameFromURN(rgbaComponentUL)); if (rgbaComponents.size() == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing RGBAComponent in J2CLayout", imageEssencedescriptorID.toString())); } else { Map<RGBAComponentType, Integer> componentMap = new HashMap<>(); for (DOMNodeObjectModel domNodeObjectModel : rgbaComponents) { String code = domNodeObjectModel.getFieldAsString(regXMLLibDictionary.getTypeFieldNameFromURN(rgbaComponentUL, codeUL)); if (code == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has an RGBAComponent with missing Code", imageEssencedescriptorID.toString())); } else { RGBAComponentType codeValue = RGBAComponentType.valueOf(regXMLLibDictionary.getEnumerationValueFromName(rgbaComponentKindUL, code)); Integer pixelBitDepth = domNodeObjectModel.getFieldAsInteger(regXMLLibDictionary.getTypeFieldNameFromURN(rgbaComponentUL, componentSizeUL)); if (pixelBitDepth == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has an RGBAComponent %s with missing ComponentSize", imageEssencedescriptorID.toString(), code)); } else { if (refPixelBitDepth == null) { refPixelBitDepth = pixelBitDepth; } if ((codeValue.equals(Null) && pixelBitDepth != 0) || (!codeValue.equals(Null) && (!pixelBitDepth.equals(refPixelBitDepth)))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has an RGBAComponent %s with invalid ComponentSize %d", imageEssencedescriptorID.toString(), code, pixelBitDepth)); } } if (componentMap.containsKey(codeValue)) { Integer count = componentMap.get(codeValue); componentMap.put(codeValue, count + 1); } else { componentMap.put(codeValue, 1); } } } componentMap.entrySet().stream().forEach( e -> { if (e.getKey().equals(RGBAComponentType.Null)) { if (!e.getValue().equals(5)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s and ColorModel %s has invalid number of RGBAComponent %s in J2CLayout", imageEssencedescriptorID.toString(), colorModel.name(), e.getKey())); } } else if (!colorModel.getComponentTypeSet().contains(e.getKey())) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s and ColorModel %s has invalid RGBAComponent %s in J2CLayout", imageEssencedescriptorID.toString(), colorModel.name(), e.getKey())); } else if (!e.getValue().equals(1)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s and ColorModel %s has more than one RGBAComponent %s in J2CLayout", imageEssencedescriptorID.toString(), colorModel.name(), e.getKey())); } } ); } } } } return refPixelBitDepth != null ? refPixelBitDepth : 0; } private @Nonnull Quantization parseQuantization(@Nonnull ColorModel colorModel, @Nonnull Integer pixelBitDepth) { Quantization quantization = Quantization.Unknown; Long signalMin = null; Long signalMax = null; if(colorModel.equals(ColorModel.RGB)) { signalMin = getFieldAsLong(componentMinRefUL); signalMax = getFieldAsLong(componentMaxRefUL); if (signalMax == null || signalMin == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing ComponentMinRef/ComponentMaxRef in Image Essence Descriptor", imageEssencedescriptorID.toString())); } } else if(colorModel.equals(ColorModel.YUV)) { signalMin = getFieldAsLong(blackRefLevelUL); signalMax = getFieldAsLong(whiteRefLevelUL); if (signalMax == null || signalMin == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing BlackRefLevel/WhiteRefLevel in Image Essence Descriptor", imageEssencedescriptorID.toString())); } } if(signalMax != null && signalMin != null) { quantization = Colorimetry.Quantization.valueOf(pixelBitDepth, signalMin, signalMax); if(quantization.equals(Quantization.Unknown)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid combination of ComponentMinRef/BlackRefLevel(%d)-ComponentMaxRef/WhiteRefLevel(%d)-PixelBitDepth(%d) in Image " + "Essence Descriptor", imageEssencedescriptorID.toString(), signalMin, signalMax, pixelBitDepth )); } } return quantization; } private @Nonnull Sampling parseSampling(@Nonnull ColorModel colorModel) { Colorimetry.Sampling sampling = Sampling.Unknown; if(colorModel.equals(ColorModel.RGB)) { return Colorimetry.Sampling.Sampling444; } else { Integer horizontalSubSampling = getFieldAsInteger(horizontalSubSamplingUL); Integer verticalSubSampling = getFieldAsInteger(verticalSubSamplingUL); if (horizontalSubSampling == null || verticalSubSampling == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing HorizontalSubSampling/VerticalSubSampling in Image Essence Descriptor", imageEssencedescriptorID.toString())); } else { sampling = Colorimetry.Sampling.valueOf(horizontalSubSampling, verticalSubSampling); if(sampling.equals(Sampling.Unknown)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid combination of HorizontalSubSampling(%d)-VerticalSubSampling(%d) in Image " + "Essence Descriptor", imageEssencedescriptorID.toString(), horizontalSubSampling, verticalSubSampling)); } } } return sampling; } private void parseApp5SubDescriptors() { DOMNodeObjectModel subDescriptors = imageEssencedescriptorDOMNode.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(subdescriptorsUL)); if (subDescriptors != null) { List<DOMNodeObjectModel> acesPictureSubDescriptors = subDescriptors.getDOMNodes(regXMLLibDictionary.getSymbolNameFromURN(acesPictureSubDescriptorUL)); List<DOMNodeObjectModel> targetFrameSubDescriptors = subDescriptors.getDOMNodes(regXMLLibDictionary.getSymbolNameFromURN(targetFrameSubDescriptorUL)); List<DOMNodeObjectModel> containerConstraintsSubDescriptors = subDescriptors.getDOMNodes(regXMLLibDictionary.getSymbolNameFromURN(containerConstraintsSubDescriptorUL)); if (!acesPictureSubDescriptors.isEmpty()) { for (DOMNodeObjectModel domNodeObjectModel : acesPictureSubDescriptors) { String authoring_information = domNodeObjectModel.getFieldAsString(regXMLLibDictionary.getSymbolNameFromURN(acesAuthoringInformationUL)); if ((authoring_information == null) || authoring_information.isEmpty()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("ACES Picture SubDescriptor (ID %s): Optional item ACES Authoring Information is not present or empty", domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString())); } DOMNodeObjectModel primaries = domNodeObjectModel.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(acesMasteringDisplayPrimariesUL)); DOMNodeObjectModel whitePoint = domNodeObjectModel.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(acesMasteringDisplayWhitePointChromaticityUL)); Integer maxLum = domNodeObjectModel.getFieldAsInteger(regXMLLibDictionary.getSymbolNameFromURN(acesMasteringDisplayDisplayMaximumLuminanceUL)); Integer minLum = domNodeObjectModel.getFieldAsInteger(regXMLLibDictionary.getSymbolNameFromURN(acesMasteringDisplayDisplayMinimumLuminanceUL)); if (!(((primaries == null) && (whitePoint == null) && (maxLum == null) && (minLum == null)) || ((primaries != null) && (whitePoint != null) && (maxLum != null) && (minLum != null)))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("ACES Picture SubDescriptor (ID %s) shall have either all or none of the following elements: Mastering Display Primaries, White Point, Maximum Luminance, Minimum Luminance", domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString())); } } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("INFO (can be ignored): EssenceDescriptor with ID %s: No ACESPictureSubDescriptor found", imageEssencedescriptorID.toString())); } if (!targetFrameSubDescriptors.isEmpty()) { for (DOMNodeObjectModel domNodeObjectModel : targetFrameSubDescriptors) { String missing_items = ""; Set<UUID> targetFrameAncillaryResourceID = domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(targetFrameAncillaryResourceIDUL)); // Check for missing required items if (targetFrameAncillaryResourceID.isEmpty()) { missing_items += "TargetFrameAncillaryResourceID, "; } else { //TODO Check it targetFrameAncillaryResourceID belongs to an existing GSP imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("INFO (can be ignored): Target FrameSubDescriptor (ID %s) references an Ancillary Resource (ID %s), but Ancillary Resources cannot be checked yet", domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString(), targetFrameAncillaryResourceID.toString())); } String media_type = domNodeObjectModel.getFieldAsString(regXMLLibDictionary.getSymbolNameFromURN(mediaTypeUL)); if (media_type == null) { missing_items += "MediaType, "; } Long index = domNodeObjectModel.getFieldAsLong(regXMLLibDictionary.getSymbolNameFromURN(targetFrameIndexUL)); if (index == null) { missing_items += "TargetFrameIndex, "; } UL transfer = domNodeObjectModel.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN(targetFrameTransferCharacteristicUL)); if (transfer == null) { missing_items += "TargetFrameTransferCharacteristic, "; } UL color = domNodeObjectModel.getFieldAsUL(regXMLLibDictionary.getSymbolNameFromURN(targetFrameColorPrimariesUL)); if (color == null) { missing_items += "TargetFrameColorPrimaries, "; } Integer max_ref = domNodeObjectModel.getFieldAsInteger(regXMLLibDictionary.getSymbolNameFromURN(targetFrameComponentMaxRefUL)); if (max_ref == null) { missing_items += "TargetFrameComponentMaxRef, "; } Integer min_ref = domNodeObjectModel.getFieldAsInteger(regXMLLibDictionary.getSymbolNameFromURN(targetFrameComponentMinRefUL)); if (min_ref == null) { missing_items += "TargetFrameComponentMinRef, "; } Integer stream_id = domNodeObjectModel.getFieldAsInteger(regXMLLibDictionary.getSymbolNameFromURN(targetFrameEssenceStreamIDUL)); if (stream_id == null) { missing_items += "TargetFrameEssenceStreamID"; } if (!missing_items.isEmpty()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Target FrameSubDescriptor (ID %s): is missing required item(s): %s", domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString(), missing_items)); } // Check if acesPictureSubDescriptorInstanceID references an existing ACESPictureSubDescriptor Instance ID Set<UUID> acesPictureSubDescriptorInstanceID = domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(acesPictureSubDescriptorInstanceIDUL)); if (!acesPictureSubDescriptorInstanceID.isEmpty()) { if (acesPictureSubDescriptors.isEmpty()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Target FrameSubDescriptor (ID %s) references an ACESPictureSubDescriptorInstanceID (%s) but no ACESPictureSubDescriptor is present", domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString(), acesPictureSubDescriptorInstanceID.toString())); } else { if (acesPictureSubDescriptors.stream().noneMatch(e -> e.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).equals(acesPictureSubDescriptorInstanceID))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Target FrameSubDescriptor (ID %s) references an ACESPictureSubDescriptor but no ACESPictureSubDescriptor with Instance ID (%s) is present", domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString(), acesPictureSubDescriptorInstanceID.toString())); } } } if ((max_ref != null) && (min_ref != null)) { if (max_ref <= min_ref) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Target FrameSubDescriptor (ID %s): TargetFrameComponentMaxRef (%d) is less than or equal to TargetFrameComponentMaxRef (%d)", domNodeObjectModel.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString(), max_ref, min_ref)); } } } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("INFO (can be ignored): EssenceDescriptor with ID %s: No TargetFrameSubDescriptor found", imageEssencedescriptorID.toString())); } if (containerConstraintsSubDescriptors.isEmpty()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("EssenceDescriptor with ID %s: A ContainerConstraintsSubDescriptor shall be present per ST 379-2, but is missing", imageEssencedescriptorID.toString())); } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("INFO (can be ignored): EssenceDescriptor with ID %s: No ACESPictureSubDescriptor and no TargetFrameSubDescriptor found", imageEssencedescriptorID.toString())); } return; } private void parseApp5VideoLineMap() { DOMNodeObjectModel videoLineMap = imageEssencedescriptorDOMNode.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(videoLineMapUL)); if (videoLineMap == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall have a Video Line Map item", imageEssencedescriptorID.toString())); } } private void parseApp5PixelLayout() { DOMNodeObjectModel pixelLayout = imageEssencedescriptorDOMNode.getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(pixelLayoutUL)); if (pixelLayout == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall have a Pixel Layout item", imageEssencedescriptorID.toString())); } else { List<DOMNodeObjectModel> rgbaComponents = pixelLayout.getDOMNodes(regXMLLibDictionary.getSymbolNameFromURN(rgbaComponentUL)); if (rgbaComponents.size() == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s is missing RGBAComponent in Pixel Layout", imageEssencedescriptorID.toString())); } else { Map<RGBAComponentType, Integer> componentMap = new LinkedHashMap<>(); List<RGBAComponentType> componentList = new ArrayList<>(); for (DOMNodeObjectModel domNodeObjectModel : rgbaComponents) { String code = domNodeObjectModel.getFieldAsString(regXMLLibDictionary.getTypeFieldNameFromURN(rgbaComponentUL, codeUL)); if (code == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has a Pixel Layout item with an RGBAComponent with missing Code", imageEssencedescriptorID.toString())); } else { RGBAComponentType codeValue = RGBAComponentType.valueOf(regXMLLibDictionary.getEnumerationValueFromName(rgbaComponentKindUL, code)); Integer pixelBitDepth = domNodeObjectModel.getFieldAsInteger(regXMLLibDictionary.getTypeFieldNameFromURN(rgbaComponentUL, componentSizeUL)); if (pixelBitDepth == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has a Pixel Layout item with an RGBAComponent %s with missing Depth", imageEssencedescriptorID.toString(), code)); } else { if ((codeValue.equals(Null) && pixelBitDepth != 0) || (!codeValue.equals(Null) && (!pixelBitDepth.equals(253)))) { // In App#5, all components are of type HALF FLOAT imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has a Pixel Layout item %s with invalid Depth value %d (expected depth value: 253)", imageEssencedescriptorID.toString(), code, pixelBitDepth)); } } if (componentMap.containsKey(codeValue)) { Integer count = componentMap.get(codeValue); componentMap.put(codeValue, count + 1); } else { componentMap.put(codeValue, 1); componentList.add(codeValue); } } } boolean error = true; if (componentList.size() >= 4) { // ABGR or BGR per 2067-50 plus Null if (componentList.get(0).toString().equals("Alpha")) { // ABGR per 2067-50 if (componentList.get(1).toString().equals("Blue") || componentList.get(2).toString().equals("Green") || componentList.get(3).toString().equals("Red") ) error = false; } else if (componentList.get(0).toString().equals("Blue")) { // BGR per 2067-50 if (componentList.get(1).toString().equals("Green") || componentList.get(2).toString().equals("Red")) error = false; } } if (error) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has incorrect PixelLayout %s", imageEssencedescriptorID.toString(), componentList.toString())); } componentMap.entrySet().stream().forEach( e -> { if (e.getKey().equals(RGBAComponentType.Null)) { if (!(e.getValue().equals(5) || e.getValue().equals(4))) { // ABGR or BGR per 2067-50 imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s and ColorModel %s has invalid number of RGBAComponent %s in J2CLayout", imageEssencedescriptorID.toString(), colorModel.name(), e.getKey())); } } else if (!e.getValue().equals(1)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has more than one RGBAComponent %s in Pixel Layout", imageEssencedescriptorID.toString(), e.getKey())); } } ); } } } }
5,059
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFSequenceType.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; /** * A class that models Sequence structure of an IMF Composition Playlist. */ @Immutable final class IMFSequenceType { protected final String id; protected final String trackId; protected final List<? extends IMFBaseResourceType> resourceList; protected final Composition.SequenceTypeEnum type; public IMFSequenceType(String id, String trackId, Composition.SequenceTypeEnum type, List<? extends IMFBaseResourceType> resourceList) { this.id = id; this.trackId = trackId; this.resourceList = Collections.unmodifiableList(resourceList); this.type = type; } /** * Getter for the Sequence ID * @return a string representing the urn:uuid of the sequence */ public String getId(){ return this.id; } /** * Getter for the Sequence track ID * @return a string representing the track ID of the sequence */ public String getTrackId(){ return this.trackId; } /** * Getter for the Sequence type * @return a enum representing sequence type */ public Composition.SequenceTypeEnum getType(){ return this.type; } /** * Getter for the Resource list * @return a list containing all the resources of the Sequence */ public List<? extends IMFBaseResourceType> getResourceList(){ return this.resourceList; } }
5,060
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/Application5Composition.java
/* * * Copyright 2019 RheinMain University of Applied Sciences, Wiesbaden, Germany. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.Colorimetry; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.RGBAComponentType; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.Fraction; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.*; import javax.annotation.Nonnull; import org.w3c.dom.Node; import java.util.*; import java.util.function.BiConsumer; import java.util.stream.Collectors; import static com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.*; import static com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.RGBAComponentType.Null; import static com.netflix.imflibrary.Colorimetry.*; /** * A class that models Composition with Application 5 constraints from 2067-50 specification */ public class Application5Composition extends AbstractApplicationComposition { public static final String SCHEMA_URI_APP5_2017 = "http://www.smpte-ra.org/ns/2067-50/2017"; public static final Integer MAX_RGB_IMAGE_FRAME_WIDTH = Integer.MAX_VALUE; //TODO: 2067-50 specifies 2^32-1, would require using Long instead of Integer public static final Integer MAX_RGB_IMAGE_FRAME_HEIGHT = Integer.MAX_VALUE; //TODO: 2067-50 specifies 2^32-1, would require using Long instead of Integer public static final Map<Colorimetry, Set<Integer>>colorToBitDepthMap = Collections.unmodifiableMap(new HashMap<Colorimetry, Set<Integer>>() {{ put(Colorimetry.Unknown, new HashSet<Integer>(){{ }}); put(Colorimetry.Color_App5_AP0, new HashSet<Integer>(){{ add(16); }}); }}); public static final Set<Integer>bitDepthsSupported = Collections.unmodifiableSet(new HashSet<Integer>() {{ add(16); }}); private static final Set<String> ignoreSet = Collections.unmodifiableSet(new HashSet<String>() {{ }}); private static final Set<String> acesPictureSubDescriptorHomogeneitySelectionSet = Collections.unmodifiableSet(new HashSet<String>(){{ add("ACESAuthoringInformation"); }}); public Application5Composition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType) { this(imfCompositionPlaylistType, new HashSet<>()); } public Application5Composition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType, Set<String> homogeneitySelectionSet) { super(imfCompositionPlaylistType, ignoreSet, homogeneitySelectionSet); try { List<DOMNodeObjectModel> virtualTrackEssenceDescriptors = this.getEssenceDescriptors("RGBADescriptor").stream() .distinct() .collect(Collectors.toList()); if (virtualTrackEssenceDescriptors.isEmpty()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("No RGBA Picture Essence Descriptor found in APPLICATION_5_COMPOSITION_TYPE.")); return; } List<DOMNodeObjectModel> refAcesPictureSubDescriptors = new ArrayList<>(); int indexFirstAcesPictureSubdescriptor = 0; boolean areAcesPictureSubDecriptorsHomogeneous = true; List<String> inhomogeneousEssenceDescriptorIds = new ArrayList<>(); do { // Find first appearance of an ACESPictureSubDescriptor, if any DOMNodeObjectModel subDescriptors = virtualTrackEssenceDescriptors.get(indexFirstAcesPictureSubdescriptor).getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(subdescriptorsUL)); List<DOMNodeObjectModel> acesPictureSubDescriptors = subDescriptors.getDOMNodes(regXMLLibDictionary.getSymbolNameFromURN(acesPictureSubDescriptorUL)); for (DOMNodeObjectModel desc : acesPictureSubDescriptors) { DOMNodeObjectModel refAcesPictureSubDescriptor = desc.createDOMNodeObjectModelSelectionSet(desc, acesPictureSubDescriptorHomogeneitySelectionSet); refAcesPictureSubDescriptors.add(refAcesPictureSubDescriptor); } indexFirstAcesPictureSubdescriptor++; } while (refAcesPictureSubDescriptors.isEmpty() && (indexFirstAcesPictureSubdescriptor < virtualTrackEssenceDescriptors.size())); if ((indexFirstAcesPictureSubdescriptor == 1) && (!refAcesPictureSubDescriptors.isEmpty())) { // ACESPicture SubDescriptor(s) present in first resource for (int i = 1; i < virtualTrackEssenceDescriptors.size(); i++) { DOMNodeObjectModel subDescriptors = virtualTrackEssenceDescriptors.get(i).getDOMNode(regXMLLibDictionary.getSymbolNameFromURN(subdescriptorsUL)); List<DOMNodeObjectModel> other = subDescriptors.getDOMNodes(regXMLLibDictionary.getSymbolNameFromURN(acesPictureSubDescriptorUL)); DOMNodeObjectModel refAcesPictureSubDescriptor = virtualTrackEssenceDescriptors.get(i).createDOMNodeObjectModelSelectionSet(virtualTrackEssenceDescriptors.get(i), acesPictureSubDescriptorHomogeneitySelectionSet); if (other.size() != refAcesPictureSubDescriptors.size()) { // Number of ACESPictureSubDescriptors is different areAcesPictureSubDecriptorsHomogeneous = false; inhomogeneousEssenceDescriptorIds.add(virtualTrackEssenceDescriptors.get(i).getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString()); } else { for (DOMNodeObjectModel desc : other) { DOMNodeObjectModel selectOther = desc.createDOMNodeObjectModelSelectionSet(desc, acesPictureSubDescriptorHomogeneitySelectionSet); if (!refAcesPictureSubDescriptors.contains(selectOther)) { // Value of Field ACESAuthoringInformation is different areAcesPictureSubDecriptorsHomogeneous = false; inhomogeneousEssenceDescriptorIds.add(virtualTrackEssenceDescriptors.get(i).getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString()); } } } } } else if (indexFirstAcesPictureSubdescriptor > 1 ) { // Inhomogeneous: First subdescriptor does not contain an ACESPictureSubDescriptor, but others do areAcesPictureSubDecriptorsHomogeneous = false; DOMNodeObjectModel firstOccurence = virtualTrackEssenceDescriptors.get(indexFirstAcesPictureSubdescriptor-1); if (firstOccurence != null) { inhomogeneousEssenceDescriptorIds.add(firstOccurence.getFieldsAsUUID(regXMLLibDictionary.getSymbolNameFromURN(instanceID)).toString()); } } if (!areAcesPictureSubDecriptorsHomogeneous) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("ACESPictureSubDescriptors shall be homogeneous per Draft Academy Digital Source Master Specification S-2018-001, mismatch occured in essence (sub)descriptor(s) %s.", inhomogeneousEssenceDescriptorIds.toString())); } // Validate all Essence Descriptors, because ACES sub-descriptors are not required to be homogeneous for all elements, in particular the TargetFrameSubDescriptors may differ per ST 2067-50. for(DOMNodeObjectModel imageEssencedescriptorDOMNode : virtualTrackEssenceDescriptors){ CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel = null; UUID imageEssenceDescriptorID = this.getEssenceDescriptorListMap().entrySet().stream().filter(e -> e.getValue().equals(imageEssencedescriptorDOMNode)).map(e -> e.getKey()).findFirst() .get(); imageEssenceDescriptorModel = new CompositionImageEssenceDescriptorModel(imageEssenceDescriptorID, imageEssencedescriptorDOMNode, regXMLLibDictionary); if (imageEssenceDescriptorModel != null) { imfErrorLogger.addAllErrors(imageEssenceDescriptorModel.getErrors()); Application5Composition.validatePictureEssenceDescriptor(imageEssenceDescriptorModel, ApplicationCompositionType.APPLICATION_5_COMPOSITION_TYPE, imfErrorLogger); } } } catch (Exception e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Exception in validating EssenceDescriptors in APPLICATION_5_COMPOSITION_TYPE: %s ", e.getMessage())); } } public static void validatePictureEssenceDescriptor(CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel, ApplicationCompositionFactory.ApplicationCompositionType applicationCompositionType, IMFErrorLogger imfErrorLogger) { UUID imageEssenceDescriptorID = imageEssenceDescriptorModel.getImageEssencedescriptorID(); ColorModel colorModel = imageEssenceDescriptorModel.getColorModel(); if( !colorModel.equals(ColorModel.RGB)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall be an RGBA descriptor per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); return; } Integer storedWidth = imageEssenceDescriptorModel.getStoredWidth(); Integer storedHeight = imageEssenceDescriptorModel.getStoredHeight(); if ((storedWidth <= 0) || (storedHeight <= 0)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid storedWidth(%d) or storedHeight(%d) as per %s", imageEssenceDescriptorID.toString(), storedWidth, storedHeight, applicationCompositionType.toString())); } Integer sampleWidth = imageEssenceDescriptorModel.getSampleWidth(); Integer sampleHeight = imageEssenceDescriptorModel.getSampleHeight(); if ((sampleWidth != null && !sampleWidth.equals(storedWidth)) || (sampleHeight != null && !sampleHeight.equals(storedHeight))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid sampleWidth(%d) or sampleHeight(%d) as per %s", imageEssenceDescriptorID.toString(), sampleWidth != null ? sampleWidth : 0, sampleHeight != null ? sampleHeight : 0, applicationCompositionType.toString())); } Integer displayWidth = imageEssenceDescriptorModel.getDisplayWidth(); Integer displayHeight = imageEssenceDescriptorModel.getDisplayHeight(); if ((displayWidth <= 0) || (displayHeight <= 0)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid displayWidth(%d) or displayHeight(%d) item as per %s", imageEssenceDescriptorID.toString(), displayWidth, displayHeight, applicationCompositionType.toString())); } Integer displayXOffset = imageEssenceDescriptorModel.getDisplayXOffset(); Integer displayYOffset = imageEssenceDescriptorModel.getDisplayYOffset(); if ((displayXOffset == null) || (displayYOffset == null)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has no displayXOffset or displayYOffset item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } Fraction imageAspectRatio = imageEssenceDescriptorModel.getImageAspectRatio(); if( imageAspectRatio == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall have an Aspect Ratio item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } //TODO: Test if imageAspectRatio == roundToIntegralTiesToAway(DisplayWidth*pixelAspectRatio) / DisplayHeight ColorPrimaries colorPrimaries = imageEssenceDescriptorModel.getColorPrimaries(); if(!colorPrimaries.equals(ColorPrimaries.ACES)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid ColorPrimaries as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } TransferCharacteristic transferCharacteristic = imageEssenceDescriptorModel.getTransferCharacteristic(); if(!transferCharacteristic.equals(TransferCharacteristic.Linear)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid TransferCharacteristic as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } Colorimetry color = imageEssenceDescriptorModel.getColor(); if(!color.equals(Colorimetry.Color_App5_AP0)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid ColorPrimaries(%s) as per %s", imageEssenceDescriptorID.toString(), colorPrimaries.name(), applicationCompositionType.toString())); } UL essenceContainerFormatUL = imageEssenceDescriptorModel.getEssenceContainerFormatUL(); UL MXFGCFrameWrappedACESPictures = UL.fromULAsURNStringToUL("urn:smpte:ul:060e2b34.0401010d.0d010301.02190100"); // MXF-GC Frame-wrapped ACES Pictures per 2065-5 if(essenceContainerFormatUL == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s does not contain a ContainerFormat as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } else { if (!essenceContainerFormatUL.equals(MXFGCFrameWrappedACESPictures)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid ContainerFormat(%s) as per %s", imageEssenceDescriptorID.toString(), essenceContainerFormatUL.toString(), applicationCompositionType.toString())); } } Integer offset = imageEssenceDescriptorModel.getSampledXOffset(); if((offset != null) && (offset != 0)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid SampledXOffset (%d) as per %s", imageEssenceDescriptorID.toString(), offset, applicationCompositionType.toString())); } offset = imageEssenceDescriptorModel.getSampledYOffset(); if((offset != null) && (offset != 0)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has an invalid SampledYOffset (%d) item as per %s", imageEssenceDescriptorID.toString(), offset, applicationCompositionType.toString())); } //FrameLayout FrameLayoutType frameLayoutType = imageEssenceDescriptorModel.getFrameLayoutType(); if (!frameLayoutType.equals(FrameLayoutType.FullFrame)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid FrameLayout(%s) as per %s", imageEssenceDescriptorID.toString(), frameLayoutType.name(), applicationCompositionType.toString())); } //SampleRate Fraction sampleRate = imageEssenceDescriptorModel.getSampleRate(); if (sampleRate.equals(new Fraction(0))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has no SampleRate per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } //The following items shall not be present per 2065-5 Table 10 if(imageEssenceDescriptorModel.getStoredOffset() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a StoredF2Offset item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getDisplayF2Offset() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a DisplayF2Offset item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getActiveFormatDescriptor() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain an Active Format Descriptor item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getAlphaTransparency() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain an Alpha Transparency as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getImageAlignmentOffset() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain an Image Alignment Offset item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getStoredOffset() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a StoredF2Offset item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getImageStartOffset() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain an Image Start Offset item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getImageEndOffset() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain an Image End Offset item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getFieldDominance() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a Field Dominance item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getCodingEquations() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a Coding Equations item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getComponentMaxRef() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a Component Max Ref item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getComponentMinRef() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a Component Min Ref item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getAlphaMaxRef() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain an Alpha Max Ref item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getAlphaMinRef() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain an Alpha Min Ref item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getPalette() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a Palette item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } if(imageEssenceDescriptorModel.getPaletteLayout() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s shall not contain a Palette Layout item as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); } } public ApplicationCompositionType getApplicationCompositionType() { return ApplicationCompositionType.APPLICATION_5_COMPOSITION_TYPE; } }
5,061
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/CompositionModel_st2067_2_2013.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.writerTools.CompositionPlaylistBuilder_2013; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.w3c.dom.Element; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * A class that models aspects of a Composition such as a VirtualTrack, TrackResources etc. compliant with the 2013 CompositionPlaylist specification st2067-3:2013. * Used for converting a specific JAXB class (org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType) into the canonical, version-independent, class IMFCompositionPlaylistType */ final class CompositionModel_st2067_2_2013 { //To prevent instantiation private CompositionModel_st2067_2_2013(){ } /** * Converts a CompositionPlaylist from a JAXB object, into a version-independent model * @param compositionPlaylistType - a CompositionPlaylist object model * @param imfErrorLogger - an object for logging errors * @return A canonical, version-independent, instance of IMFCompositionPlaylistType */ @Nonnull public static IMFCompositionPlaylistType getCompositionPlaylist (@Nonnull org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType compositionPlaylistType, @Nonnull IMFErrorLogger imfErrorLogger) { // Parse each Segment List<IMFSegmentType> segmentList = compositionPlaylistType.getSegmentList().getSegment().stream() .map(segment -> parseSegment(segment, compositionPlaylistType.getEditRate(), imfErrorLogger)) .collect(Collectors.toList()); // Parse the EssenceDescriptors, if present List<IMFEssenceDescriptorBaseType> essenceDescriptorList = Collections.emptyList(); if (compositionPlaylistType.getEssenceDescriptorList() != null) { essenceDescriptorList = compositionPlaylistType.getEssenceDescriptorList().getEssenceDescriptor().stream() .map(ed -> parseEssenceDescriptor(ed, imfErrorLogger)) .collect(Collectors.toList()); } // Parse the ApplicationIdentification values Set<String> applicationIDs = parseApplicationIds(compositionPlaylistType, imfErrorLogger); // Identify the Core Constraints version String coreConstraintsSchema = CoreConstraints.fromApplicationId(applicationIDs); if (coreConstraintsSchema == null) { // Get the namespaces of each Sequence being used Set<String> sequenceNamespaces = compositionPlaylistType.getSegmentList().getSegment().get(0) .getSequenceList().getAny().stream().filter(JAXBElement.class::isInstance) .map(je -> ((JAXBElement<?>) je).getName().getNamespaceURI()).collect(Collectors.toSet()); // Find the Core Constraints version, based on the namespaces of the Sequences coreConstraintsSchema = CoreConstraints.fromElementNamespaces(sequenceNamespaces); // If all else fails, assume the minimum version applicable to this CPL version if (coreConstraintsSchema == null) coreConstraintsSchema = CoreConstraints.NAMESPACE_IMF_2013; } return new IMFCompositionPlaylistType( compositionPlaylistType.getId(), compositionPlaylistType.getEditRate(), (compositionPlaylistType.getAnnotation() == null ? null : compositionPlaylistType.getAnnotation().getValue()), (compositionPlaylistType.getIssuer() == null ? null : compositionPlaylistType.getIssuer().getValue()), (compositionPlaylistType.getCreator() == null ? null : compositionPlaylistType.getCreator().getValue()), (compositionPlaylistType.getContentOriginator() == null ? null : compositionPlaylistType.getContentOriginator().getValue()), (compositionPlaylistType.getContentTitle() == null ? null : compositionPlaylistType.getContentTitle().getValue()), segmentList, essenceDescriptorList, coreConstraintsSchema, applicationIDs ); } @Nonnull static org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType unmarshallCpl(@Nonnull ResourceByteRangeProvider resourceByteRangeProvider, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1)) { // Validate the document against the CPL schemas, when unmarshalling Schema schema = CompositionModel_st2067_2_2013.ValidationSchema.INSTANCE; ValidationEventHandlerImpl validationEventHandlerImpl = new ValidationEventHandlerImpl(true); Unmarshaller unmarshaller = CompositionModel_st2067_2_2013.CompositionPlaylistType2013_Context.INSTANCE.createUnmarshaller(); unmarshaller.setEventHandler(validationEventHandlerImpl); unmarshaller.setSchema(schema); JAXBElement<org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType> jaxbCpl = unmarshaller.unmarshal(new StreamSource(inputStream), org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.class); // Report any schema validation errors that occurred during unmarshalling if (validationEventHandlerImpl.hasErrors()) { validationEventHandlerImpl.getErrors().stream() .map(e -> new ErrorLogger.ErrorObject( IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, e.getValidationEventSeverity(), "Line Number : " + e.getLineNumber().toString() + " - " + e.getErrorMessage())) .forEach(imfErrorLogger::addError); throw new IMFException(validationEventHandlerImpl.toString(), imfErrorLogger); } return jaxbCpl.getValue(); } catch(JAXBException e) { throw new IMFException("Error when unmarshalling org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType", e, imfErrorLogger); } } // Parse the list of ApplicationIdentification values @Nonnull private static Set<String> parseApplicationIds(@Nonnull org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType compositionPlaylistType, @Nonnull IMFErrorLogger imfErrorLogger) { if (compositionPlaylistType.getExtensionProperties() == null) return Collections.emptySet(); return compositionPlaylistType.getExtensionProperties().getAny().stream() .filter(JAXBElement.class::isInstance).map(JAXBElement.class::cast) .filter(extProp -> extProp.getName().getLocalPart().equals("ApplicationIdentification")).map(JAXBElement::getValue) .filter(List.class::isInstance).map(appIdList -> (List<?>) appIdList) .findAny().orElse(Collections.emptyList()).stream().map(Object::toString).collect(Collectors.toSet()); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType // Into a canonical, version-independent, instance of IMFEssenceDescriptorBaseType @Nonnull private static IMFEssenceDescriptorBaseType parseEssenceDescriptor(@Nonnull org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType essenceDescriptor, @Nonnull IMFErrorLogger imfErrorLogger) { return new IMFEssenceDescriptorBaseType(essenceDescriptor.getId(), essenceDescriptor.getAny()); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2013.SegmentType // Into a canonical, version-independent, instance of IMFSegmentType @Nonnull private static IMFSegmentType parseSegment(@Nonnull org.smpte_ra.schemas._2067_3._2013.SegmentType segment, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { List<IMFSequenceType> sequenceList = new ArrayList<IMFSequenceType>(); // Parse the Marker Sequence org.smpte_ra.schemas._2067_3._2013.SequenceType markerSequence = segment.getSequenceList().getMarkerSequence(); if (markerSequence != null) { sequenceList.add(parseMarkerSequence(markerSequence, cplEditRate, imfErrorLogger)); } /* Parse rest of the sequences */ for (Object object : segment.getSequenceList().getAny()) { // Ignore unrecognized Sequence types if(!(object instanceof JAXBElement)){ String details = ""; if(object instanceof Element) { Element element = Element.class.cast(object); details = "Tag: " + element.getTagName() + " URI: " + element.getNamespaceURI(); } imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.NON_FATAL, String.format("Unsupported sequence type or schema %s", details)); continue; } // Get the JAXB SequenceType object JAXBElement jaxbElement = (JAXBElement)(object); org.smpte_ra.schemas._2067_3._2013.SequenceType sequence = (org.smpte_ra.schemas._2067_3._2013.SequenceType) jaxbElement.getValue(); // Determine the type of Sequence being parsed Composition.SequenceTypeEnum sequenceType = Composition.SequenceTypeEnum.getSequenceTypeEnum(jaxbElement.getName().getLocalPart()); // Parse the Sequence sequenceList.add(parseSequence(sequence, cplEditRate, sequenceType, imfErrorLogger)); } return new IMFSegmentType(segment.getId(), sequenceList); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2013.SequenceType // Into a canonical, version-independent, instance of IMFSequenceType @Nonnull private static IMFSequenceType parseMarkerSequence(@Nonnull org.smpte_ra.schemas._2067_3._2013.SequenceType markerSequence, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { List<IMFBaseResourceType> sequenceResources = new ArrayList<>(); for (org.smpte_ra.schemas._2067_3._2013.BaseResourceType resource : markerSequence.getResourceList().getResource()) { if (resource instanceof org.smpte_ra.schemas._2067_3._2013.MarkerResourceType) { try { IMFMarkerResourceType markerResource = parseMarkerResource( (org.smpte_ra.schemas._2067_3._2013.MarkerResourceType) resource, cplEditRate, imfErrorLogger); sequenceResources.add(markerResource); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, "Unsupported Resource type in Marker Sequence"); } } return new IMFSequenceType(markerSequence.getId(), markerSequence.getTrackId(), Composition.SequenceTypeEnum.MarkerSequence, sequenceResources); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2013.SequenceType // Into a canonical, version-independent, instance of IMFSequenceType @Nonnull private static IMFSequenceType parseSequence(@Nonnull org.smpte_ra.schemas._2067_3._2013.SequenceType sequence, @Nonnull List<Long> cplEditRate, Composition.SequenceTypeEnum sequenceType, @Nonnull IMFErrorLogger imfErrorLogger) { List<IMFBaseResourceType> sequenceResources = new ArrayList<>(); for (org.smpte_ra.schemas._2067_3._2013.BaseResourceType resource : sequence.getResourceList().getResource()) { if(resource instanceof org.smpte_ra.schemas._2067_3._2013.TrackFileResourceType) { try { IMFTrackFileResourceType trackFileResource = parseTrackFileResource( (org.smpte_ra.schemas._2067_3._2013.TrackFileResourceType) resource, cplEditRate, imfErrorLogger); sequenceResources.add(trackFileResource); } catch(IMFException e) { imfErrorLogger.addAllErrors(e.getErrors()); } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, "Unsupported Resource type"); } } return new IMFSequenceType(sequence.getId(), sequence.getTrackId(), sequenceType, sequenceResources); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2013.MarkerResourceType // Into a canonical, version-independent, instance of IMFMarkerResourceType @Nonnull private static IMFMarkerResourceType parseMarkerResource(@Nonnull org.smpte_ra.schemas._2067_3._2013.MarkerResourceType markerResource, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { // Parse each Marker within the MarkerResource List<IMFMarkerType> markerList = new ArrayList<IMFMarkerType>(); for (org.smpte_ra.schemas._2067_3._2013.MarkerType marker : markerResource.getMarker()) { markerList.add(new IMFMarkerType(marker.getAnnotation() == null ? null : marker .getAnnotation().getValue(), new IMFMarkerType.Label(marker.getLabel().getValue(), marker.getLabel().getScope()), marker.getOffset())); } return new IMFMarkerResourceType( markerResource.getId(), markerResource.getEditRate().size() != 0 ? markerResource.getEditRate() : cplEditRate, markerResource.getIntrinsicDuration(), markerResource.getEntryPoint(), markerResource.getSourceDuration(), markerResource.getRepeatCount(), markerList); } // Converts an instance of the JAXB class org.smpte_ra.schemas._2067_3._2013.TrackFileResourceType // Into a canonical, version-independent, instance of IMFTrackFileResourceType @Nonnull private static IMFTrackFileResourceType parseTrackFileResource(@Nonnull org.smpte_ra.schemas._2067_3._2013.TrackFileResourceType trackFileResource, @Nonnull List<Long> cplEditRate, @Nonnull IMFErrorLogger imfErrorLogger) { return new IMFTrackFileResourceType( trackFileResource.getId(), trackFileResource.getTrackFileId(), trackFileResource.getEditRate().size() != 0 ? trackFileResource.getEditRate() : cplEditRate, trackFileResource.getIntrinsicDuration(), trackFileResource.getEntryPoint(), trackFileResource.getSourceDuration(), trackFileResource.getRepeatCount(), trackFileResource.getSourceEncoding(), trackFileResource.getHash(), CompositionPlaylistBuilder_2013.defaultHashAlgorithm ); } // Singleton to allow a JAXBContext configured for 2013 CPLs to be reused and lazy-loaded private static class CompositionPlaylistType2013_Context { static final JAXBContext INSTANCE = createJAXBContext(); private static JAXBContext createJAXBContext() { try { return JAXBContext.newInstance( org.smpte_ra.schemas._2067_3._2013.ObjectFactory.class, // 2013 CPL org.smpte_ra.schemas._2067_2._2013.ObjectFactory.class //Core constraints ); } catch(JAXBException e) { throw new IMFException("Failed to create JAXBContext needed by CompositionPlaylistType (2013)", e); } } } // Singleton to allow the CPL validation Schema object to be reused and lazy-loaded private static class ValidationSchema { static final Schema INSTANCE = createValidationSchema(); private static Schema createValidationSchema() { // Load all XSD schemas required to validate a CompositionPlaylist document ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try (InputStream xsd_xmldsig_core = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"); InputStream xsd_dcmlTypes = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd"); InputStream xsd_cpl_2013 = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_3_2013/imf-cpl.xsd"); InputStream xsd_core_constraints_2013 = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2013/imf-core-constraints-20130620-pal.xsd"); ) { // Build a schema from all of the XSD files provided SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); return schemaFactory.newSchema(new StreamSource[]{ new StreamSource(xsd_xmldsig_core), new StreamSource(xsd_dcmlTypes), new StreamSource(xsd_cpl_2013), new StreamSource(xsd_core_constraints_2013), }); } catch(IOException | SAXException e) { throw new IMFException("Unable to create CPL validation schema", e); } } } }
5,062
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFMarkerResourceType.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import javax.annotation.concurrent.Immutable; import java.math.BigInteger; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * A class that models Marker resource structure of an IMF Composition Playlist. */ @Immutable public final class IMFMarkerResourceType extends IMFBaseResourceType { private final List<IMFMarkerType> markerList; public IMFMarkerResourceType(String id, List<Long> editRate, BigInteger intrinsicDuration, BigInteger entryPoint, BigInteger sourceDuration, BigInteger repeatCount, List<IMFMarkerType> markerList ) { super(id, editRate, intrinsicDuration, entryPoint, sourceDuration, repeatCount); markerList.sort(Comparator.comparing(IMFMarkerType::getOffset)); this.markerList = Collections.unmodifiableList(markerList); } /** * Getter for the Marker list * @return a list containing all the Markers of the resource */ public List<IMFMarkerType> getMarkerList(){ return this.markerList; } /** * A method to determine the equivalence of any 2 Marker resource. * @param other - the object to compare against * @return boolean indicating if the two Marker resources are equivalent/representing the same timeline */ @Override public boolean equivalent(IMFBaseResourceType other) { if(other == null || !(other instanceof IMFMarkerResourceType)){ return false; } IMFMarkerResourceType otherMarkerResource = IMFMarkerResourceType.class.cast(other); boolean result = true; result &= super.equivalent( otherMarkerResource ); List<IMFMarkerType> otherMarkerList = otherMarkerResource.getMarkerList(); if(otherMarkerList.size() != this.markerList.size()){ return false; } for(int i=0; i< this.markerList.size(); i++){ IMFMarkerType thisMarker = this.markerList.get(i); IMFMarkerType otherMarker = otherMarkerList.get(i); result &= thisMarker.equivalent(otherMarker); } return result; } }
5,063
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/Application2ExtendedComposition.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.Colorimetry; import com.netflix.imflibrary.Colorimetry.ColorModel; import com.netflix.imflibrary.Colorimetry.Quantization; import com.netflix.imflibrary.Colorimetry.Sampling; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.Fraction; import javax.annotation.Nonnull; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import static com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.FrameLayoutType; /** * A class that models Composition with Application 2Extended constraints from 2067-21 specification */ public class Application2ExtendedComposition extends AbstractApplicationComposition { public static final String SCHEMA_URI_APP2E_2014 = "http://www.smpte-ra.org/schemas/2067-21/2014"; public static final String SCHEMA_URI_APP2E_2016 = "http://www.smpte-ra.org/schemas/2067-21/2016"; public static final String SCHEMA_URI_APP2E_2020 = "http://www.smpte-ra.org/ns/2067-21/2020"; public static final Integer MAX_YUV_IMAGE_FRAME_WIDTH = 3840; public static final Integer MAX_YUV_IMAGE_FRAME_HEIGHT = 2160; public static final Integer MAX_RGB_IMAGE_FRAME_WIDTH = 4096; public static final Integer MAX_RGB_IMAGE_FRAME_HEIGHT = 3112; public static final UL JPEG2000PICTURECODINGSCHEME = UL.fromULAsURNStringToUL("urn:smpte:ul:060e2b34.04010107.04010202.03010000"); public static final Set<Fraction>rgbaSampleRateSupported = Collections.unmodifiableSet(new HashSet<Fraction>() {{ add(new Fraction(24)); add(new Fraction(25)); add(new Fraction(30)); add(new Fraction(50)); add(new Fraction(60)); add(new Fraction(120)); add(new Fraction(24000, 1001)); add(new Fraction(30000, 1001)); add(new Fraction(60000, 1001)); }}); public static final Set<Fraction>yuvSampleRateSupported = Collections.unmodifiableSet(new HashSet<Fraction>() {{ add(new Fraction(24)); add(new Fraction(25)); add(new Fraction(30)); add(new Fraction(50)); add(new Fraction(60)); add(new Fraction(24000, 1001)); add(new Fraction(30000, 1001)); add(new Fraction(60000, 1001)); }}); public static final Map<Colorimetry, Set<Integer>>colorToBitDepthMap = Collections.unmodifiableMap(new HashMap<Colorimetry, Set<Integer>>() {{ put(Colorimetry.Unknown, new HashSet<Integer>(){{ }}); put(Colorimetry.Color3, new HashSet<Integer>(){{ add(8); add(10); }}); put(Colorimetry.Color4, new HashSet<Integer>(){{ add(8); add(10); }}); put(Colorimetry.Color5, new HashSet<Integer>(){{ add(10); add(12); }}); put(Colorimetry.Color6, new HashSet<Integer>(){{ add(10); add(12); add(16);}}); put(Colorimetry.Color7, new HashSet<Integer>(){{ add(10); add(12); add(16); }}); }}); public static final Set<Integer>bitDepthsSupported = Collections.unmodifiableSet(new HashSet<Integer>() {{ add(8); add(10); add(12); add(16); }}); private static final Set<String> ignoreSet = Collections.unmodifiableSet(new HashSet<String>() {{ add("SignalStandard"); add("ActiveFormatDescriptor"); add("VideoLineMap"); add("AlphaTransparency"); add("PixelLayout"); add("ActiveHeight"); add("ActiveWidth"); add("ActiveXOffset"); add("ActiveYOffset"); }}); public Application2ExtendedComposition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType) { this(imfCompositionPlaylistType, new HashSet<>()); } public Application2ExtendedComposition(@Nonnull IMFCompositionPlaylistType imfCompositionPlaylistType, Set<String> homogeneitySelectionSet) { super(imfCompositionPlaylistType, ignoreSet, homogeneitySelectionSet); try { CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel = getCompositionImageEssenceDescriptorModel(); if (imageEssenceDescriptorModel != null) { IMFErrorLogger app2ErrorLogger = new IMFErrorLoggerImpl(); IMFErrorLogger app2ExtendedErrorLogger = new IMFErrorLoggerImpl(); imfErrorLogger.addAllErrors(imageEssenceDescriptorModel.getErrors()); Application2Composition.validateGenericPictureEssenceDescriptor(imageEssenceDescriptorModel, ApplicationCompositionType.APPLICATION_2E_COMPOSITION_TYPE, imfErrorLogger); Application2Composition.validateImageCharacteristics(imageEssenceDescriptorModel, ApplicationCompositionType.APPLICATION_2_COMPOSITION_TYPE, app2ErrorLogger); if(app2ErrorLogger.getNumberOfErrors() != 0) { Application2ExtendedComposition.validateImageCharacteristics(imageEssenceDescriptorModel, ApplicationCompositionType.APPLICATION_2E_COMPOSITION_TYPE, app2ExtendedErrorLogger); if(app2ExtendedErrorLogger.getNumberOfErrors() != 0) { imfErrorLogger.addAllErrors(app2ExtendedErrorLogger.getErrors()); } } } } catch (Exception e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Exception in validating EssenceDescriptors in APPLICATION_2E_COMPOSITION_TYPE: %s ", e.getMessage())); } } public static void validateImageCharacteristics(CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel, ApplicationCompositionType applicationCompositionType, IMFErrorLogger imfErrorLogger) { UUID imageEssenceDescriptorID = imageEssenceDescriptorModel.getImageEssencedescriptorID(); ColorModel colorModel = imageEssenceDescriptorModel.getColorModel(); if( !colorModel.equals(ColorModel.RGB) && !colorModel.equals(ColorModel.YUV)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has Invalid color components as per %s", imageEssenceDescriptorID.toString(), applicationCompositionType.toString())); return; } //storedWidth Integer storedWidth = imageEssenceDescriptorModel.getStoredWidth(); if (((colorModel.equals(ColorModel.RGB) && storedWidth > MAX_RGB_IMAGE_FRAME_WIDTH) || (colorModel.equals(ColorModel.YUV) && storedWidth > MAX_YUV_IMAGE_FRAME_WIDTH))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid StoredWidth(%d) for ColorModel(%s) as per %s", imageEssenceDescriptorID.toString(), storedWidth, colorModel.name(), applicationCompositionType.toString())); } //storedHeight Integer storedHeight = imageEssenceDescriptorModel.getStoredHeight(); if (((colorModel.equals(ColorModel.RGB) && storedHeight > MAX_RGB_IMAGE_FRAME_HEIGHT) || (colorModel.equals(ColorModel.YUV) && storedHeight > MAX_YUV_IMAGE_FRAME_HEIGHT))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid storedHeight(%d) for ColorModel(%s) as per %s", imageEssenceDescriptorID.toString(), storedHeight, colorModel.name(), applicationCompositionType.toString())); } //PixelBitDepth Integer pixelBitDepth = imageEssenceDescriptorModel.getPixelBitDepth(); Colorimetry color = imageEssenceDescriptorModel.getColor(); if( !bitDepthsSupported.contains(pixelBitDepth) || !colorToBitDepthMap.get(color).contains(pixelBitDepth)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s invalid PixelBitDepth(%d) for Color(%s) as per %s", imageEssenceDescriptorID.toString(), pixelBitDepth, color.name(), applicationCompositionType.toString())); } //FrameLayout FrameLayoutType frameLayoutType = imageEssenceDescriptorModel.getFrameLayoutType(); if (!frameLayoutType.equals(FrameLayoutType.FullFrame)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has invalid FrameLayout(%s) as per %s", imageEssenceDescriptorID.toString(), frameLayoutType.name(), applicationCompositionType.toString())); } //SampleRate Fraction sampleRate = imageEssenceDescriptorModel.getSampleRate(); Set<Fraction> frameRateSupported = colorModel.equals(ColorModel.RGB) ? rgbaSampleRateSupported : yuvSampleRateSupported; if (!frameRateSupported.contains(sampleRate)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has Invalid SampleRate(%s) for ColorModel(%s) as per %s", imageEssenceDescriptorID.toString(), sampleRate.toString(), colorModel.name(), applicationCompositionType.toString())); } //Sampling Sampling sampling = imageEssenceDescriptorModel.getSampling(); if((colorModel.equals(ColorModel.RGB) && !sampling.equals(Sampling.Sampling444)) || (colorModel.equals(ColorModel.YUV) && !sampling.equals(Sampling.Sampling422))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has Invalid Sampling(%s) for ColorModel(%s) as per %s", imageEssenceDescriptorID.toString(), sampling.name(), colorModel.name(), applicationCompositionType.toString())); } //Quantization Quantization quantization = imageEssenceDescriptorModel.getQuantization(); if((colorModel.equals(ColorModel.RGB) && !(quantization.equals(Quantization.QE2) || quantization.equals(Quantization.QE1))) || (colorModel.equals(ColorModel.YUV) && !quantization.equals(Quantization.QE1))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor with ID %s has Invalid Quantization(%s) for ColorModel(%s) as per %s", imageEssenceDescriptorID.toString(), quantization.name(), colorModel.name(), applicationCompositionType.toString())); } //Coding UL pictureEssenceCoding = imageEssenceDescriptorModel.getPictureEssenceCodingUL(); if(pictureEssenceCoding.equalsWithMask(JPEG2000PICTURECODINGSCHEME, 0b1111111011111100)) { boolean validProfile = false; if (pictureEssenceCoding.getByte(14) == 0x01) { switch (pictureEssenceCoding.getByte(15)) { case 0x11: /* JPEG2000BroadcastContributionSingleTileProfileLevel1 */ case 0x12: /* JPEG2000BroadcastContributionSingleTileProfileLevel2 */ case 0x13: /* JPEG2000BroadcastContributionSingleTileProfileLevel3 */ case 0x14: /* JPEG2000BroadcastContributionSingleTileProfileLevel4 */ case 0x15: /* JPEG2000BroadcastContributionSingleTileProfileLevel5 */ case 0x16: /* JPEG2000BroadcastContributionMultiTileReversibleProfileLevel6 */ case 0x17: /* JPEG2000BroadcastContributionMultiTileReversibleProfileLevel7 */ validProfile = true; break; default: } } else if (pictureEssenceCoding.getByte(14) == 0x02) { switch (pictureEssenceCoding.getByte(15)) { case 0x03: /* J2K_2KIMF_SingleTileLossyProfile_M1S1 */ case 0x05: /* J2K_2KIMF_SingleTileLossyProfile_M2S1 */ case 0x07: /* J2K_2KIMF_SingleTileLossyProfile_M3S1 */ case 0x09: /* J2K_2KIMF_SingleTileLossyProfile_M4S1 */ case 0x0a: /* J2K_2KIMF_SingleTileLossyProfile_M4S2 */ case 0x0c: /* J2K_2KIMF_SingleTileLossyProfile_M5S1 */ case 0x0d: /* J2K_2KIMF_SingleTileLossyProfile_M5S2 */ case 0x0e: /* J2K_2KIMF_SingleTileLossyProfile_M5S3 */ case 0x10: /* J2K_2KIMF_SingleTileLossyProfile_M6S1 */ case 0x11: /* J2K_2KIMF_SingleTileLossyProfile_M6S2 */ case 0x12: /* J2K_2KIMF_SingleTileLossyProfile_M6S3 */ case 0x13: /* J2K_2KIMF_SingleTileLossyProfile_M6S4 */ validProfile = true; break; default: } } else if (pictureEssenceCoding.getByte(14) == 0x03) { switch (pictureEssenceCoding.getByte(15)) { case 0x03: /* J2K_4KIMF_SingleTileLossyProfile_M1S1 */ case 0x05: /* J2K_4KIMF_SingleTileLossyProfile_M2S1 */ case 0x07: /* J2K_4KIMF_SingleTileLossyProfile_M3S1 */ case 0x09: /* J2K_4KIMF_SingleTileLossyProfile_M4S1 */ case 0x0a: /* J2K_4KIMF_SingleTileLossyProfile_M4S2 */ case 0x0c: /* J2K_4KIMF_SingleTileLossyProfile_M5S1 */ case 0x0d: /* J2K_4KIMF_SingleTileLossyProfile_M5S2 */ case 0x0e: /* J2K_4KIMF_SingleTileLossyProfile_M5S3 */ case 0x10: /* J2K_4KIMF_SingleTileLossyProfile_M6S1 */ case 0x11: /* J2K_4KIMF_SingleTileLossyProfile_M6S2 */ case 0x12: /* J2K_4KIMF_SingleTileLossyProfile_M6S3 */ case 0x13: /* J2K_4KIMF_SingleTileLossyProfile_M6S4 */ case 0x15: /* J2K_4KIMF_SingleTileLossyProfile_M7S1 */ case 0x16: /* J2K_4KIMF_SingleTileLossyProfile_M7S2 */ case 0x17: /* J2K_4KIMF_SingleTileLossyProfile_M7S3 */ case 0x18: /* J2K_4KIMF_SingleTileLossyProfile_M7S4 */ case 0x19: /* J2K_4KIMF_SingleTileLossyProfile_M7S5 */ case 0x1b: /* J2K_4KIMF_SingleTileLossyProfile_M8S1 */ case 0x1c: /* J2K_4KIMF_SingleTileLossyProfile_M8S2 */ case 0x1d: /* J2K_4KIMF_SingleTileLossyProfile_M8S3 */ case 0x1e: /* J2K_4KIMF_SingleTileLossyProfile_M8S4 */ case 0x1f: /* J2K_4KIMF_SingleTileLossyProfile_M8S5 */ case 0x20: /* J2K_4KIMF_SingleTileLossyProfile_M8S6 */ validProfile = true; break; default: } } else if (pictureEssenceCoding.getByte(14) == 0x05) { switch (pictureEssenceCoding.getByte(15)) { case 0x02: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M1S0 */ case 0x04: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M2S0 */ case 0x06: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M3S0 */ case 0x08: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M4S0 */ case 0x0b: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M5S0 */ case 0x0f: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M6S0 */ validProfile = true; break; default: } } else if (pictureEssenceCoding.getByte(14) == 0x06) { switch (pictureEssenceCoding.getByte(15)) { case 0x02: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M1S0 */ case 0x04: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M2S0 */ case 0x06: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M3S0 */ case 0x08: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M4S0 */ case 0x0b: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M5S0 */ case 0x0f: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M6S0 */ case 0x14: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M7S0 */ case 0x1a: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M8S0 */ validProfile = true; break; default: } } if (! validProfile) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Invalid JPEG 2000 profile: %s", pictureEssenceCoding.toString() )); } } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("Image codec must be JPEG 2000. Found %s instead.", pictureEssenceCoding.toString() )); } } public ApplicationCompositionType getApplicationCompositionType() { return ApplicationCompositionType.APPLICATION_2E_COMPOSITION_TYPE; } }
5,064
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_2/IMFMarkerVirtualTrack.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st2067_2; import javax.annotation.concurrent.Immutable; import java.util.List; import java.util.UUID; /** * A class that represents Marker Virtual Track. All the resources in this track are of type MarkerResourceType. */ @Immutable public final class IMFMarkerVirtualTrack extends Composition.VirtualTrack { public IMFMarkerVirtualTrack(UUID trackID, Composition.SequenceTypeEnum sequenceTypeEnum, List<IMFMarkerResourceType> resourceList, Composition.EditRate compositionEditRate){ super(trackID, sequenceTypeEnum, resourceList, compositionEditRate); } /** * Getter for the resources that are a part of this virtual track * @return an unmodifiable list of resources of type IMFMarkerResourceType that are a part of this virtual track */ public List<IMFMarkerResourceType> getMarkerResourceList() { return (List<IMFMarkerResourceType>)this.getResourceList(); } }
5,065
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0429_8/PackingList.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st0429_8; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smpte_ra.schemas._429_8._2007.pkl.PackingListType; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * This class represents a thin, immutable wrapper around the XML type 'PackingListType' which is defined in Section 7, * st0429-8:2007. A PackingList object can be constructed from an XML file only if it satisfies all the constraints specified * in st0429-8:2007 */ @Immutable public final class PackingList { private static final Logger logger = LoggerFactory.getLogger(PackingList.class); private final IMFErrorLogger imfErrorLogger; private static final String xmldsig_core_schema_path = "org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"; public static final List<String> supportedPKLNamespaces = Collections.unmodifiableList(new ArrayList<String>(){{ add("http://www.smpte-ra.org/schemas/429-8/2007/PKL"); add("http://www.smpte-ra.org/schemas/2067-2/2016/PKL");}}); private final UUID uuid; private final JAXBElement packingListTypeJAXBElement; private final PKLSchema pklSchema; private final List<Asset> assetList = new ArrayList<>(); private static class PKLSchema { private final String pklSchemaPath; private final String pklContext; private PKLSchema(String pklSchemaPath, String pklContext){ this.pklSchemaPath = pklSchemaPath; this.pklContext = pklContext; } private String getPKLSchemaPath(){ return this.pklSchemaPath; } private String getPKLContext(){ return this.pklContext; } } public static final Map<String, PKLSchema> supportedPKLSchemas = Collections.unmodifiableMap (new HashMap<String, PKLSchema>() {{ put("http://www.smpte-ra.org/schemas/429-8/2007/PKL", new PKLSchema("org/smpte_ra/schemas/st0429_8_2007/PKL/packingList_schema.xsd", "org.smpte_ra.schemas._429_8._2007.pkl")); put("http://www.smpte-ra.org/schemas/2067-2/2016/PKL", new PKLSchema("org/smpte_ra/schemas/st2067_2_2016/PKL/packingList_schema.xsd", "org.smpte_ra.schemas._2067_2._2016.pkl"));}}); /** * Constructor for a {@link com.netflix.imflibrary.st0429_8.PackingList PackingList} object that corresponds to a PackingList XML document * @param packingListXMLFile the input XML file * @throws IOException - any I/O related error is exposed through an IOException */ public PackingList(File packingListXMLFile) throws IOException { this(new FileByteRangeProvider(packingListXMLFile)); } /** * Constructor for a {@link com.netflix.imflibrary.st0429_8.PackingList PackingList} object that corresponds to a PackingList XML document * @param resourceByteRangeProvider corresponding to the PackingList XML file * @throws IOException - any I/O related error is exposed through an IOException */ public PackingList(ResourceByteRangeProvider resourceByteRangeProvider)throws IOException { JAXBElement<PackingListType> packingListTypeJAXBElement = null; imfErrorLogger = new IMFErrorLoggerImpl(); String packingListNamespaceURI = getPackingListSchemaURI(resourceByteRangeProvider, imfErrorLogger); PKLSchema pklSchema = supportedPKLSchemas.get(packingListNamespaceURI); if(pklSchema == null){ String message = String.format("Please check the PKL document, currently we only support the " + "following schema URIs %s", serializePKLSchemasToString()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1); InputStream xmldsig_core_is = contextClassLoader.getResourceAsStream(PackingList.xmldsig_core_schema_path); InputStream pkl_is = contextClassLoader.getResourceAsStream(pklSchema.getPKLSchemaPath()); ) { StreamSource[] streamSources = new StreamSource[2]; streamSources[0] = new StreamSource(xmldsig_core_is); streamSources[1] = new StreamSource(pkl_is); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(streamSources); ValidationEventHandlerImpl validationEventHandlerImpl = new ValidationEventHandlerImpl(true); JAXBContext jaxbContext = JAXBContext.newInstance(pklSchema.getPKLContext()); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setEventHandler(validationEventHandlerImpl); unmarshaller.setSchema(schema); packingListTypeJAXBElement = (JAXBElement) unmarshaller.unmarshal(inputStream); if (validationEventHandlerImpl.hasErrors()) { List<ValidationEventHandlerImpl.ValidationErrorObject> errors = validationEventHandlerImpl.getErrors(); for (ValidationEventHandlerImpl.ValidationErrorObject error : errors) { String errorMessage = "Line Number : " + error.getLineNumber().toString() + " - " + error.getErrorMessage(); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, error.getValidationEventSeverity(), errorMessage); } throw new IMFException(validationEventHandlerImpl.toString(), imfErrorLogger); } } } catch(SAXException | JAXBException e){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, e.getMessage()); } if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("PackingList parsing failed", imfErrorLogger); } this.pklSchema = pklSchema; this.packingListTypeJAXBElement = packingListTypeJAXBElement; switch(this.pklSchema.getPKLContext()) { case "org.smpte_ra.schemas._429_8._2007.pkl": //this.packingListType = PackingList.checkConformance(packingListTypeJAXBElement.getValue()); org.smpte_ra.schemas._429_8._2007.pkl.PackingListType packingListType_st0429_8_2007_PKL = (org.smpte_ra.schemas._429_8._2007.pkl.PackingListType) this.packingListTypeJAXBElement.getValue(); this.uuid = UUIDHelper.fromUUIDAsURNStringToUUID(packingListType_st0429_8_2007_PKL.getId()); for (org.smpte_ra.schemas._429_8._2007.pkl.AssetType assetType : packingListType_st0429_8_2007_PKL.getAssetList().getAsset()) { Asset asset = new Asset(assetType.getId(), Arrays.copyOf(assetType.getHash(), assetType.getHash().length), assetType.getSize().longValue(), assetType.getType(), assetType.getOriginalFileName() != null ? assetType.getOriginalFileName().getValue() : null); this.assetList.add(asset); } break; case "org.smpte_ra.schemas._2067_2._2016.pkl": org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType packingListType_st2067_2_2016_PKL = (org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType) this.packingListTypeJAXBElement.getValue(); this.uuid = UUIDHelper.fromUUIDAsURNStringToUUID(packingListType_st2067_2_2016_PKL.getId()); for (org.smpte_ra.schemas._2067_2._2016.pkl.AssetType assetType : packingListType_st2067_2_2016_PKL.getAssetList().getAsset()) { Asset asset = new Asset(assetType.getId(), Arrays.copyOf(assetType.getHash(), assetType.getHash().length), assetType.getSize().longValue(), assetType.getType(), assetType.getOriginalFileName() != null ? assetType.getOriginalFileName().getValue() : null, assetType.getHashAlgorithm().getAlgorithm()); this.assetList.add(asset); } break; default: String message = String.format("Please check the PKL document, currently we only support the " + "following schema URIs %s", serializePKLSchemasToString()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } Set<UUID> assetUUIDs = new HashSet<>(); for(Asset asset : this.assetList){ if(assetUUIDs.contains(asset.getUUID())){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("More than one PackingList Asset seems to use AssetUUID %s this is invalid.", asset.getUUID().toString())); } else{ assetUUIDs.add(asset.getUUID()); } } } private static String getPackingListSchemaURI(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException { String packingListSchemaURI = ""; try(InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize()-1);) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, exception.getMessage())); } @Override public void error(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, exception.getMessage())); } @Override public void fatalError(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, exception.getMessage())); } }); Document document = documentBuilder.parse(inputStream); NodeList nodeList = null; for(String supportedSchemaURI : supportedPKLNamespaces) { //obtain root node nodeList = document.getElementsByTagNameNS(supportedSchemaURI, "PackingList"); if (nodeList != null && nodeList.getLength() == 1) { packingListSchemaURI = supportedSchemaURI; break; } } } catch(ParserConfigurationException | SAXException e) { String message = String.format("Error occurred while trying to determine the PackingList Namespace " + "URI, invalid PKL document Error Message : %s", e.getMessage()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } if(packingListSchemaURI.isEmpty()) { String message = String.format("Please check the PKL document and namespace URI, currently we only " + "support the following schema URIs %s", serializePKLSchemasToString()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } return packingListSchemaURI; } private static final String serializePKLSchemasToString(){ StringBuilder stringBuilder = new StringBuilder(); Iterator iterator = supportedPKLSchemas.values().iterator(); while(iterator.hasNext()){ stringBuilder.append(String.format("%n")); stringBuilder.append(((PKLSchema)iterator.next()).getPKLContext()); } return stringBuilder.toString(); } /** * A stateless method that verifies if the raw data represented by the ResourceByteRangeProvider corresponds to a valid * IMF Packing List document * @param resourceByteRangeProvider - a byte range provider for the document that needs to be verified * @return - a boolean indicating if the document represented is an IMF PackingList or not * @throws IOException - any I/O related error is exposed through an IOException */ public static boolean isFileOfSupportedSchema(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException{ try(InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize()-1);) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); NodeList nodeList = null; for(String supportedSchemaURI : supportedPKLNamespaces) { //obtain root node nodeList = document.getElementsByTagNameNS(supportedSchemaURI, "PackingList"); if (nodeList != null && nodeList.getLength() == 1) { return true; } } } catch(ParserConfigurationException | SAXException e) { return false; } return false; } private static PackingListType checkConformance(PackingListType packingListType) { return packingListType; } /** * Getter for the complete list of assets present in this PackingList * @return the list of assets present in this PackingList */ public List<Asset> getAssets() { return Collections.unmodifiableList(this.assetList); } /** * Getter for the UUID corresponding to this PackingList object * @return the uuid of this PackingList object */ public UUID getUUID() { return this.uuid; } /** * A method that returns a string representation of a PackingList object * * @return string representing the object */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("=================== PackingList : %s%n", this.uuid)); for (Asset asset : this.assetList) { sb.append(asset.toString()); } return sb.toString(); } /** * Getter for the errors in PackingList * * @return List of errors in PackingList. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } /** * This class represents a thin, immutable wrapper around the XML type 'AssetType' which is defined in Section 7, * st0429-8:2007. It exposes a minimal set of properties of the wrapped object through appropriate Getter methods */ public static final class Asset { public static final String APPLICATION_MXF_TYPE = "application/mxf"; public static final String TEXT_XML_TYPE = "text/xml"; private static final String DEFAULT_HASH_ALGORITHM = "http://www.w3.org/2000/09/xmldig#sha1"; private final UUID uuid; private final byte[] hash; private final long size; private final String type; private final String original_filename; private final String hash_algorithm; /** * Constructor for the wrapping {@link com.netflix.imflibrary.st0429_8.PackingList.Asset Asset} object from the wrapped model version of XML type 'AssetType' * @param uuid identifying the PackingList Asset * @param hash hash a byte[] containing the Base64 encoded SHA-1 hash of this PackingList Asset * @param size of the asset in bytes * @param type could be either text/xml or application/mxf as defined in st0429-9:2007 * @param original_filename a free form human readable text that contains the name of the file * containing the asset at the time the PackingList was created */ public Asset(String uuid, byte[] hash, long size, String type, String original_filename) { this(uuid, hash, size, type, original_filename, Asset.DEFAULT_HASH_ALGORITHM); } public Asset(String uuid, byte[] hash, long size, String type, String original_filename, String hash_algorithm) { this.uuid = UUIDHelper.fromUUIDAsURNStringToUUID(uuid); this.hash = Arrays.copyOf(hash, hash.length); this.size = size; this.type = type; this.original_filename = original_filename; this.hash_algorithm = hash_algorithm; } /** * Getter for the UUID associated with this object * @return the asset UUID */ public UUID getUUID() { return this.uuid; } /** * Getter for the size of the underlying file associated with this object * @return the file size */ public long getSize() { return this.size; } /** * Getter for the MIME type of the underlying file associated with this object * @return the MIME type as a string */ public String getType() { return this.type; } /** * Getter for the filename of the underlying file associated with this object * @return the filename or null if no file name was present */ public @Nullable String getOriginalFilename() { return this.original_filename; } public byte[] getHash(){ return Arrays.copyOf(this.hash, this.hash.length); } /** * Getter for the Hash Algorithm used in generating the Hash of this Asset * @return a string corresponding to the HashAlgorithm */ public String getHashAlgorithm(){ return this.hash_algorithm; } /** * A method that returns a string representation of a PackingList Asset object * * @return string representing the object */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("=================== Asset : %s%n", this.getUUID())); sb.append(String.format("hash = %s%n", Arrays.toString(this.hash))); sb.append(String.format("size = %d%n", this.getSize())); sb.append(String.format("type = %s%n", this.getType())); sb.append(String.format("original_filename = %s%n", this.getOriginalFilename())); sb.append(String.format("hash_algorithm = %s%n", this.hash_algorithm)); return sb.toString(); } } public static void validatePackingListSchema(ResourceByteRangeProvider resourceByteRangeProvider, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException, SAXException { String pklNamespaceURI = PackingList.getPackingListSchemaURI(resourceByteRangeProvider, imfErrorLogger); PKLSchema pklSchema = supportedPKLSchemas.get(pklNamespaceURI); if(pklSchema == null){ String message = String.format("Please check the PKL document, currently we only support the " + "following schema URIs %s", serializePKLSchemasToString()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1); InputStream xmldsig_core_is = contextClassLoader.getResourceAsStream(PackingList.xmldsig_core_schema_path); InputStream pkl_is = contextClassLoader.getResourceAsStream(pklSchema.getPKLSchemaPath()); ) { StreamSource inputSource = new StreamSource(inputStream); StreamSource[] streamSources = new StreamSource[2]; streamSources[0] = new StreamSource(xmldsig_core_is); streamSources[1] = new StreamSource(pkl_is); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(streamSources); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, exception.getMessage())); } @Override public void error(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, exception.getMessage())); } @Override public void fatalError(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, exception.getMessage())); } }); validator.validate(inputSource); } } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <inputFilePath>%n", PackingList.class.getName())); return sb.toString(); } public static void main(String args[]) throws IOException, SAXException, JAXBException { if (args.length != 1) { logger.error(usage()); throw new IllegalArgumentException("Invalid parameters"); } File inputFile = new File(args[0]); if(!inputFile.exists()){ logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.PackingList, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject>errors = IMPValidator.validatePKL(payloadRecord); if(errors.size() > 0){ long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("PackingList Document has %d errors and %d warnings", errors.size() - warningCount, warningCount)); for(ErrorLogger.ErrorObject errorObject : errors){ if(errorObject.getErrorLevel()!= IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if(errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } } else{ logger.info("No errors were detected in the PackingList Document"); } } }
5,066
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0429_9/BasicMapProfileV2FileSet.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st0429_9; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import javax.annotation.concurrent.Immutable; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; /** * This class represents an immutable implementation of 'Basic Map Profile v2' defined in Annex A of st0429-9:2014 * limited to the case of a single Asset Map document in the root directory of the . A BasicMapProfilev2FileSet object can only be constructed if the constraints * specified in Section A.1 in Annex A of st0429-9:2014 are satisfied */ @Immutable public final class BasicMapProfileV2FileSet { private static final Logger logger = LoggerFactory.getLogger(BasicMapProfileV2FileSet.class); private final BasicMapProfileV2MappedFileSet basicMapProfileV2MappedFileSet; private final IMFErrorLogger imfErrorLogger; /** * Constructor for a {@link BasicMapProfileV2FileSet BasicMapProfilev2FileSet} from a {@link BasicMapProfileV2MappedFileSet MappedFileSet} object. Construction * succeeds if the constraints specified in Section A.1 in Annex A of st0429-9:2014 are satisfied * @param basicMapProfileV2MappedFileSet the Mapped File Set object corresponding to this object * @throws IOException - forwarded from {@link BasicMapProfileV2MappedFileSet#BasicMapProfileV2MappedFileSet(java.io.File) MappedFileSet} constructor * @throws SAXException - forwarded from {@link BasicMapProfileV2MappedFileSet#BasicMapProfileV2MappedFileSet(java.io.File) MappedFileSet} constructor * @throws JAXBException - forwarded from {@link BasicMapProfileV2MappedFileSet#BasicMapProfileV2MappedFileSet(java.io.File) MappedFileSet} constructor * @throws URISyntaxException - forwarded from {@link BasicMapProfileV2MappedFileSet#BasicMapProfileV2MappedFileSet(java.io.File) MappedFileSet} constructor */ public BasicMapProfileV2FileSet(BasicMapProfileV2MappedFileSet basicMapProfileV2MappedFileSet) throws IOException, SAXException, JAXBException, URISyntaxException { imfErrorLogger = new IMFErrorLoggerImpl(); for (AssetMap.Asset asset : basicMapProfileV2MappedFileSet.getAssetMap().getAssetList()) {//per Section A.2 in Annex A of st0429-9:2014, each path element value shall be a relative path reference if (asset.getPath().isAbsolute()) { String message = String.format("%s is an absolute URI", asset.getPath()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, message); } } this.basicMapProfileV2MappedFileSet = basicMapProfileV2MappedFileSet; if (imfErrorLogger.hasFatalErrors()) { throw new IMFException(String.format("Found %d errors in AssetMap XML file", imfErrorLogger .getNumberOfErrors()), imfErrorLogger); } } /** * Getter for the {@link com.netflix.imflibrary.st0429_9.AssetMap AssetMap} object corresponding to this object * @return the corresponding AssetMap object */ public AssetMap getAssetMap() { return this.basicMapProfileV2MappedFileSet.getAssetMap(); } /** * Getter for the absolute, hierarchical URI with a scheme equal to <tt>"file"</tt> URI corresponding to the {@link com.netflix.imflibrary.st0429_9.AssetMap AssetMap} * object associated with this Mapped File Set * @return file-based URI for the AssetMap object */ public URI getAbsoluteAssetMapURI() { return this.basicMapProfileV2MappedFileSet.getAbsoluteAssetMapURI(); } public static void main(String[] args) throws IOException, SAXException, JAXBException, URISyntaxException { File rootFile = new File(args[0]); BasicMapProfileV2FileSet basicMapProfileV2FileSet = new BasicMapProfileV2FileSet(new BasicMapProfileV2MappedFileSet(rootFile)); logger.warn(basicMapProfileV2FileSet.getAssetMap().toString()); } }
5,067
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0429_9/AssetMap.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st0429_9; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smpte_ra.schemas._429_9._2007.am.AssetMapType; import org.smpte_ra.schemas._429_9._2007.am.AssetType; import org.smpte_ra.schemas._429_9._2007.am.ChunkType; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; /** * This class represents a thin, immutable wrapper around the XML type 'AssetMapType' which is defined in Section 11, * st0429-9:2014. An AssetMap object can be constructed from an XML file only if it satisfies all the constraints specified * in st0429-9:2014 */ @Immutable public final class AssetMap { private static final Integer MAX_NUMBER_OF_PATH_SEGMENTS = 10; private static final Integer MAX_PATH_SEGMENT_LENGTH = 100; private static final Integer MAX_PATH_ELEMENT_LENGTH = 100; private final UUID uuid; private final List<Asset> assetList = new ArrayList<>(); private final List<Asset> packingListAssets = new ArrayList<>(); private final Map<UUID, URI> uuidToPath = new HashMap<>(); private static final Logger logger = LoggerFactory.getLogger(AssetMap.class); public static final List<String> supportedAssetMapSchemaURIs = Collections.unmodifiableList(new ArrayList<String>(){{ add("http://www.smpte-ra.org/schemas/429-9/2007/AM");}}); public static final Map<String, AssetMapSchema> supportedAssetMapSchemas = Collections.unmodifiableMap (new HashMap<String, AssetMapSchema>() {{ put("http://www.smpte-ra.org/schemas/429-9/2007/AM", new AssetMapSchema("org/smpte_ra/schemas/st0429_9_2007/AM/assetMap_schema.xsd", "org.smpte_ra.schemas._429_9._2007.am"));}}); private final IMFErrorLogger imfErrorLogger; private static class AssetMapSchema { private final String assetMapSchemaPath; private final String assetMapContext; private AssetMapSchema(String assetMapSchemaPath, String assetMapContext){ this.assetMapSchemaPath = assetMapSchemaPath; this.assetMapContext = assetMapContext; } private String getAssetMapSchemaPath(){ return this.assetMapSchemaPath; } private String getAssetMapContext(){ return this.assetMapContext; } } /** * Constructor for an {@link com.netflix.imflibrary.st0429_9.AssetMap AssetMap} object from an XML file that contains an AssetMap document * @param assetMapXmlFile the input XML file * @throws IOException - any I/O related error is exposed through an IOException */ public AssetMap(File assetMapXmlFile) throws IOException { this(getFileAsResourceByteRangeProvider(assetMapXmlFile)); } /** * Constructor for an {@link com.netflix.imflibrary.st0429_9.AssetMap AssetMap} object from an XML file that contains an AssetMap document * @param resourceByteRangeProvider that supports the mark() (mark position should be set to point to the beginning of the file) and reset() methods corresponding to the input XML file * @throws IOException - any I/O related error is exposed through an IOException */ public AssetMap(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { imfErrorLogger = new IMFErrorLoggerImpl(); JAXBElement assetMapTypeJAXBElement = null; String assetMapNamespaceURI = getAssetMapNamespaceURI(resourceByteRangeProvider); AssetMapSchema assetMapSchema = supportedAssetMapSchemas.get(assetMapNamespaceURI); if(assetMapSchema == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Please check the AssetMap document, currently we only support " + "the following schema URIs %s", serializeAssetMapSchemasToString())); throw new IMFException(String.format("Please check the AssetMap document, currently we only support the " + "following schema URIs %s", serializeAssetMapSchemasToString()), imfErrorLogger); } try { try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1); InputStream assetMap_schema_is = Thread.currentThread().getContextClassLoader().getResourceAsStream(assetMapSchema.getAssetMapSchemaPath());) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource schemaSource = new StreamSource(assetMap_schema_is); Schema schema = schemaFactory.newSchema(schemaSource); ValidationEventHandlerImpl validationEventHandlerImpl = new ValidationEventHandlerImpl(true); JAXBContext jaxbContext = JAXBContext.newInstance(assetMapSchema.getAssetMapContext()); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setEventHandler(validationEventHandlerImpl); unmarshaller.setSchema(schema); assetMapTypeJAXBElement = (JAXBElement) unmarshaller.unmarshal(inputStream); if (validationEventHandlerImpl.hasErrors()) { List<ValidationEventHandlerImpl.ValidationErrorObject> errors = validationEventHandlerImpl.getErrors(); for (ValidationEventHandlerImpl.ValidationErrorObject error : errors) { String errorMessage = "Line Number : " + error.getLineNumber().toString() + " - " + error.getErrorMessage(); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, error.getValidationEventSeverity(), errorMessage); } throw new IMFException("AssetMap parsing failed with validation errors", imfErrorLogger); } } } catch(SAXException | JAXBException e){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, e.getMessage()); } if(imfErrorLogger.hasFatalErrors()) { throw new IMFException("AssetMap parsing failed", imfErrorLogger); } switch(assetMapSchema.getAssetMapContext()) { case "org.smpte_ra.schemas._429_9._2007.am": UUID uuid = null; org.smpte_ra.schemas._429_9._2007.am.AssetMapType assetMapType = (org.smpte_ra.schemas._429_9._2007.am.AssetMapType) assetMapTypeJAXBElement.getValue(); imfErrorLogger.addAllErrors(checkConformance(assetMapType)); uuid = UUIDHelper.fromUUIDAsURNStringToUUID(assetMapType.getId()); this.uuid = uuid; for (org.smpte_ra.schemas._429_9._2007.am.AssetType assetType : assetMapType.getAssetList().getAsset()) { boolean isPackingList = (assetType.isPackingList() != null) ? assetType.isPackingList() : false; String path = assetType.getChunkList().getChunk().get(0).getPath(); try { Asset asset = new Asset(assetType.getId(), isPackingList, path); this.imfErrorLogger.addAllErrors(asset.getErrors()); this.assetList.add(asset); this.uuidToPath.put(asset.getUUID(), asset.getPath()); if ((assetType.isPackingList() != null) && (assetType.isPackingList())) { this.packingListAssets.add(asset); } } catch(URISyntaxException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, e.getMessage()); } catch(IMFException e) { this.imfErrorLogger.addAllErrors(e.getErrors()); } } break; default: imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Please check the AssetMap document, currently we only support " + "the following schema URIs %s", serializeAssetMapSchemasToString())); throw new IMFException(String.format("Please check the AssetMap document, currently we only support " + "the following schema URIs %s", serializeAssetMapSchemasToString()), imfErrorLogger); } if (imfErrorLogger.hasFatalErrors()) { throw new IMFException(String.format("Found %d errors in AssetMap XML file", imfErrorLogger .getNumberOfErrors()), imfErrorLogger); } } /** * Getter for the errors in AssetMap * * @return List of errors in AssetMap. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } private static final String serializeAssetMapSchemasToString(){ StringBuilder stringBuilder = new StringBuilder(); Iterator iterator = supportedAssetMapSchemas.values().iterator(); while(iterator.hasNext()){ stringBuilder.append(String.format("%n")); stringBuilder.append(((AssetMapSchema)iterator.next()).getAssetMapContext()); } return stringBuilder.toString(); } /** * A stateless method that verifies if the raw data represented by the ResourceByteRangeProvider corresponds to a valid * IMF AssetMap document * @param resourceByteRangeProvider - a byte range provider for the document that needs to be verified * @return - a boolean indicating if the document represented is an IMF AssetMap or not * @throws IOException - any I/O related error is exposed through an IOException */ public static boolean isFileOfSupportedSchema(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException{ try(InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize()-1);) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); NodeList nodeList = null; for(String supportedSchemaURI : supportedAssetMapSchemaURIs) { //obtain root node nodeList = document.getElementsByTagNameNS(supportedSchemaURI, "AssetMap"); if (nodeList != null && nodeList.getLength() == 1) { return true; } } } catch(ParserConfigurationException | SAXException e) { return false; } return false; } private static String getAssetMapNamespaceURI(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException{ String assetMapNamespaceURI = ""; try(InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize()-1);) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); NodeList nodeList = null; for(String supportedSchemaURI : supportedAssetMapSchemaURIs) { //obtain root node nodeList = document.getElementsByTagNameNS(supportedSchemaURI, "AssetMap"); if (nodeList != null && nodeList.getLength() == 1) { assetMapNamespaceURI = supportedSchemaURI; break; } } } catch(ParserConfigurationException | SAXException e) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Error occurred while trying to determine the AssetMap Namespace " + "URI, invalid AssetMap document Error Message : %s", e.getMessage())); throw new IMFException(String.format("Error occurred while trying to determine the AssetMap Namespace " + "URI, invalid AssetMap document Error Message : %s", e.getMessage()), imfErrorLogger); } if(assetMapNamespaceURI.isEmpty()) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Please check the AssetMap document and namespace URI, currently we " + "only support the following schema URIs %s", Utilities.serializeObjectCollectionToString (supportedAssetMapSchemaURIs))); throw new IMFException(String.format("Please check the AssetMap document and namespace URI, currently we " + "only support the following schema URIs %s", Utilities.serializeObjectCollectionToString (supportedAssetMapSchemaURIs)), imfErrorLogger); } return assetMapNamespaceURI; } private static ResourceByteRangeProvider getFileAsResourceByteRangeProvider(File file) { return new FileByteRangeProvider(file); } static List<ErrorLogger.ErrorObject> checkConformance(AssetMapType assetMapType) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); //per st0429-9:2014 Section 5.4, VolumeCount shall be one if (!assetMapType.getVolumeCount().equals(new BigInteger("1"))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("<VolumeCount> element = %d, is not equal to 1", assetMapType.getVolumeCount())); } if(assetMapType.getAssetList() == null || assetMapType.getAssetList().getAsset().size() <= 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("No assets in AssetMap")); } else { for (AssetType assetType : assetMapType.getAssetList().getAsset()) { if(assetType.getChunkList() == null || assetType.getChunkList().getChunk().size() <= 0 ) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("No chunks in Asset %s", assetType.getId())); } else { //per st0429-9:2014 Section 6.4, <ChunkList> shall contain one <Chunk> element if (assetType.getChunkList().getChunk().size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("<ChunkList> element contains %d <Chunk> elements, only 1 " + "is allowed", assetType.getChunkList().getChunk().size())); } ChunkType chunkType = assetType.getChunkList().getChunk().get(0); //per st0429-9:2014 Section 6.4, <VolumeIndex> shall be equal to 1 or absent if ((chunkType.getVolumeIndex() != null) && !chunkType.getVolumeIndex().equals(new BigInteger("1"))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("<VolumeIndex> element = %d, only 1 is allowed", chunkType .getVolumeIndex())); } //per st0429-9:2014 Section 6.4, <Offset> shall be equal to 0 or absent if ((chunkType.getOffset() != null) && !chunkType.getOffset().equals(new BigInteger("0"))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("<Offset> element = %d, only 0 is allowed", chunkType .getOffset())); } } } } return imfErrorLogger.getErrors(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("=================== AssetMap : %s%n", this.uuid)); for (Asset asset : this.assetList) { sb.append(asset.toString()); } return sb.toString(); } /** * Getter for the complete list of assets present in this AssetMap * @return the list of assets present in this AssetMap */ public List<Asset> getAssetList() { return Collections.unmodifiableList(this.assetList); } /** * Getter for the list of packing list (see st0429-8:2007) assets present in this AssetMap * @return the list of assets present in this AssetMap that are packing lists */ public List<Asset> getPackingListAssets() { return Collections.unmodifiableList(this.packingListAssets); } /** * * @param uuid the unique identifier for the asset of interest * @return the unmodified path URI (as it occurs in the AssetMap XML document) corresponding to the asset of interest */ public @Nullable URI getPath(UUID uuid) { return this.uuidToPath.get(uuid); } /** * Getter for the AssetMap's UUID * @return uuid corresponding to this AssetMap document */ public UUID getUUID(){ return this.uuid; } /** * This class represents a thin, immutable wrapper around the XML type 'AssetType' which is defined in Section 11, * st0429-9:2014. It exposes a minimal set of properties of the wrapped object through appropriate Getter methods */ @Immutable public static final class Asset { private final UUID uuid; private final boolean isPackingList; private final URI path; private final IMFErrorLogger imfErrorLogger; /** * Constructor for the wrapping {@link com.netflix.imflibrary.st0429_9.AssetMap.Asset Asset} object from the wrapped model version of XML type 'AssetType'. Construction * fails in case the URI associated with wrapped object is invalid * @param uuid - the ID corresponding to an Asset in the AssetMap * @param isPackingList - a boolean flag to indicate if this Asset is a PackingList * @param path - URI associated with this asset * @throws URISyntaxException - exposes any issues with the URI associated with the wrapped object */ public Asset(String uuid, boolean isPackingList, String path) throws URISyntaxException { this.uuid = UUIDHelper.fromUUIDAsURNStringToUUID(uuid); this.isPackingList = isPackingList; this.imfErrorLogger = new IMFErrorLoggerImpl(); String[] pathSegments = path.split("/"); List<String> invalidURISyntaxPathSegments = new ArrayList<>(); List<String> invalidLengthPathSegments = new ArrayList<>(); if(pathSegments.length > MAX_NUMBER_OF_PATH_SEGMENTS) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The Asset path %s has %d path segments which exceeds the limit %d", path, pathSegments.length, MAX_NUMBER_OF_PATH_SEGMENTS)); } if(path.matches("^/.+")) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The Asset path %s begins with '/' character", path)); } for(String pathSegment : pathSegments) { if (pathSegment.matches("^[a-zA-Z0-9._-]+") == false) { invalidURISyntaxPathSegments.add(pathSegment); } if (pathSegment.length() > MAX_PATH_SEGMENT_LENGTH) { invalidLengthPathSegments.add(pathSegment); } } if(invalidURISyntaxPathSegments.size() > 0){ this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Asset path %s has following path segments with invalid URI syntax in Annex-A of st429-9:2014 (a-z, A-Z, 0-9, ., _, -): %s", path, Utilities.serializeObjectCollectionToString(invalidURISyntaxPathSegments))); } if(invalidLengthPathSegments.size() > 0){ this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The Asset path %s has the following path segments with a length greater than 100: %s", path, Utilities.serializeObjectCollectionToString(invalidLengthPathSegments))); } else if(path.length() > MAX_PATH_ELEMENT_LENGTH) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The Asset path %s has length %d which exceeds the limit %d", path, path.length(), MAX_PATH_ELEMENT_LENGTH)); } if(this.imfErrorLogger.hasFatalErrors()) { throw new IMFException( String.format("Invalid asset path %s", path), imfErrorLogger); } if(Paths.get(path).normalize().startsWith("..")) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The Asset path %s is outside the tree rooted at the directory containing the Asset Map", path)); } this.path = new URI(path); } /** * Getter for the UUID associated with the {@link com.netflix.imflibrary.st0429_9.AssetMap.Asset Asset} object * @return the asset UUID */ public UUID getUUID() { return this.uuid; } /** * Tells if the {@link com.netflix.imflibrary.st0429_9.AssetMap.Asset Asset} object is a packing list * @return true if the object corresponds to a packing list, false otherwise */ public boolean isPackingList() { return this.isPackingList; } /** * Getter for the path associated with the {@link com.netflix.imflibrary.st0429_9.AssetMap.Asset Asset} object. The * path is unmodified relative to what was present in the AssetMap XML document * @return the asset path as a URI */ public URI getPath() { return this.path; } /** * Getter for the errors in Composition * * @return List of errors in Composition. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("================== Asset : %s%n", this.uuid)); sb.append(String.format("isPackingList = %s%n", this.isPackingList())); sb.append(String.format("path = %s%n", this.path)); return sb.toString(); } } public static List<ErrorLogger.ErrorObject> validateAssetMapSchema(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); String assetMapSchemaURI = getAssetMapNamespaceURI(resourceByteRangeProvider); AssetMapSchema assetMapSchema = supportedAssetMapSchemas.get(assetMapSchemaURI); if(assetMapSchema == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Please check the AssetMap document, currently we only support the " + "following schema URIs %s", serializeAssetMapSchemasToString())); return imfErrorLogger.getErrors(); } try { try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1); InputStream assetMap_is = Thread.currentThread().getContextClassLoader().getResourceAsStream(assetMapSchema.getAssetMapSchemaPath()); ) { StreamSource inputSource = new StreamSource(inputStream); StreamSource[] streamSources = new StreamSource[1]; streamSources[0] = new StreamSource(assetMap_is); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(streamSources); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, exception.getMessage())); } @Override public void error(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, exception.getMessage())); } @Override public void fatalError(SAXParseException exception) throws SAXException { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, exception.getMessage())); } }); validator.validate(inputSource); } } catch(SAXException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, e.getMessage()); } return imfErrorLogger.getErrors(); } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <inputFilePath>%n", AssetMap.class.getName())); return sb.toString(); } public static void main(String args[]) throws IOException, URISyntaxException, SAXException, JAXBException { if (args.length != 1) { logger.error(usage()); throw new IllegalArgumentException("Invalid parameters"); } File inputFile = new File(args[0]); if(!inputFile.exists()){ logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath())); System.exit(-1); } ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.AssetMap, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject>errors = IMPValidator.validateAssetMap(payloadRecord); if(errors.size() > 0){ long warningCount = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels .WARNING)).count(); logger.info(String.format("AssetMap Document has %d errors and %d warnings", errors.size() - warningCount, warningCount)); for(ErrorLogger.ErrorObject errorObject : errors){ if(errorObject.getErrorLevel()!= IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.error(errorObject.toString()); } else if(errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) { logger.warn(errorObject.toString()); } } } else{ logger.info("No errors were detected in the AssetMap Document"); } } }
5,068
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0429_9/BasicMapProfileV2MappedFileSet.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st0429_9; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ErrorLogger; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import javax.xml.bind.JAXBException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; /** * This class is an immutable implementation of the Mapped File Set concept defined in Section A.1 in Annex A of st0429-9:2014. * A BasicMapProfilev2MappedFileSet object can only be constructed if the constraints specified in Section A.1 in Annex A of st0429-9:2014 are * satisfied */ @Immutable public final class BasicMapProfileV2MappedFileSet { public static final String ASSETMAP_FILE_NAME = "ASSETMAP.xml"; private final AssetMap assetMap; private final URI absoluteAssetMapURI; private final IMFErrorLogger imfErrorLogger; /** * Constructor for a MappedFileSet object from a file representing the root of a directory tree * @param rootFile the directory which serves as the tree root of the Mapped File Set * @throws IOException - forwarded from {@link AssetMap#AssetMap(java.io.File) AssetMap} constructor */ public BasicMapProfileV2MappedFileSet(File rootFile) throws IOException { imfErrorLogger = new IMFErrorLoggerImpl(); if (!rootFile.isDirectory()) { String message = String.format("Root file %s corresponding to the mapped file set is not a " + "directory", rootFile.getAbsolutePath()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } FilenameFilter filenameFilter = new FilenameFilter() { @Override public boolean accept(File rootFile, String name) { return name.equals(BasicMapProfileV2MappedFileSet.ASSETMAP_FILE_NAME); } }; File[] files = rootFile.listFiles(filenameFilter); if ((files == null) || (files.length != 1)) { String message = String.format("Found %d files with name %s in mapped file set rooted at %s, " + "exactly 1 is allowed", (files == null) ? 0 : files.length, BasicMapProfileV2MappedFileSet .ASSETMAP_FILE_NAME, rootFile.getAbsolutePath()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } this.assetMap = new AssetMap(files[0]); this.absoluteAssetMapURI = files[0].toURI(); } /** * Getter for the {@link com.netflix.imflibrary.st0429_9.AssetMap AssetMap} object that represents the single AssetMap document * corresponding to this Mapped File Set * @return the AssetMap object */ public AssetMap getAssetMap() { return this.assetMap; } /** * Getter for the absolute, hierarchical URI with a scheme equal to <tt>"file"</tt> URI corresponding to the {@link com.netflix.imflibrary.st0429_9.AssetMap AssetMap} * object associated with this Mapped File Set * @return file-based URI for the AssetMap object */ public URI getAbsoluteAssetMapURI() { return this.absoluteAssetMapURI; } /** * Getter for the errors in Composition * * @return List of errors in Composition. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } }
5,069
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_201/IMFIABConstraintsChecker.java
package com.netflix.imflibrary.st2067_201; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.st2067_2.IMFBaseResourceType; import com.netflix.imflibrary.st2067_2.IMFTrackFileResourceType; import com.netflix.imflibrary.st2067_201.IABSoundfieldLabelSubDescriptor; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.RegXMLLibDictionary; import com.netflix.imflibrary.utils.UUIDHelper; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import static com.netflix.imflibrary.st0377.header.GenericSoundEssenceDescriptor.ElectroSpatialFormulation.MULTI_CHANNEL_MODE; import static com.netflix.imflibrary.st2067_201.IABEssenceDescriptor.IMF_IAB_ESSENCE_CLIP_WRAPPED_CONTAINER_UL; import static com.netflix.imflibrary.st2067_201.IABEssenceDescriptor.IMMERSIVE_AUDIO_CODING_LABEL; public class IMFIABConstraintsChecker { private static final Integer IAB_BIT_DEPTH = 24; private static final short IAB_CHANNEL_COUNT = 0; public static List<ErrorLogger.ErrorObject> checkIABVirtualTrack(Composition.EditRate compositionEditRate, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap, RegXMLLibDictionary regXMLLibDictionary, Set<String> homogeneitySelectionSet) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Iterator iterator = virtualTrackMap.entrySet().iterator(); while(iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); if (!virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.IABSequence)) continue; List<? extends IMFBaseResourceType> virtualTrackResourceList = virtualTrack.getResourceList(); for(IMFBaseResourceType baseResource : virtualTrackResourceList) { IMFTrackFileResourceType imfTrackFileResourceType = IMFTrackFileResourceType.class.cast(baseResource); DOMNodeObjectModel domNodeObjectModel = essenceDescriptorListMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(imfTrackFileResourceType.getSourceEncoding())); if (!domNodeObjectModel.getLocalName().equals("IABEssenceDescriptor")) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource does not have an IABEssenceDescriptor but %s", imfTrackFileResourceType.getSourceEncoding(), domNodeObjectModel.getLocalName())); } if (((imfTrackFileResourceType.getEditRate().getNumerator()*compositionEditRate.getDenominator()) % (imfTrackFileResourceType.getEditRate().getDenominator()*compositionEditRate.getNumerator()) != 0)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The EditRate %s/%s of resource %s is not a multiple of the EditRate of the Main Image Virtual Track %s/%s", imfTrackFileResourceType.getEditRate().getNumerator(), imfTrackFileResourceType.getEditRate().getDenominator(), imfTrackFileResourceType.getId(), compositionEditRate.getNumerator(), compositionEditRate.getDenominator())); } if (!domNodeObjectModel.getFieldAsUL("ContainerFormat").equals(IMF_IAB_ESSENCE_CLIP_WRAPPED_CONTAINER_UL)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource does not use the correct Essence Container UL: %s vs. %s", imfTrackFileResourceType.getSourceEncoding(), domNodeObjectModel.getFieldAsUL("ContainerFormat"), IMF_IAB_ESSENCE_CLIP_WRAPPED_CONTAINER_UL)); } if (domNodeObjectModel.getFieldAsUL("Codec") != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource shall not have a Codec item: %s", imfTrackFileResourceType.getSourceEncoding(), domNodeObjectModel.getFieldAsUL("Codec"))); } if (!domNodeObjectModel.getFieldAsUL("SoundCompression").equals(IMMERSIVE_AUDIO_CODING_LABEL)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource does not use the correct Sound Compression UL: %s vs. %s", imfTrackFileResourceType.getSourceEncoding(), domNodeObjectModel.getFieldAsUL("SoundCompression"), IMMERSIVE_AUDIO_CODING_LABEL)); } if (domNodeObjectModel.getFieldAsInteger("QuantizationBits") != IAB_BIT_DEPTH.intValue()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource has invalid QuantizationBits field: %s vs. %s", imfTrackFileResourceType.getSourceEncoding(), domNodeObjectModel.getFieldAsInteger("QuantizationBits"), IAB_BIT_DEPTH)); } if (domNodeObjectModel.getFieldAsString("AudioSampleRate") == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource does not have an AudioSampleRate item.", imfTrackFileResourceType.getSourceEncoding())); } if (domNodeObjectModel.getFieldAsInteger("ElectrospatialFormulation") != null && domNodeObjectModel.getFieldAsInteger("ElectrospatialFormulation").intValue() != MULTI_CHANNEL_MODE.value()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource has an invalid value of ElectrospatialFormulation: %d vs. %d.", imfTrackFileResourceType.getSourceEncoding(), domNodeObjectModel.getFieldAsInteger("ElectrospatialFormulation"), MULTI_CHANNEL_MODE.value())); } if (domNodeObjectModel.getChildrenDOMNodes().size() == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource has no SubDescriptor", imfTrackFileResourceType.getSourceEncoding())); } else { for (Map.Entry<DOMNodeObjectModel, Integer> entry : domNodeObjectModel.getChildrenDOMNodes().entrySet()) { if (!entry.getKey().getLocalName().equals("SubDescriptors")) continue; for (Map.Entry<DOMNodeObjectModel, Integer> subentry : entry.getKey().getChildrenDOMNodes().entrySet()) { if (subentry.getKey().getLocalName().equals("AudioChannelLabelSubDescriptor") || subentry.getKey().getLocalName().equals("SoundfieldGroupLabelSubDescriptor") || subentry.getKey().getLocalName().equals("GroupOfSoundfieldGroupsLabelSubDescriptor")) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource has forbidden %s", imfTrackFileResourceType.getSourceEncoding(), subentry.getKey().getLocalName())); } else if (subentry.getKey().getLocalName().equals("IABSoundfieldLabelSubDescriptor")) { // if (subentry.getKey().getFieldAsString("MCAAudioContentKind") == null) { // imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("EssenceDescriptor ID %s referenced by " + // "an IAB VirtualTrack Resource misses MCAAudioContentKind", imfTrackFileResourceType.getSourceEncoding())); // } // if (subentry.getKey().getFieldAsString("MCAAudioElementKind") == null) { // imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("EssenceDescriptor ID %s referenced by " + // "an IAB VirtualTrack Resource misses MCAAudioElementKind", imfTrackFileResourceType.getSourceEncoding())); // } // if (subentry.getKey().getFieldAsString("MCATitle") == null) { // imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("EssenceDescriptor ID %s referenced by " + // "an IAB VirtualTrack Resource misses MCATitle", imfTrackFileResourceType.getSourceEncoding())); // } // if (subentry.getKey().getFieldAsString("MCATitleVersion") == null) { // imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("EssenceDescriptor ID %s referenced by " + // "an IAB VirtualTrack Resource misses MCATitleVersion", imfTrackFileResourceType.getSourceEncoding())); // } if (!IABSoundfieldLabelSubDescriptor.IAB_MCA_LABEL_DICTIONNARY_ID_UL.equals(subentry.getKey().getFieldAsUL("MCALabelDictionaryID"))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource has invalid MCA Label Dictionary ID (%s vs. %s)", imfTrackFileResourceType.getSourceEncoding(), subentry.getKey().getFieldAsUL("MCALabelDictionaryID"), IABSoundfieldLabelSubDescriptor.IAB_MCA_LABEL_DICTIONNARY_ID_UL)); } if (!IABSoundfieldLabelSubDescriptor.IAB_MCA_TAG_SYMBOL.equals(subentry.getKey().getFieldAsString("MCATagSymbol"))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource misses MCA Tag Symbol (%s vs. %s)", imfTrackFileResourceType.getSourceEncoding(), subentry.getKey().getFieldAsString("MCATagSymbol"), IABSoundfieldLabelSubDescriptor.IAB_MCA_TAG_SYMBOL)); } if (!IABSoundfieldLabelSubDescriptor.IAB_MCA_TAG_NAME.equals(subentry.getKey().getFieldAsString("MCATagName"))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource misses MCA Tag Name (%s vs. %s)", imfTrackFileResourceType.getSourceEncoding(), subentry.getKey().getFieldAsString("MCATagName"), IABSoundfieldLabelSubDescriptor.IAB_MCA_TAG_NAME)); } if (subentry.getKey().getFieldAsString("MCAChannelID") != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("EssenceDescriptor ID %s referenced by " + "an IAB VirtualTrack Resource has forbidden MCAChannelID %s", imfTrackFileResourceType.getSourceEncoding(), subentry.getKey().getFieldAsString("MCAChannelID"))); } } } } } } } return imfErrorLogger.getErrors(); } }
5,070
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_201/IABTrackFileConstraints.java
package com.netflix.imflibrary.st2067_201; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.st0377.CompoundDataTypes; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.IndexTableSegment; import com.netflix.imflibrary.st0377.header.AudioChannelLabelSubDescriptor; import com.netflix.imflibrary.st0377.header.GenericDescriptor; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.GenericSoundEssenceDescriptor; import com.netflix.imflibrary.st0377.header.GroupOfSoundFieldGroupLabelSubDescriptor; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.Sequence; import com.netflix.imflibrary.st0377.header.SoundFieldGroupLabelSubDescriptor; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st0377.header.TimelineTrack; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.utils.ErrorLogger; import javax.annotation.Nonnull; import java.io.IOException; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; public final class IABTrackFileConstraints { private static final String IMF_IAB_EXCEPTION_PREFIX = "IMF IAB check: "; // Prevent instantiation public IABTrackFileConstraints() {} public static void checkCompliance(IMFConstraints.HeaderPartitionIMF headerPartitionIMF, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { HeaderPartition headerPartition = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition(); Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage; filePackage = (SourcePackage) genericPackage; UUID packageID = filePackage.getPackageMaterialNumberasUUID(); for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); if (sequence == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("TimelineTrack with instanceUID = %s in the IMFTrackFile represented by ID %s has no sequence.", timelineTrack.getInstanceUID(), packageID.toString())); } else { GenericDescriptor genericDescriptor = filePackage.getGenericDescriptor(); if (genericDescriptor instanceof IABEssenceDescriptor) { // Support for st2067-201 // Section 5.2 CompoundDataTypes.MXFCollections.MXFCollection<UL> conformsToSpecifications = preface.getConformstoSpecificationsULs(); if (conformsToSpecifications == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("Preface in the IMFTrackFile represented by ID %s does not have the required conformsToSpecifications item.", packageID.toString())); } else { List specificationsULs = conformsToSpecifications.getEntries(); if (specificationsULs.size() == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("Preface in the IMFTrackFile represented by ID %s does not have a single UL in the conformsToSpecifications item.", packageID.toString())); } else if (!specificationsULs.contains(IABEssenceDescriptor.IMF_IAB_TRACK_FILE_LEVEL0_UL)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("Preface in the IMFTrackFile represented by ID %s does not indicate the required IAB Level 0 Plugin UL in the conformsToSpecifications item, but to %s", packageID.toString(), specificationsULs)); } } IABEssenceDescriptor iabEssenceDescriptor = (IABEssenceDescriptor) genericDescriptor; // Section 5.4 if (timelineTrack.getEditRateNumerator() != iabEssenceDescriptor.getSampleRate().get(0) || timelineTrack.getEditRateDenominator() != iabEssenceDescriptor.getSampleRate().get(1)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("Timeline Track Edit Rate %d/%d does not match IABEssenceDescriptor Sample Rate %d/%d in the IMFTrackFile represented by ID %s.", timelineTrack.getEditRateNumerator(), timelineTrack.getEditRateDenominator(), iabEssenceDescriptor.getSampleRate().get(0), iabEssenceDescriptor.getSampleRate().get(1), packageID.toString())); } // Section 5.6.1 int bitDepth = iabEssenceDescriptor.getQuantizationBits(); if (bitDepth != 24) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s indicates an Audio Bit Depth = %d, only 24 is allowed.", packageID.toString(), iabEssenceDescriptor.getQuantizationBits())); } // Section 5.9 if (!iabEssenceDescriptor.getEssenceContainerUL().equals(IABEssenceDescriptor.IMF_IAB_ESSENCE_CLIP_WRAPPED_CONTAINER_UL)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s does not use as Essence Container Label item the IMF Clip-Wrapped IAB Essence Container Label %s but %s.", packageID.toString(), IABEssenceDescriptor.IMF_IAB_ESSENCE_CLIP_WRAPPED_CONTAINER_UL, iabEssenceDescriptor.getEssenceContainerUL().toString())); } if (iabEssenceDescriptor.getCodec() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s indicates a non-null codec: %s.", packageID.toString(), iabEssenceDescriptor.getCodec().toString())); } if (!iabEssenceDescriptor.getSoundEssenceCoding().equals(IABEssenceDescriptor.IMMERSIVE_AUDIO_CODING_LABEL)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s does not indicate the Immersive Audio Coding value in its Sound Essence Coding item %s but %s.", packageID.toString(), IABEssenceDescriptor.IMMERSIVE_AUDIO_CODING_LABEL, iabEssenceDescriptor.getSoundEssenceCoding().toString())); } if (iabEssenceDescriptor.getElectroSpatialFormulation() != null && iabEssenceDescriptor.getElectroSpatialFormulation() != GenericSoundEssenceDescriptor.ElectroSpatialFormulation.MULTI_CHANNEL_MODE) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s does not indicate the multi-channel mode default value for the Electro-Spatial Formulation item : %d.", packageID.toString(), iabEssenceDescriptor.getElectroSpatialFormulation().value())); } if (iabEssenceDescriptor.getReferenceImageEditRate() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s is missing the Reference Image Edit Rate item.", packageID.toString())); } if (iabEssenceDescriptor.getReferenceAudioAlignmentLevel() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s is missing the Reference Audio Alignment Level item.", packageID.toString())); } List<InterchangeObject.InterchangeObjectBO> subDescriptors = headerPartition.getSubDescriptors(); // Section 5.10.2 if (subDescriptors.size() == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s does not have subdescriptors", packageID.toString())); } else { List<InterchangeObject.InterchangeObjectBO> soundFieldGroupLabelSubDescriptors = subDescriptors.subList(0, subDescriptors.size()).stream().filter(interchangeObjectBO -> interchangeObjectBO.getClass().getEnclosingClass().equals(SoundFieldGroupLabelSubDescriptor.class)).collect(Collectors.toList()); if (soundFieldGroupLabelSubDescriptors.size() != 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s has %d illegal SoundFieldGroupLabelSubDescriptor(s)", packageID.toString(), soundFieldGroupLabelSubDescriptors.size())); } List<InterchangeObject.InterchangeObjectBO> audioChannelLabelSubDescriptors = subDescriptors.subList(0, subDescriptors.size()).stream().filter(interchangeObjectBO -> interchangeObjectBO.getClass().getEnclosingClass().equals(AudioChannelLabelSubDescriptor.class)).collect(Collectors.toList()); if (audioChannelLabelSubDescriptors.size() != 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s has %d illegal AudioChannelLabelSubDescriptor(s)", packageID.toString(), audioChannelLabelSubDescriptors.size())); } List<InterchangeObject.InterchangeObjectBO> groupOfSoundfieldGroupsLabelSubDescriptors = subDescriptors.subList(0, subDescriptors.size()).stream().filter(interchangeObjectBO -> interchangeObjectBO.getClass().getEnclosingClass().equals(GroupOfSoundFieldGroupLabelSubDescriptor.class)).collect(Collectors.toList()); if (groupOfSoundfieldGroupsLabelSubDescriptors.size() != 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s has %d illegal GroupOfSoundFieldGroupLabelSubDescriptor(s)", packageID.toString(), groupOfSoundfieldGroupsLabelSubDescriptors.size())); } List<InterchangeObject.InterchangeObjectBO> iabSoundFieldLabelSubDescriptors = subDescriptors.subList(0, subDescriptors.size()).stream().filter(interchangeObjectBO -> interchangeObjectBO.getClass().getEnclosingClass().equals(IABSoundfieldLabelSubDescriptor.class)).collect(Collectors.toList()); if (iabSoundFieldLabelSubDescriptors.size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABEssenceDescriptor in the IMFTrackFile represented by ID %s refers to %d IABSoundfieldLabelSubDescriptor, exactly 1 is required", packageID.toString(), iabSoundFieldLabelSubDescriptors.size())); } else { // Section 5.10.3 IABSoundfieldLabelSubDescriptor.IABSoundfieldLabelSubDescriptorBO iabSoundFieldLabelSubDescriptorBO = IABSoundfieldLabelSubDescriptor.IABSoundfieldLabelSubDescriptorBO.class.cast(iabSoundFieldLabelSubDescriptors.get(0)); if (iabSoundFieldLabelSubDescriptorBO.getMCATagName() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s is missing MCATagName", packageID.toString())); } else { // Section 5.10.4 if (!iabSoundFieldLabelSubDescriptorBO.getMCATagName().equals(IABSoundfieldLabelSubDescriptor.IAB_MCA_TAG_NAME)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s does not have a valid MCATagName: %s", packageID.toString(), iabSoundFieldLabelSubDescriptorBO.getMCATagName())); } } if (iabSoundFieldLabelSubDescriptorBO.getMCATagSymbol() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s is missing MCATagSymbol", packageID.toString())); } else { // Section 5.10.4 if (!iabSoundFieldLabelSubDescriptorBO.getMCATagSymbol().equals(IABSoundfieldLabelSubDescriptor.IAB_MCA_TAG_SYMBOL)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s does not have a valid MCATagSymbol: %s", packageID.toString(), iabSoundFieldLabelSubDescriptorBO.getMCATagSymbol())); } } if (iabSoundFieldLabelSubDescriptorBO.getMCALabelDictionnaryId() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s is missing MCALabelDictionaryId", packageID.toString())); } else { // Section 5.10.4 if (!iabSoundFieldLabelSubDescriptorBO.getMCALabelDictionnaryId().equals(IABSoundfieldLabelSubDescriptor.IAB_MCA_LABEL_DICTIONNARY_ID_UL)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s does not have the required MCA Label Dictionary Id %s but %s", packageID.toString(), IABSoundfieldLabelSubDescriptor.IAB_MCA_LABEL_DICTIONNARY_ID_UL, iabSoundFieldLabelSubDescriptorBO.getMCALabelDictionnaryId().toString())); } } if (iabSoundFieldLabelSubDescriptorBO.getRFC5646SpokenLanguage() != null && !IMFConstraints.isSpokenLanguageRFC5646Compliant(iabSoundFieldLabelSubDescriptorBO.getRFC5646SpokenLanguage())) { imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Language Code (%s) in IABSoundfieldLabelSubDescriptor in the IMFTrackfile represented by ID %s is not RFC5646 compliant", iabSoundFieldLabelSubDescriptorBO.getRFC5646SpokenLanguage(), packageID.toString()))); } if (iabSoundFieldLabelSubDescriptorBO.getMCAAudioContentKind() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s is missing MCAAudioContentKind", packageID.toString())); } if (iabSoundFieldLabelSubDescriptorBO.getMCAAudioElementKind() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s is missing MCAAudioElementKind", packageID.toString())); } if (iabSoundFieldLabelSubDescriptorBO.getMCATitle() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s is missing MCATitle", packageID.toString())); } if (iabSoundFieldLabelSubDescriptorBO.getMCATitleVersion() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s is missing MCATitleVersion", packageID.toString())); } // Section C.2 if (iabSoundFieldLabelSubDescriptorBO.getMCAChannelID() != null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, IMF_IAB_EXCEPTION_PREFIX + String.format("IABSoundfieldLabelSubDescriptor in the IMFTrackFile represented by ID %s has forbidden MCAChannelID %d", packageID.toString(), iabSoundFieldLabelSubDescriptorBO.getMCAChannelID())); } } } } } } } public static void checkIndexEditRate(IMFConstraints.HeaderPartitionIMF headerPartitionIMF, IndexTableSegment indexTableSegment, IMFErrorLogger imfErrorLogger) { HeaderPartition headerPartition = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition(); Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage; filePackage = (SourcePackage) genericPackage; UUID packageID = filePackage.getPackageMaterialNumberasUUID(); for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); if (sequence == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("TimelineTrack with instanceUID = %s in the IMFTrackFile represented by ID %s has no sequence.", timelineTrack.getInstanceUID(), packageID.toString())); } else { GenericDescriptor genericDescriptor = filePackage.getGenericDescriptor(); if (genericDescriptor instanceof IABEssenceDescriptor) { // Support for st2067-201 IABEssenceDescriptor iabEssenceDescriptor = (IABEssenceDescriptor) genericDescriptor; // Section 5.7 if (timelineTrack.getEditRateNumerator() != indexTableSegment.getIndexEditRate().getNumerator() || timelineTrack.getEditRateDenominator() != indexTableSegment.getIndexEditRate().getDenominator()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_IAB_EXCEPTION_PREFIX + String.format("Timeline Track Edit Rate %d/%d does not match Index Table Segment Index Edit Rate %d/%d in the IMFTrackFile represented by ID %s.", timelineTrack.getEditRateNumerator(), timelineTrack.getEditRateDenominator(), indexTableSegment.getIndexEditRate().getNumerator(), indexTableSegment.getIndexEditRate().getDenominator(), packageID.toString())); } } } } } }
5,071
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_201/IABEssenceDescriptor.java
package com.netflix.imflibrary.st2067_201; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.st0377.header.GenericSoundEssenceDescriptor; import com.netflix.imflibrary.st0377.header.StructuralMetadata; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.List; import java.util.Map; /** * Object model corresponding to IABEssenceDescriptor structural metadata set defined in st2067-201:201x */ @Immutable public class IABEssenceDescriptor extends GenericSoundEssenceDescriptor { final static UL IMF_IAB_TRACK_FILE_LEVEL0_UL = UL.fromULAsURNStringToUL("urn:smpte:ul:060E2B34.0401010D.01010201.02000000"); public final static UL IMMERSIVE_AUDIO_CODING_LABEL = UL.fromULAsURNStringToUL("urn:smpte:ul:060E2B34.04010105.0E090604.00000000"); public final static UL IMF_IAB_ESSENCE_CLIP_WRAPPED_ELEMENT_UL = UL.fromULAsURNStringToUL("urn:smpte:ul:060E2B34.01020101.0D010301.16000D00"); public final static UL IMF_IAB_ESSENCE_CLIP_WRAPPED_CONTAINER_UL = UL.fromULAsURNStringToUL("urn:smpte:ul:060E2B34.0401010D.0D010301.021D0101"); public IABEssenceDescriptor(IABEssenceDescriptorBO iabEssenceDescriptorBO) { this.genericSoundEssenceDescriptorBO = iabEssenceDescriptorBO; } public List<Long> getSampleRate() { return this.genericSoundEssenceDescriptorBO.getSampleRate(); } /** * Object corresponding to a parsed IABEssenceDescriptor structural metadata set defined in st2067_201 */ @Immutable public static final class IABEssenceDescriptorBO extends GenericSoundEssenceDescriptor.GenericSoundEssenceDescriptorBO { /** * Constructor for a IABEssenceDescriptor ByteObject. * * @param header the MXF KLV header (Key and Length field) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public IABEssenceDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header, imfErrorLogger); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); postPopulateCheck(); } public boolean equals(Object other) { if (!(other instanceof IABEssenceDescriptorBO)) { return false; } return super.equals(other); } /** * A method that returns a string representation of a IABEssenceDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); return sb.toString(); } } }
5,072
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st2067_201/IABSoundfieldLabelSubDescriptor.java
package com.netflix.imflibrary.st2067_201; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.header.GenericDescriptor; import com.netflix.imflibrary.st0377.header.MCALabelSubDescriptor; import com.netflix.imflibrary.st0377.header.StructuralMetadata; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to MultiChannelAudioLabelSubDescriptor structural metadata set defined in st20167-201:201x */ @Immutable public final class IABSoundfieldLabelSubDescriptor extends MCALabelSubDescriptor { public static final String IAB_MCA_TAG_SYMBOL = "IAB"; public static final String IAB_MCA_TAG_NAME = "IAB"; public static final UL IAB_MCA_LABEL_DICTIONNARY_ID_UL = UL.fromULAsURNStringToUL("urn:smpte:ul:060E2B34.0401010D.03020221.00000000"); private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + IABSoundfieldLabelSubDescriptor.class.getSimpleName() + " : "; private final IABSoundfieldLabelSubDescriptorBO iabSoundfieldLabelSubDescriptorBO; /** * Constructor for an IABSoundfieldLabelSubDescriptor object * @param iabSoundfieldLabelSubDescriptorBO the parsed IAB Soundfield label sub-descriptor object */ public IABSoundfieldLabelSubDescriptor(IABSoundfieldLabelSubDescriptorBO iabSoundfieldLabelSubDescriptorBO) { this.iabSoundfieldLabelSubDescriptorBO = iabSoundfieldLabelSubDescriptorBO; } /** * A getter for the spoken language in this SubDescriptor * @return string representing the spoken language as defined in RFC-5646 */ public String getRFC5646SpokenLanguage(){ return this.iabSoundfieldLabelSubDescriptorBO.getRFC5646SpokenLanguage(); } /** * A method that returns a string representation of an IABSoundfieldLabelSubDescriptor object. * * @return string representing the object */ public String toString() { return this.iabSoundfieldLabelSubDescriptorBO.toString(); } /** * Object corresponding to a parsed IABSoundfieldLabelSubDescriptor structural metadata set defined in st20167-201:201x */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class IABSoundfieldLabelSubDescriptorBO extends MCALabelSubDescriptor.MCALabelSubDescriptorBO { @MXFProperty(size=16) private final byte[] soundfield_group_link_id = null; //UUID /** * Instantiates a new parsed AudioChannelLabelSubDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public IABSoundfieldLabelSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IABSoundfieldLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.mca_label_dictionary_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IABSoundfieldLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_label_dictionary_id is null"); } if (this.mca_link_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IABSoundfieldLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_link_id is null"); } if (this.mca_tag_symbol == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IABSoundfieldLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_tag_symbol is null"); } } /** * A method that returns a string representation of the object. * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); if (this.soundfield_group_link_id != null) { sb.append(String.format("soundfield_group_link_id = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.soundfield_group_link_id[0], this.soundfield_group_link_id[1], this.soundfield_group_link_id[2], this.soundfield_group_link_id[3], this.soundfield_group_link_id[4], this.soundfield_group_link_id[5], this.soundfield_group_link_id[6], this.soundfield_group_link_id[7], this.soundfield_group_link_id[8], this.soundfield_group_link_id[9], this.soundfield_group_link_id[10], this.soundfield_group_link_id[11], this.soundfield_group_link_id[12], this.soundfield_group_link_id[13], this.soundfield_group_link_id[14], this.soundfield_group_link_id[15])); } return sb.toString(); } } }
5,073
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/IMFAssetMapObjectFieldsFactory.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.writerTools.utils.IMFDocumentsObjectFieldsFactory; public final class IMFAssetMapObjectFieldsFactory { /*Prevent instantiation*/ private IMFAssetMapObjectFieldsFactory() { } /** * A factory method that constructs a 2007 Schema compliant PackingListType object and recursively constructs all of its constituent fields. * Note: Fields that are either Java primitives, wrapperTypes or a subclass of Collection * are not constructed by this method for the reason that the field's accessor methods would do so. * * @return A 2007 schema compliant AssetMapType object */ public static org.smpte_ra.schemas._429_9._2007.am.AssetMapType constructAssetMapType_2007() { org.smpte_ra.schemas._429_9._2007.am.AssetMapType amType_2007 = new org.smpte_ra.schemas._429_9._2007.am.AssetMapType(); IMFDocumentsObjectFieldsFactory.constructObjectFields(amType_2007); return amType_2007; } }
5,074
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/PackingListBuilder.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFAuthoringException; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.writerTools.utils.IMFUUIDGenerator; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.UUID; /** * A class that implements the logic to build a SMPTE st0429-8:2007 or st2067-2:2016 schema compliant PackingList document. */ public class PackingListBuilder { private final UUID uuid; private final XMLGregorianCalendar issueDate; private final String iconId; private final String groupId; private final File workingDirectory; private final IMFErrorLogger imfErrorLogger; public final static String defaultHashAlgorithm = "http://www.w3.org/2000/09/xmldsig#sha1"; private final String pklFileName; /** * A constructor for the PackingListBuilder object * @param uuid that uniquely identifies the PackingList document * @param issueDate date at which the PackingList was issued * @param workingDirectory a folder location where the generated PackingListDocument will be written to * @param imfErrorLogger a logger object to record errors that occur during the creation of the PackingList document */ public PackingListBuilder(@Nonnull UUID uuid, @Nonnull XMLGregorianCalendar issueDate, @Nonnull File workingDirectory, @Nonnull IMFErrorLogger imfErrorLogger){ this.uuid = uuid; this.issueDate = issueDate; this.iconId = null; this.groupId = null; this.workingDirectory = workingDirectory; this.imfErrorLogger = imfErrorLogger; this.pklFileName = "PKL-" + this.uuid.toString() + ".xml"; } /** * A constructor for the PackingListBuilder object * @param uuid that uniquely identifies the PackingList document * @param issueDate date at which the PackingList was issued * @param iconId a urn:uuid: that identifies an external image resource containing a picture illustrating the PackingList * @param groupId a urn:uuid: that is used to create associations between packages * @param workingDirectory a folder location where the generated PackingListDocument will be written to * @param imfErrorLogger a logger object to record errors that occur during the creation of the PackingList document */ public PackingListBuilder(@Nonnull UUID uuid, @Nonnull XMLGregorianCalendar issueDate, @Nonnull String iconId, @Nonnull String groupId, @Nonnull File workingDirectory, @Nonnull IMFErrorLogger imfErrorLogger){ this.uuid = uuid; this.issueDate = issueDate; this.iconId = iconId; this.groupId = groupId; this.workingDirectory = workingDirectory; this.imfErrorLogger = imfErrorLogger; this.pklFileName = "PKL-" + this.uuid.toString() + ".xml"; } /** * A method to construct a UserTextType compliant with the 2007 schema for IMF PackingList documents * @param value the string that is a part of the annotation text * @param language the language code of the annotation text * @return a UserTextType */ public static org.smpte_ra.schemas._429_8._2007.pkl.UserText buildPKLUserTextType_2007(String value, String language){ org.smpte_ra.schemas._429_8._2007.pkl.UserText userText = new org.smpte_ra.schemas._429_8._2007.pkl.UserText(); userText.setValue(value); userText.setLanguage(language); return userText; } /** * A method to construct a UserTextType compliant with the 2016 schema for IMF PackingList documents * @param value the string that is a part of the annotation text * @param language the language code of the annotation text * @return a UserTextType */ public static org.smpte_ra.schemas._2067_2._2016.pkl.UserText buildPKLUserTextType_2016(String value, String language){ org.smpte_ra.schemas._2067_2._2016.pkl.UserText userText = new org.smpte_ra.schemas._2067_2._2016.pkl.UserText(); userText.setValue(value); userText.setLanguage(language); return userText; } /** * A method to construct a Default Digest Method Type with a default HashAlgorithm * @return a DigestMethodType object conforming to the 2016 schema with the default HashAlgorithm */ public org.w3._2000._09.xmldsig_.DigestMethodType buildDefaultDigestMethodType(){ org.w3._2000._09.xmldsig_.DigestMethodType digestMethodType = new org.w3._2000._09.xmldsig_.DigestMethodType(); digestMethodType.setAlgorithm(PackingListBuilder.defaultHashAlgorithm); return digestMethodType; } /** * A method to construct a Digest Method Type with the HashAlgorithm string that was passed in * @param algorithm a String representing the algorithm used for generating the Hash * @return a DigestMethodType object conforming to the 2016 schema with the default HashAlgorithm */ public org.w3._2000._09.xmldsig_.DigestMethodType buildDigestMethodType(String algorithm){ org.w3._2000._09.xmldsig_.DigestMethodType digestMethodType = new org.w3._2000._09.xmldsig_.DigestMethodType(); digestMethodType.setAlgorithm(algorithm); return digestMethodType; } /** * A method to build a PackingList document compliant with the st0429-8:2007 schema * @param annotationText a free form human readable text * @param issuer a free form human readable text describing the issuer of the PackingList document * @param creator a free form human readable text describing the tool used to create the AssetMap document * @param assets a list of PackingListBuilder assets roughly modeling the PackingList Asset compliant * with the st0429-8:2007 schema * @return a list of errors that occurred while generating the PackingList document compliant with the st0429-8:2007 schema * @throws IOException - any I/O related error will be exposed through an IOException */ public List<ErrorLogger.ErrorObject> buildPackingList_2007(@Nonnull org.smpte_ra.schemas._429_8._2007.pkl.UserText annotationText, @Nonnull org.smpte_ra.schemas._429_8._2007.pkl.UserText issuer, @Nonnull org.smpte_ra.schemas._429_8._2007.pkl.UserText creator, @Nonnull List<PackingListBuilderAsset_2007> assets) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); org.smpte_ra.schemas._429_8._2007.pkl.PackingListType packingListType = IMFPKLObjectFieldsFactory.constructPackingListType_2007(); packingListType.setId(UUIDHelper.fromUUID(this.uuid)); packingListType.setAnnotationText(annotationText); packingListType.setIconId(this.iconId); packingListType.setIssueDate(this.issueDate); packingListType.setIssuer(issuer); packingListType.setCreator(creator); packingListType.setGroupId(this.groupId); org.smpte_ra.schemas._429_8._2007.pkl.PackingListType.AssetList assetList = new org.smpte_ra.schemas._429_8._2007.pkl.PackingListType.AssetList(); List<org.smpte_ra.schemas._429_8._2007.pkl.AssetType> packingListAssets = assetList.getAsset(); for(PackingListBuilderAsset_2007 asset : assets){ org.smpte_ra.schemas._429_8._2007.pkl.AssetType packingListAssetType = new org.smpte_ra.schemas._429_8._2007.pkl.AssetType(); packingListAssetType.setId(asset.getUUID()); packingListAssetType.setAnnotationText(asset.getAnnotationText()); packingListAssetType.setHash(asset.getHash()); packingListAssetType.setSize(asset.getSize()); packingListAssetType.setType(asset.getAssetType().toString()); packingListAssetType.setOriginalFileName(asset.getOriginalFileName()); packingListAssets.add(packingListAssetType); } packingListType.setAssetList(assetList); //The following attributes are optional setting them to null so that the JAXB Marshaller will not marshall them packingListType.setSigner(null); packingListType.setSignature(null); File outputFile = new File(this.workingDirectory + File.separator + this.pklFileName); boolean formatted = true; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try( InputStream packingListSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0429_8_2007/PKL/packingList_schema.xsd"); InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"); OutputStream outputStream = new FileOutputStream(outputFile); ) { try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource[] schemaSources = new StreamSource[2]; //The order in which these schema sources are initialized is important because some elements in the //PackingList schema depend on types defined in the DSig schema. schemaSources[0] = new StreamSource(dsigSchemaAsAStream); schemaSources[1] = new StreamSource(packingListSchemaAsAStream); Schema schema = schemaFactory.newSchema(schemaSources); JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas._429_8._2007.pkl"); Marshaller marshaller = jaxbContext.createMarshaller(); ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true); marshaller.setEventHandler(validationEventHandler); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted); /*marshaller.marshal(cplType, output); workaround for 'Error: unable to marshal type "AssetMapType" as an element because it is missing an @XmlRootElement annotation' as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always */ marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/429-8/2007/PKL", "PackingList"), org.smpte_ra.schemas._429_8._2007.pkl.PackingListType.class, packingListType), outputStream); outputStream.close(); if (validationEventHandler.hasErrors()) { //TODO : Perhaps a candidate for a Lambda for (ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, validationErrorObject.getValidationEventSeverity(), validationErrorObject.getErrorMessage()); } } } catch( SAXException | JAXBException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, e.getMessage()); } } return imfErrorLogger.getErrors(); } /** * A class that roughly models a Packing List Asset conformant to the st0429-8:2007 schema */ public static class PackingListBuilderAsset_2007 { private final String uuid; private final org.smpte_ra.schemas._429_8._2007.pkl.UserText annotationText; private final byte[] hash; private final BigInteger size; private final PKLAssetTypeEnum assetType; private final org.smpte_ra.schemas._429_8._2007.pkl.UserText originalFileName; /** * A constructor for a PackingListAsset that roughly models a Packing List Asset conformant to the st0429-8:2007 schema * @param uuid that uniquely identifies this asset in the Packing List * @param annotationText a free form human readable text * @param hash a byte[] containing the Base64 encoded SHA-1 hash of this PackingList Asset * @param size of the asset in bytes * @param assetType could be either text/xml or application/mxf as defined in st0429-8:2007 * @param originalFileName a free form human readable text that contains the name of the file * containing the asset at the time the PackingList was created */ public PackingListBuilderAsset_2007(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._429_8._2007.pkl.UserText annotationText, @Nonnull byte[] hash, @Nonnull Long size, @Nonnull PKLAssetTypeEnum assetType, org.smpte_ra.schemas._429_8._2007.pkl.UserText originalFileName){ this.uuid = UUIDHelper.fromUUID(uuid); this.annotationText = annotationText; this.hash = Arrays.copyOf(hash, hash.length); this.size = BigInteger.valueOf(size); this.assetType = assetType; this.originalFileName = originalFileName; } /** * Getter for the UUID identifying this Packing List Asset * @return a String representing the "urn:uuid:" of this PackingList Asset */ public String getUUID(){ return this.uuid; } /** * Getter for the AnnotationText of this Packing List Asset * @return a UserText representing the Annotation Text */ public org.smpte_ra.schemas._429_8._2007.pkl.UserText getAnnotationText(){ return this.annotationText; } /** * Getter for the Hash of this Packing List Asset * @return a byte[] representing the Base64 encoded SHA-1 Hash of the Asset */ public byte[] getHash(){ return Arrays.copyOf(this.hash, this.hash.length); } /** * Getter for the size of this Packing List Asset * @return a BigInteger representing the size of this PackingList Asset */ public BigInteger getSize(){ return this.size; } /** * Getter for the type of this PackingList Asset * @return an enumerated value representing the type of this PackingList Asset */ public PKLAssetTypeEnum getAssetType(){ return this.assetType; } /** * Getter for the OriginalFileName of this PackingList Asset * @return a UserText representing the OriginalFileName of the PackingList Asset * at the time that the PackingList was created */ public org.smpte_ra.schemas._429_8._2007.pkl.UserText getOriginalFileName(){ return this.originalFileName; } } /** * Getter for the errors in PackingListBuilder * * @return List of errors in PackingListBuilder. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } /** * Getter for the PKL file name for the PackingList * * @return PKL file name for the PackingList. */ public String getPKLFileName() { return this.pklFileName; } public static enum PKLAssetTypeEnum { TEXT_XML("text/xml"), APP_MXF("application/mxf"), UNDEFINED("Undefined"); private final String assetType; /** * To prevent instantiation * @param pklAssetType a string representing the PKL AssetType */ private PKLAssetTypeEnum(String pklAssetType){ this.assetType = pklAssetType; } /** * Getter for the AssetType of the PKLAssetTypeEnum * @return a string indicating the asset type represented by this Enumeration */ public String getAssetType(){ return this.assetType; } public static PKLAssetTypeEnum getAssetTypeEnum(String assetType){ switch (assetType){ case "text/xml": return PKLAssetTypeEnum.TEXT_XML; case "application/mxf": return PKLAssetTypeEnum.APP_MXF; default: return PKLAssetTypeEnum.UNDEFINED; } } /** * The overridden toString() method * @return a string representing this PKLAssetType enumeration */ public String toString(){ return this.assetType; } } /** * A method to build a PackingList document compliant with the st0429-8:2007 schema * @param annotationText a free form human readable text * @param issuer a free form human readable text describing the issuer of the PackingList document * @param creator a free form human readable text describing the tool used to create the AssetMap document * @param assets a list of PackingListBuilder assets roughly modeling the PackingList Asset compliant * with the st0429-8:2007 schema * @return a list of errors that occurred while generating the PackingList document compliant with the st0429-8:2007 schema * @throws IOException - any I/O related error will be exposed through an IOException * @throws SAXException - exposes any issues with instantiating a {@link javax.xml.validation.Schema Schema} object * @throws JAXBException - any issues in serializing the XML document using JAXB are exposed through a JAXBException */ public List<ErrorLogger.ErrorObject> buildPackingList_2016(@Nonnull org.smpte_ra.schemas._2067_2._2016.pkl.UserText annotationText, @Nonnull org.smpte_ra.schemas._2067_2._2016.pkl.UserText issuer, @Nonnull org.smpte_ra.schemas._2067_2._2016.pkl.UserText creator, @Nonnull List<PackingListBuilderAsset_2016> assets) throws IOException, SAXException, JAXBException { int numErrors = imfErrorLogger.getNumberOfErrors(); org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType packingListType = IMFPKLObjectFieldsFactory.constructPackingListType_2016(); packingListType.setId(UUIDHelper.fromUUID(this.uuid)); packingListType.setIconId(this.iconId); packingListType.setAnnotationText(annotationText); packingListType.setIssueDate(this.issueDate); packingListType.setIssuer(issuer); packingListType.setCreator(creator); packingListType.setGroupId(this.groupId); org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType.AssetList assetList = new org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType.AssetList(); List<org.smpte_ra.schemas._2067_2._2016.pkl.AssetType> packingListAssets = assetList.getAsset(); for(PackingListBuilderAsset_2016 asset : assets){ org.smpte_ra.schemas._2067_2._2016.pkl.AssetType packingListAssetType = new org.smpte_ra.schemas._2067_2._2016.pkl.AssetType(); packingListAssetType.setId(asset.getUUID()); packingListAssetType.setAnnotationText(asset.getAnnotationText()); packingListAssetType.setHash(asset.getHash()); packingListAssetType.setSize(asset.getSize()); packingListAssetType.setType(asset.getAssetType().toString()); packingListAssetType.setOriginalFileName(asset.getOriginalFileName()); packingListAssetType.setHashAlgorithm(asset.getHashAlgorithm()); packingListAssets.add(packingListAssetType); } packingListType.setAssetList(assetList); //The following attributes are optional setting them to null so that the JAXB Marshaller will not marshall them packingListType.setSigner(null); packingListType.setSignature(null); File outputFile = new File(this.workingDirectory + File.separator + this.pklFileName); boolean formatted = true; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try( InputStream packingListSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2016/PKL/packingList_schema.xsd"); InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"); OutputStream outputStream = new FileOutputStream(outputFile); ) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI ); StreamSource[] schemaSources = new StreamSource[2]; //The order in which these schema sources are initialized is important because some elements in the //PackingList schema depend on types defined in the DSig schema. schemaSources[0] = new StreamSource(dsigSchemaAsAStream); schemaSources[1] = new StreamSource(packingListSchemaAsAStream); Schema schema = schemaFactory.newSchema(schemaSources); JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas._2067_2._2016.pkl"); Marshaller marshaller = jaxbContext.createMarshaller(); ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true); marshaller.setEventHandler(validationEventHandler); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted); /*marshaller.marshal(cplType, output); workaround for 'Error: unable to marshal type "AssetMapType" as an element because it is missing an @XmlRootElement annotation' as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always */ marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/2067-2/2016/PKL", "PackingList"), org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType.class, packingListType), outputStream); outputStream.close(); if(validationEventHandler.hasErrors()) { //TODO : Perhaps a candidate for a Lambda for(ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR, validationErrorObject.getValidationEventSeverity(), validationErrorObject.getErrorMessage()); } } } if(this.imfErrorLogger.getNumberOfErrors() > numErrors){ List<ErrorLogger.ErrorObject> fatalErrors = imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, this.imfErrorLogger.getNumberOfErrors()); if(fatalErrors.size() > 0){ throw new IMFAuthoringException(String.format("Following FATAL errors were detected while building the PackingList document %s", fatalErrors.toString())); } } return imfErrorLogger.getErrors(); } /** * A class that roughly models a Packing List Asset conformant to the st0429-8:2007 schema */ public static class PackingListBuilderAsset_2016 { private final String uuid; private final org.smpte_ra.schemas._2067_2._2016.pkl.UserText annotationText; private final byte[] hash; private final org.w3._2000._09.xmldsig_.DigestMethodType hashAlgorithm; private final BigInteger size; private final PKLAssetTypeEnum assetType; private final org.smpte_ra.schemas._2067_2._2016.pkl.UserText originalFileName; /** * A constructor for a PackingListAsset that roughly models a Packing List Asset conformant to the st0429-8:2007 schema * @param uuid that uniquely identifies this asset in the Packing List * @param annotationText a free form human readable text * @param hash a byte[] containing the Base64 encoded SHA-1 hash of this PackingList Asset * @param hashAlgorithm a String representing the algorithm used to generate the Hash * @param size of the asset in bytes * @param assetType could be either text/xml or application/mxf as defined in st0429-8:2007 * @param originalFileName a free form human readable text that contains the name of the file * containing the asset at the time the PackingList was created */ public PackingListBuilderAsset_2016(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._2067_2._2016.pkl.UserText annotationText, @Nonnull byte[] hash, @Nonnull org.w3._2000._09.xmldsig_.DigestMethodType hashAlgorithm, @Nonnull Long size, @Nonnull PKLAssetTypeEnum assetType, org.smpte_ra.schemas._2067_2._2016.pkl.UserText originalFileName){ this.uuid = UUIDHelper.fromUUID(uuid); this.annotationText = annotationText; this.hash = Arrays.copyOf(hash, hash.length); this.hashAlgorithm = hashAlgorithm; this.size = BigInteger.valueOf(size); this.assetType = assetType; this.originalFileName = originalFileName; } /** * Getter for the UUID identifying this Packing List Asset * @return a String representing the "urn:uuid:" of this PackingList Asset */ public String getUUID(){ return this.uuid; } /** * Getter for the AnnotationText of this Packing List Asset * @return a UserText representing the Annotation Text */ public org.smpte_ra.schemas._2067_2._2016.pkl.UserText getAnnotationText(){ return this.annotationText; } /** * Getter for the Hash of this Packing List Asset * @return a byte[] representing the Base64 encoded SHA-1 Hash of the Asset */ public byte[] getHash(){ return Arrays.copyOf(this.hash, this.hash.length); } /** * Getter for the HashAlgorithm used to generate the Hash of this PackingList Asset * @return a org.w3._2000._09.xmldsig_.DigestMethodType representing the Hashing algorithm */ public org.w3._2000._09.xmldsig_.DigestMethodType getHashAlgorithm(){ return this.hashAlgorithm; } /** * Getter for the size of this Packing List Asset * @return a BigInteger representing the size of this PackingList Asset */ public BigInteger getSize(){ return this.size; } /** * Getter for the type of this PackingList Asset * @return an enumerated value representing the type of this PackingList Asset */ public PKLAssetTypeEnum getAssetType(){ return this.assetType; } /** * Getter for the OriginalFileName of this PackingList Asset * @return a UserText representing the OriginalFileName of the PackingList Asset * at the time that the PackingList was created */ public org.smpte_ra.schemas._2067_2._2016.pkl.UserText getOriginalFileName(){ return this.originalFileName; } } }
5,075
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/CompositionPlaylistBuilder_2016.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFAuthoringException; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.st2067_2.CoreConstraints; import com.netflix.imflibrary.st2067_2.IMFEssenceComponentVirtualTrack; import com.netflix.imflibrary.st2067_2.IMFEssenceDescriptorBaseType; import com.netflix.imflibrary.st2067_2.IMFMarkerResourceType; import com.netflix.imflibrary.st2067_2.IMFMarkerType; import com.netflix.imflibrary.st2067_2.IMFMarkerVirtualTrack; import com.netflix.imflibrary.st2067_2.IMFTrackFileResourceType; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.writerTools.utils.IMFUUIDGenerator; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType; import org.smpte_ra.schemas._2067_3._2016.CompositionTimecodeType; import org.smpte_ra.schemas._2067_3._2016.ContentVersionType; import org.smpte_ra.schemas._2067_3._2016.EssenceDescriptorBaseType; import org.smpte_ra.schemas._2067_3._2016.SegmentType; import org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; /** * A class that implements the logic to build a SMPTE st2067-2:2016 schema compliant CompositionPlaylist document. */ public class CompositionPlaylistBuilder_2016 { private final UUID uuid; private final XMLGregorianCalendar issueDate; private final org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText; private final org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType issuer; private final org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType creator; private final List<? extends Composition.VirtualTrack> virtualTracks; private final List<Long> compositionEditRate; private final Long totalRunningTime; private final Map<UUID, IMPBuilder.IMFTrackFileInfo> trackFileInfoMap; private final File workingDirectory; private final IMFErrorLogger imfErrorLogger; private final Map<Node, String> essenceDescriptorIDMap = new HashMap<>(); private final List<org.smpte_ra.schemas._2067_3._2016.SegmentType> segments = new ArrayList<>(); private final List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList; public final static String defaultHashAlgorithm = "http://www.w3.org/2000/09/xmldsig#sha1"; private final static String defaultContentKindScope = "http://www.smpte-ra.org/schemas/2067-3/XXXX#content-kind"; private final String cplFileName; private final Set<String> applicationIds; private final String coreConstraintsSchema; private final Map<UUID, UUID> trackResourceSourceEncodingMap; /** * A constructor for CompositionPlaylistBuilder class to build a CompositionPlaylist document compliant with st2067-2:2016 schema * @param uuid identifying the CompositionPlaylist document * @param annotationText a free form human readable text * @param issuer a free form human readable text describing the issuer of the CompositionPlaylist document * @param creator a free form human readable text describing the tool used to create the CompositionPlaylist document * @param virtualTracks a list of VirtualTracks of the Composition * @param compositionEditRate the edit rate of the Composition * @param applicationIds ApplicationIds for the composition * @param totalRunningTime a long value representing in seconds the total running time of this composition * @param trackFileInfoMap a map of the IMFTrackFile's UUID to the track file info * @param workingDirectory a folder location where the constructed CPL document can be written to * @param imfEssenceDescriptorBaseTypeList List of IMFEssenceDescriptorBaseType * @param coreConstraintsSchema schema defining core constraints version */ public CompositionPlaylistBuilder_2016(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType issuer, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType creator, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull Set<String> applicationIds, long totalRunningTime, @Nonnull Map<UUID, IMPBuilder.IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList, @Nonnull String coreConstraintsSchema, Map<UUID, UUID> trackFileIdToEssenceDescriptorIdMap){ this.uuid = uuid; this.annotationText = annotationText; this.issuer = issuer; this.creator = creator; this.issueDate = IMFUtils.createXMLGregorianCalendar(); this.virtualTracks = Collections.unmodifiableList(virtualTracks); this.compositionEditRate = Collections.unmodifiableList(Arrays.asList(compositionEditRate.getNumerator(), compositionEditRate.getDenominator())); this.totalRunningTime = totalRunningTime; this.trackFileInfoMap = Collections.unmodifiableMap(trackFileInfoMap); this.workingDirectory = workingDirectory; this.imfErrorLogger = new IMFErrorLoggerImpl(); this.cplFileName = "CPL-" + this.uuid.toString() + ".xml"; this.applicationIds = Collections.unmodifiableSet(applicationIds); this.imfEssenceDescriptorBaseTypeList = Collections.unmodifiableList(imfEssenceDescriptorBaseTypeList); this.coreConstraintsSchema = coreConstraintsSchema; Map<UUID, UUID> trackEncodingMap = new HashMap<>(); //Map of TrackFileId -> SourceEncodingElement of each resource of this VirtualTrack for(Composition.VirtualTrack virtualTrack : virtualTracks) { if (!(virtualTrack instanceof IMFEssenceComponentVirtualTrack)) { continue; // Skip non-essence tracks } IMFEssenceComponentVirtualTrack essenceTrack = (IMFEssenceComponentVirtualTrack) virtualTrack; for (IMFTrackFileResourceType trackResource : essenceTrack.getTrackFileResourceList()) { UUID sourceEncoding = trackEncodingMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId())); // To avoid mismatched essenceDescriptorId and sourceEncodingId, we use the trackFileIdToEssenceDescriptorIdMap. If this function is called by the deprecated constructor, // we run the risk of mismatch ONLY if there are multiple essence descriptors for the same virtualTrackFile in the input CPL. if (sourceEncoding == null) { if (trackFileIdToEssenceDescriptorIdMap != null) { trackEncodingMap.put(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId()), trackFileIdToEssenceDescriptorIdMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId()))); } else { trackEncodingMap.put(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId()), UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getSourceEncoding())); } } } } this.trackResourceSourceEncodingMap = Collections.unmodifiableMap(trackEncodingMap); } /** * @deprecated Instead use {{@link #CompositionPlaylistBuilder_2016(UUID, UserTextType, UserTextType, UserTextType, List, Composition.EditRate, Set, long, Map, File, List, String)}} * A constructor for CompositionPlaylistBuilder class to build a CompositionPlaylist document compliant with st2067-2:2016 schema * @param uuid identifying the CompositionPlaylist document * @param annotationText a free form human readable text * @param issuer a free form human readable text describing the issuer of the CompositionPlaylist document * @param creator a free form human readable text describing the tool used to create the CompositionPlaylist document * @param virtualTracks a list of VirtualTracks of the Composition * @param compositionEditRate the edit rate of the Composition * @param applicationId ApplicationId for the composition * @param totalRunningTime a long value representing in seconds the total running time of this composition * @param trackFileInfoMap a map of the IMFTrackFile's UUID to the track file info * @param workingDirectory a folder location where the constructed CPL document can be written to * @param imfEssenceDescriptorBaseTypeList List of IMFEssenceDescriptorBaseType */ @Deprecated public CompositionPlaylistBuilder_2016(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType issuer, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType creator, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, long totalRunningTime, @Nonnull Map<UUID, IMPBuilder.IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList){ this(uuid, annotationText, issuer, creator, virtualTracks, compositionEditRate, Collections.singleton(applicationId), totalRunningTime, trackFileInfoMap, workingDirectory, imfEssenceDescriptorBaseTypeList, CoreConstraints.NAMESPACE_IMF_2016, null); } /** * A method to build a CompositionPlaylist document conforming to the st2067-2/3:2016 schema * @return a list of errors resulting during the creation of the CPL document * @throws IOException - any I/O related error is exposed through an IOException * @throws ParserConfigurationException if a DocumentBuilder * cannot be created which satisfies the configuration requested * @throws SAXException - exposes any issues with instantiating a {@link javax.xml.validation.Schema Schema} object * @throws JAXBException - any issues in serializing the XML document using JAXB are exposed through a JAXBException */ public List<ErrorLogger.ErrorObject> build() throws IOException, ParserConfigurationException, SAXException, JAXBException { org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType cplRoot = IMFCPLObjectFieldsFactory.constructCompositionPlaylistType_2016(); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); cplRoot.setId(UUIDHelper.fromUUID(this.uuid)); cplRoot.setAnnotation(this.annotationText); cplRoot.setIssueDate(IMFUtils.createXMLGregorianCalendar()); cplRoot.setIssuer(this.issuer); cplRoot.setCreator(this.creator); cplRoot.setContentOriginator(null); cplRoot.setContentTitle(buildCPLUserTextType_2016("Not Included", "en")); cplRoot.setContentKind(null); org.smpte_ra.schemas._2067_3._2016.ContentVersionType contentVersionType = buildContentVersionType(IMFUUIDGenerator.getInstance().getUrnUUID(), buildCPLUserTextType_2016("Photon CompositionPlaylistBuilder", "en")); List<org.smpte_ra.schemas._2067_3._2016.ContentVersionType> contentVersionTypeList = new ArrayList<>(); contentVersionTypeList.add(contentVersionType); cplRoot.setContentVersionList(buildContentVersionList(contentVersionTypeList)); cplRoot.setLocaleList(null); cplRoot.setExtensionProperties(null); cplRoot.getEditRate().addAll(this.compositionEditRate); /*long compositionEditRate = (this.compositionEditRate.get(0)/ this.compositionEditRate.get(1)); cplRoot.setCompositionTimecode(buildCompositionTimeCode(BigInteger.valueOf(compositionEditRate))); */ cplRoot.setCompositionTimecode(null); cplRoot.setTotalRunningTime(String.format("%02d:%02d:%02d", totalRunningTime / 3600, (totalRunningTime % 3600) / 60, (totalRunningTime % 60))); /** * Process each VirtualTrack that is a part of this Composition */ List<CompositionPlaylistBuilder_2016.SequenceTypeTuple> sequenceTypeTuples = new ArrayList<>(); for(Composition.VirtualTrack virtualTrack : virtualTracks) { /** * Build TrackResourceList */ List<org.smpte_ra.schemas._2067_3._2016.BaseResourceType> trackResourceList = buildTrackResourceList(virtualTrack); /** * Build the Sequence */ UUID sequenceId = IMFUUIDGenerator.getInstance().generateUUID(); UUID trackId = IMFUUIDGenerator.getInstance().generateUUID(); SequenceTypeTuple sequenceTypeTuple = buildSequenceTypeTuple(sequenceId, trackId, buildResourceList(trackResourceList), virtualTrack.getSequenceTypeEnum()); sequenceTypeTuples.add(sequenceTypeTuple); } org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.EssenceDescriptorList essenceDescriptorListType = buildEssenceDescriptorList(this.imfEssenceDescriptorBaseTypeList); cplRoot.setEssenceDescriptorList(essenceDescriptorListType); UUID segmentId = IMFUUIDGenerator.getInstance().generateUUID(); org.smpte_ra.schemas._2067_3._2016.SegmentType segmentType = buildSegment(segmentId, buildCPLUserTextType_2016("Segment-1", "en")); populateSequenceListForSegment(sequenceTypeTuples, segmentType); cplRoot.setSegmentList(buildSegmentList(new ArrayList<SegmentType>(){{add(segmentType);}})); cplRoot.setSigner(null); cplRoot.setSignature(null); if (!this.applicationIds.isEmpty()) { JAXBElement<List<String>> appIdElement; if (this.coreConstraintsSchema.equals(CoreConstraints.NAMESPACE_IMF_2020)) { appIdElement = new org.smpte_ra.ns._2067_2._2020.ObjectFactory().createApplicationIdentification(new ArrayList<>(this.applicationIds)); } else { appIdElement = new org.smpte_ra.schemas._2067_2._2016.ObjectFactory().createApplicationIdentification(new ArrayList<>(this.applicationIds)); } org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.ExtensionProperties extensionProperties = new org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.ExtensionProperties(); extensionProperties.getAny().add(appIdElement); cplRoot.setExtensionProperties( extensionProperties); } File outputFile = new File(this.workingDirectory + File.separator + this.cplFileName); serializeCPLToXML(cplRoot, outputFile); return imfErrorLogger.getErrors(); } private List<org.smpte_ra.schemas._2067_3._2016.BaseResourceType> buildTrackResourceList(Composition.VirtualTrack virtualTrack){ List<org.smpte_ra.schemas._2067_3._2016.BaseResourceType> trackResourceList = new ArrayList<>(); // Wrap essence track file resources into the JAXB class if (virtualTrack instanceof IMFEssenceComponentVirtualTrack) { IMFEssenceComponentVirtualTrack essenceTrack = (IMFEssenceComponentVirtualTrack) virtualTrack; for (IMFTrackFileResourceType trackFileResource : essenceTrack.getTrackFileResourceList()) { trackResourceList.add(buildTrackFileResource(trackFileResource)); } } // Wrap marker track resources into the JAXB class else if (virtualTrack instanceof IMFMarkerVirtualTrack) { IMFMarkerVirtualTrack markerTrack = (IMFMarkerVirtualTrack) virtualTrack; for (IMFMarkerResourceType markerResource : markerTrack.getMarkerResourceList()) { trackResourceList.add(buildMarkerResource(markerResource)); } } return Collections.unmodifiableList(trackResourceList); } // TODO- Refactor this and consolidate all marshall/unmarshall logic into CompositionModel_st2067_2_2016.java private void serializeCPLToXML(org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType cplRoot, File outputFile) throws IOException, JAXBException, SAXException{ int numErrors = imfErrorLogger.getNumberOfErrors(); boolean formatted = true; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try( InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"); InputStream dcmlSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd"); InputStream cplSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_3_2016/imf-cpl-20160411.xsd"); InputStream coreConstraintsSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2016/imf-core-constraints-20160411.xsd"); InputStream xsd_core_constraints_2020 = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2020/imf-core-constraints-2020.xsd"); OutputStream outputStream = new FileOutputStream(outputFile) ) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI ); StreamSource[] schemaSources = new StreamSource[5]; schemaSources[0] = new StreamSource(dsigSchemaAsAStream); schemaSources[1] = new StreamSource(dcmlSchemaAsAStream); schemaSources[2] = new StreamSource(cplSchemaAsAStream); schemaSources[3] = new StreamSource(coreConstraintsSchemaAsAStream); schemaSources[4] = new StreamSource(xsd_core_constraints_2020); Schema schema = schemaFactory.newSchema(schemaSources); JAXBContext jaxbContext = JAXBContext.newInstance( org.smpte_ra.schemas._2067_3._2016.ObjectFactory.class, // 2016 CPL org.smpte_ra.schemas._2067_2._2016.ObjectFactory.class, // 2016 Core constraints org.smpte_ra.ns._2067_2._2020.ObjectFactory.class, // 2020 Core constraints org.smpte_ra.ns._2067_201._2019.ObjectFactory.class); // IAB Marshaller marshaller = jaxbContext.createMarshaller(); ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true); marshaller.setEventHandler(validationEventHandler); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted); /*marshaller.marshal(cplType, output); workaround for 'Error: unable to marshal type "CompositionPlaylistType" as an element because it is missing an @XmlRootElement annotation' as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always */ marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/2067-3/2016", "CompositionPlaylist"), CompositionPlaylistType.class, cplRoot), outputStream); if(this.imfErrorLogger.getNumberOfErrors() > numErrors){ List<ErrorLogger.ErrorObject> fatalErrors = imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, this.imfErrorLogger.getNumberOfErrors()); if(fatalErrors.size() > 0){ throw new IMFAuthoringException(String.format("Following FATAL errors were detected while building the PackingList document %s", fatalErrors.toString())); } } } } /** * A method to construct a UserTextType compliant with the 2016 schema for IMF CompositionPlaylist documents * @param value the string that is a part of the annotation text * @param language the language code of the annotation text * @return a UserTextType conforming to the 2016 schema */ public static org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType buildCPLUserTextType_2016(String value, String language){ org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType userTextType = new org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType(); userTextType.setValue(value); userTextType.setLanguage(language); return userTextType; } /** * A method to construct a ContentKindType object conforming to the 2016 schema * @param value the string correspding to the Content Kind * @param scope a string corresponding to the scope attribute of a Content Kind * @return a ContentKind object conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.ContentKindType buildContentKindType(@Nonnull String value, String scope) { org.smpte_ra.schemas._2067_3._2016.ContentKindType contentKindType = new org.smpte_ra.schemas._2067_3._2016.ContentKindType(); if(!scope.matches("^[a-zA-Z0-9._-]+") == true) { this.imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The ContentKind scope %s does not follow the syntax of a valid URI (a-z, A-Z, 0-9, ., _, -)", scope))); contentKindType.setScope(scope); } else{ contentKindType.setScope(scope); } contentKindType.setValue(value); return contentKindType; } /** * A method to construct a ContentVersionType object conforming to the 2016 schema * @param id urn uuid corresponding to the content version type * @param value a UserTextType representing the value attribute of the ContentVersion * @return a content version object conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.ContentVersionType buildContentVersionType(String id, org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType value) { ContentVersionType contentVersionType = new ContentVersionType(); contentVersionType.setId(id); contentVersionType.setLabelText(value); return contentVersionType; } /** * A method to construct a ContentVersionList object conforming to the 2016 schema * @param contentVersions a list of ContentVersion objects conforming to the 2016 schema * @return a content version list object conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.ContentVersionList buildContentVersionList(List<org.smpte_ra.schemas._2067_3._2016.ContentVersionType> contentVersions){ org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.ContentVersionList contentVersionList = new CompositionPlaylistType.ContentVersionList(); contentVersionList.getContentVersion().addAll(contentVersions); return contentVersionList; } /** * A method to construct an EssenceDescriptorBaseType object conforming to the 2016 schema * @param id a UUID identifying the EssenceDescriptor. Note : This value should be the same as the SourceEncoding Element of * the resource in a VirtualTrack of this composition whose EssenceDescriptor it represents in the EssenceDescriptorList. This cannot be enforced * hence the responsibility is with the caller to ensure this else the generated CPL fail validation checks. * @param node a regxml representation of an EssenceDescriptor * @return a EssenceDescriptorBaseType object conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.EssenceDescriptorBaseType buildEssenceDescriptorBaseType(UUID id, Node node){ org.smpte_ra.schemas._2067_3._2016.EssenceDescriptorBaseType essenceDescriptorBaseType = new org.smpte_ra.schemas._2067_3._2016.EssenceDescriptorBaseType(); essenceDescriptorBaseType.setId(UUIDHelper.fromUUID(id)); this.essenceDescriptorIDMap.put(node, UUIDHelper.fromUUID(id)); essenceDescriptorBaseType.getAny().add(node); return essenceDescriptorBaseType; } /** * A method to construct an EssenceDescriptorList conforming to the 2016 schema * @param imfEssenceDescriptorBaseTypeList a list of IMFEssenceDescriptorBaseType objects * @return EssenceDescriptorList type object */ public org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.EssenceDescriptorList buildEssenceDescriptorList(List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList){ org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.EssenceDescriptorList essenceDescriptorList = new org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.EssenceDescriptorList(); essenceDescriptorList.getEssenceDescriptor().addAll(imfEssenceDescriptorBaseTypeList.stream().map(e -> { EssenceDescriptorBaseType essenceDescriptorBaseType = new EssenceDescriptorBaseType(); essenceDescriptorBaseType.setId(UUIDHelper.fromUUID(e.getId())); essenceDescriptorBaseType.getAny().addAll(e.getAny()); return essenceDescriptorBaseType; }).collect(Collectors.toList())); return essenceDescriptorList; } /** * A method to construct a CompositionTimecodeType conforming to the 2016 schema * @param compositionEditRate the EditRate corresponding to the Composition's EditRate * @return a CompositionTimecodeType conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.CompositionTimecodeType buildCompositionTimeCode(BigInteger compositionEditRate){ org.smpte_ra.schemas._2067_3._2016.CompositionTimecodeType compositionTimecodeType = new CompositionTimecodeType(); compositionTimecodeType.setTimecodeDropFrame(false);/*TimecodeDropFrame set to false by default*/ compositionTimecodeType.setTimecodeRate(compositionEditRate); compositionTimecodeType.setTimecodeStartAddress(IMFUtils.generateTimecodeStartAddress()); return compositionTimecodeType; } /** * A method to construct a LocaleType conforming to the 2016 schema * @param annotationText for the localeType * @param languages a list of string representing Language Tags as specified in RFC-5646 * @param regions a list of strings representing regions * @param contentMaturityRatings a list of ContentMaturityRating objects conforming to the 2016 schema * @return a LocaleType object conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.LocaleType buildLocaleType(org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText, List<String> languages, List<String> regions, List<org.smpte_ra.schemas._2067_3._2016.ContentMaturityRatingType> contentMaturityRatings){ org.smpte_ra.schemas._2067_3._2016.LocaleType localeType = new org.smpte_ra.schemas._2067_3._2016.LocaleType(); localeType.setAnnotation(annotationText); org.smpte_ra.schemas._2067_3._2016.LocaleType.LanguageList languageList = new org.smpte_ra.schemas._2067_3._2016.LocaleType.LanguageList(); languageList.getLanguage().addAll(languages); localeType.setLanguageList(languageList); org.smpte_ra.schemas._2067_3._2016.LocaleType.RegionList regionList = new org.smpte_ra.schemas._2067_3._2016.LocaleType.RegionList(); regionList.getRegion().addAll(regions); localeType.setRegionList(regionList); org.smpte_ra.schemas._2067_3._2016.LocaleType.ContentMaturityRatingList contentMaturityRatingList = new org.smpte_ra.schemas._2067_3._2016.LocaleType.ContentMaturityRatingList(); contentMaturityRatingList.getContentMaturityRating().addAll(contentMaturityRatings); return localeType; } /** * A method to construct a ContentMaturityRatingType conforming to the 2016 schema * @param agency a string representing the agency that issued the rating for this Composition * @param rating a human-readable representation of the rating of this Composition * @param audience a human-readable representation of the intended target audience of this Composition * @return a ContentMaturityRating object conforming to the 2016 schema * @throws URISyntaxException any syntax errors with the agency attribute is exposed through a URISyntaxException */ public org.smpte_ra.schemas._2067_3._2016.ContentMaturityRatingType buildContentMaturityRatingType(String agency, String rating, org.smpte_ra.schemas._2067_3._2016.ContentMaturityRatingType.Audience audience) throws URISyntaxException { org.smpte_ra.schemas._2067_3._2016.ContentMaturityRatingType contentMaturityRatingType = new org.smpte_ra.schemas._2067_3._2016.ContentMaturityRatingType(); if(!agency.matches("^[a-zA-Z0-9._-]+") == true) { //this.imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The ContentKind scope %s does not follow the syntax of a valid URI (a-z, A-Z, 0-9, ., _, -)", id))); throw new URISyntaxException("Invalid URI", "The ContentMaturityRating agency %s does not follow the syntax of a valid URI (a-z, A-Z, 0-9, ., _, -)"); } contentMaturityRatingType.setAgency(agency); contentMaturityRatingType.setRating(rating); contentMaturityRatingType.setAudience(audience); return contentMaturityRatingType; } /** * A method to construct a SegmentType conforming to the 2016 schema * @param id a uuid identifying the segment * @param annotationText a human readable annotation describing the Segment conforming to the 2016 schema * @return a SegmentType conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.SegmentType buildSegment(UUID id, org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText){ org.smpte_ra.schemas._2067_3._2016.SegmentType segment = new org.smpte_ra.schemas._2067_3._2016.SegmentType(); segment.setId(UUIDHelper.fromUUID(uuid)); segment.setAnnotation(annotationText); org.smpte_ra.schemas._2067_3._2016.SegmentType.SequenceList sequenceList = new org.smpte_ra.schemas._2067_3._2016.SegmentType.SequenceList(); segment.setSequenceList(sequenceList); this.segments.add(segment); return segment; } /** * A method to construct a SegmentList conforming to the 2016 schema * @param segments a list of Segments conforming to the 2016 schema * @return a SegmentList conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.SegmentList buildSegmentList(List<org.smpte_ra.schemas._2067_3._2016.SegmentType> segments){ org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.SegmentList segmentList = new org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType.SegmentList(); segmentList.getSegment().addAll(segments); return segmentList; } /** * A method to construct a SequenceTypeTuple object that maintains a reference to the SequenceType object conforming to the 2016 schema * and the type of the sequence * @param id a uuid identifying the sequence * @param trackId a uuid identifying the virtual track to which this SequenceBelongs. Note : This Id should remain constant across Segments for * a Sequence that belongs to a VirtualTrack, please see the definition of a TrackId in st2067-3:2016 * @param resourceList a list of resources corresponding to this Sequence * @param sequenceType an enumeration identifying the contents of this Sequence (Currently we only support serializing * MainImageSequence and MainAudioSequence to a CPL) * @return a SequenceTypeTuple that maintains a reference to a Sequence and its type */ public SequenceTypeTuple buildSequenceTypeTuple(UUID id, UUID trackId, org.smpte_ra.schemas._2067_3._2016.SequenceType.ResourceList resourceList, Composition.SequenceTypeEnum sequenceType){ org.smpte_ra.schemas._2067_3._2016.SequenceType sequence = new org.smpte_ra.schemas._2067_3._2016.SequenceType(); sequence.setId(UUIDHelper.fromUUID(id)); sequence.setTrackId(UUIDHelper.fromUUID(trackId)); sequence.setResourceList(resourceList); return new SequenceTypeTuple(sequence, sequenceType); } /** * A method to construct a ResourceList for a Sequence conforming to the 2016 schema * @param trackResourceList a list of BaseResourceTypes * @return a resource list conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.SequenceType.ResourceList buildResourceList(List<org.smpte_ra.schemas._2067_3._2016.BaseResourceType> trackResourceList){ org.smpte_ra.schemas._2067_3._2016.SequenceType.ResourceList resourceList = new org.smpte_ra.schemas._2067_3._2016.SequenceType.ResourceList(); resourceList.getResource().addAll(trackResourceList); return resourceList; } /** * A method to populate the SequenceList of a VirtualTrack segment * @param sequenceTypeTuples a SequenceTypeTuple that maintains a reference to a Sequence and its type. This type is * deliberately an opaque object whose definition is not known outside this builder. This * is done in order to allow robust construction of a SequenceList serially. * @param segment a VirtualTrack Segment conforming to the 2016 schema */ public void populateSequenceListForSegment(List<SequenceTypeTuple> sequenceTypeTuples, org.smpte_ra.schemas._2067_3._2016.SegmentType segment) { List<Object> any = segment.getSequenceList().getAny(); if (this.coreConstraintsSchema.equals(CoreConstraints.NAMESPACE_IMF_2020)) { org.smpte_ra.ns._2067_2._2020.ObjectFactory objectFactory = new org.smpte_ra.ns._2067_2._2020.ObjectFactory(); org.smpte_ra.ns._2067_201._2019.ObjectFactory iabFactory = new org.smpte_ra.ns._2067_201._2019.ObjectFactory(); for(SequenceTypeTuple sequenceTypeTuple : sequenceTypeTuples){ switch(sequenceTypeTuple.getSequenceType()){ case MainImageSequence: any.add(objectFactory.createMainImageSequence(sequenceTypeTuple.getSequence())); break; case MainAudioSequence: any.add(objectFactory.createMainAudioSequence(sequenceTypeTuple.getSequence())); break; case IABSequence: // JAXB class for IABSequence was generated in the CC 2016 package. Use that any.add(iabFactory.createIABSequence(sequenceTypeTuple.getSequence())); break; case MarkerSequence: segment.getSequenceList().setMarkerSequence(sequenceTypeTuple.getSequence()); break; default: throw new IMFAuthoringException(String.format("Currently we only support %s, %s, %s, and %s sequence types in building a Composition Playlist document, the type of sequence being requested is %s", Composition.SequenceTypeEnum.MainAudioSequence, Composition.SequenceTypeEnum.MainImageSequence, Composition.SequenceTypeEnum.IABSequence, Composition.SequenceTypeEnum.MarkerSequence, sequenceTypeTuple.getSequenceType())); } } } else { org.smpte_ra.schemas._2067_2._2016.ObjectFactory objectFactory = new org.smpte_ra.schemas._2067_2._2016.ObjectFactory(); org.smpte_ra.ns._2067_201._2019.ObjectFactory iabFactory = new org.smpte_ra.ns._2067_201._2019.ObjectFactory(); for(SequenceTypeTuple sequenceTypeTuple : sequenceTypeTuples){ switch(sequenceTypeTuple.getSequenceType()){ case MainImageSequence: any.add(objectFactory.createMainImageSequence(sequenceTypeTuple.getSequence())); break; case MainAudioSequence: any.add(objectFactory.createMainAudioSequence(sequenceTypeTuple.getSequence())); break; case IABSequence: any.add(iabFactory.createIABSequence(sequenceTypeTuple.getSequence())); break; case MarkerSequence: segment.getSequenceList().setMarkerSequence(sequenceTypeTuple.getSequence()); break; default: throw new IMFAuthoringException(String.format("Currently we only support %s, %s, %s, and %s sequence types in building a Composition Playlist document, the type of sequence being requested is %s", Composition.SequenceTypeEnum.MainAudioSequence, Composition.SequenceTypeEnum.MainImageSequence, Composition.SequenceTypeEnum.IABSequence, Composition.SequenceTypeEnum.MarkerSequence, sequenceTypeTuple.getSequenceType())); } } } } /** * A method to construct a TrackFileResourceType conforming to the 2016 schema * @param trackResource an object that roughly models a TrackFileResourceType * @return a BaseResourceType conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.BaseResourceType buildTrackFileResource(IMFTrackFileResourceType trackResource){ org.smpte_ra.schemas._2067_3._2016.TrackFileResourceType trackFileResource = new org.smpte_ra.schemas._2067_3._2016.TrackFileResourceType(); trackFileResource.setId(trackResource.getId()); trackFileResource.setAnnotation(null); trackFileResource.setTrackFileId(trackResource.getTrackFileId()); trackFileResource.getEditRate().add(trackResource.getEditRate().getNumerator()); trackFileResource.getEditRate().add(trackResource.getEditRate().getDenominator()); trackFileResource.setIntrinsicDuration(trackResource.getIntrinsicDuration()); trackFileResource.setEntryPoint(trackResource.getEntryPoint()); trackFileResource.setSourceDuration(trackResource.getSourceDuration()); trackFileResource.setRepeatCount(trackResource.getRepeatCount()); trackFileResource.setSourceEncoding(UUIDHelper.fromUUID(this.trackResourceSourceEncodingMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId())))); trackFileResource.setHash(trackResource.getHash()); trackFileResource.setHashAlgorithm(buildDefaultDigestMethodType()); return trackFileResource; } /** * A method to construct a MarkerResourceType conforming to the 2016 schema * @param markerResource an object that roughly models a MarkerResourceType * @return a MarkerResourceType conforming to the 2016 schema */ public org.smpte_ra.schemas._2067_3._2016.MarkerResourceType buildMarkerResource(IMFMarkerResourceType markerResource){ org.smpte_ra.schemas._2067_3._2016.MarkerResourceType jaxbMarkerResource = new org.smpte_ra.schemas._2067_3._2016.MarkerResourceType(); jaxbMarkerResource.setId(markerResource.getId()); jaxbMarkerResource.setAnnotation(null); jaxbMarkerResource.getEditRate().add(markerResource.getEditRate().getNumerator()); jaxbMarkerResource.getEditRate().add(markerResource.getEditRate().getDenominator()); jaxbMarkerResource.setIntrinsicDuration(markerResource.getIntrinsicDuration()); jaxbMarkerResource.setEntryPoint(markerResource.getEntryPoint()); jaxbMarkerResource.setSourceDuration(markerResource.getSourceDuration()); jaxbMarkerResource.setRepeatCount(markerResource.getRepeatCount()); for(IMFMarkerType marker : markerResource.getMarkerList()) { // Wrap each Marker into the JAXB class org.smpte_ra.schemas._2067_3._2016.MarkerType jaxbMarker = new org.smpte_ra.schemas._2067_3._2016.MarkerType(); jaxbMarker.setOffset(marker.getOffset()); if (marker.getAnnotation() != null) { jaxbMarker.setAnnotation(buildCPLUserTextType_2016(marker.getAnnotation(), null)); } org.smpte_ra.schemas._2067_3._2016.MarkerType.Label jaxbLabel = new org.smpte_ra.schemas._2067_3._2016.MarkerType.Label(); jaxbLabel.setValue(marker.getLabel().getValue()); if (marker.getLabel().getScope() != null) { jaxbLabel.setScope(marker.getLabel().getScope()); } jaxbMarker.setLabel(jaxbLabel); // Add each marker to the list in marker resource jaxbMarkerResource.getMarker().add(jaxbMarker); } return jaxbMarkerResource; } /** * A method to construct a Default Digest Method Type with a default HashAlgorithm * @return a DigestMethodType object conforming to the 2016 schema with the default HashAlgorithm */ public org.w3._2000._09.xmldsig_.DigestMethodType buildDefaultDigestMethodType(){ org.w3._2000._09.xmldsig_.DigestMethodType digestMethodType = new org.w3._2000._09.xmldsig_.DigestMethodType(); digestMethodType.setAlgorithm(CompositionPlaylistBuilder_2016.defaultHashAlgorithm); return digestMethodType; } /** * A method to construct a Digest Method Type with the HashAlgorithm string that was passed in * @param algorithm a String representing the alogrithm used for generating the Hash * @return a DigestMethodType object conforming to the 2016 schema with the default HashAlgorithm */ public org.w3._2000._09.xmldsig_.DigestMethodType buildDigestMethodType(String algorithm){ org.w3._2000._09.xmldsig_.DigestMethodType digestMethodType = new org.w3._2000._09.xmldsig_.DigestMethodType(); digestMethodType.setAlgorithm(algorithm); return digestMethodType; } /** * Getter for the errors in CompositionPlaylistBuilder_2016 * * @return List of errors in CompositionPlaylistBuilder_2016. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } /** * A thin class that maintains a reference to a VirtualTrack Sequence object and the type of the Sequence. * Its state is opaque to classes outside this builder */ public static class SequenceTypeTuple{ private final org.smpte_ra.schemas._2067_3._2016.SequenceType sequence; private final Composition.SequenceTypeEnum sequenceType; private SequenceTypeTuple(org.smpte_ra.schemas._2067_3._2016.SequenceType sequence, Composition.SequenceTypeEnum sequenceType){ this.sequence = sequence; this.sequenceType = sequenceType; } private org.smpte_ra.schemas._2067_3._2016.SequenceType getSequence(){ return this.sequence; } private Composition.SequenceTypeEnum getSequenceType(){ return this.sequenceType; } } /** * Getter for the CPL file name for the Composition * * @return CPL file name for the Composition. */ public String getCPLFileName() { return this.cplFileName; } }
5,076
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/IMFPKLObjectFieldsFactory.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.writerTools.utils.IMFDocumentsObjectFieldsFactory; public final class IMFPKLObjectFieldsFactory { /*Prevent instantiation*/ private IMFPKLObjectFieldsFactory(){ } /** * A factory method that constructs a 2013 Schema compliant PackingListType object and recursively constructs all of its constituent fields. * Note: Fields that are either Java primitives, wrapperTypes or a subclass of Collection * are not constructed by this method for the reason that the field's accessor methods would do so. * * @return A 2007 schema compliant PackingListType object */ public static org.smpte_ra.schemas._429_8._2007.pkl.PackingListType constructPackingListType_2007(){ org.smpte_ra.schemas._429_8._2007.pkl.PackingListType pklType_2007 = new org.smpte_ra.schemas._429_8._2007.pkl.PackingListType(); IMFDocumentsObjectFieldsFactory.constructObjectFields(pklType_2007); return pklType_2007; } /** * A factory method that constructs a 2016 Schema compliant PackingListType object and recursively constructs all of its constituent fields. * Note: Fields that are either Java primitives, wrapperTypes or a subclass of Collection * are not constructed by this method for the reason that the field's accessor methods would do so. * * @return A 2016 schema compliant PackingListType object */ public static org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType constructPackingListType_2016(){ org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType pklType_2016 = new org.smpte_ra.schemas._2067_2._2016.pkl.PackingListType(); IMFDocumentsObjectFieldsFactory.constructObjectFields(pklType_2016); return pklType_2016; } }
5,077
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/CompositionPlaylistBuilder_2013.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFAuthoringException; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.st2067_2.CoreConstraints; import com.netflix.imflibrary.st2067_2.IMFEssenceComponentVirtualTrack; import com.netflix.imflibrary.st2067_2.IMFEssenceDescriptorBaseType; import com.netflix.imflibrary.st2067_2.IMFMarkerResourceType; import com.netflix.imflibrary.st2067_2.IMFMarkerType; import com.netflix.imflibrary.st2067_2.IMFMarkerVirtualTrack; import com.netflix.imflibrary.st2067_2.IMFTrackFileResourceType; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.writerTools.utils.IMFUUIDGenerator; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType; import org.smpte_ra.schemas._2067_3._2013.CompositionTimecodeType; import org.smpte_ra.schemas._2067_3._2013.ContentVersionType; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; /** * A class that implements the logic to build a SMPTE st2067-2:2013 schema compliant CompositionPlaylist document. */ public class CompositionPlaylistBuilder_2013 { private final UUID uuid; private final org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText; private final org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType issuer; private final org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType creator; private final XMLGregorianCalendar issueDate; private final List<? extends Composition.VirtualTrack> virtualTracks; private final List<Long> compositionEditRate; private final Long totalRunningTime; private final Map<UUID, IMPBuilder.IMFTrackFileInfo> trackFileInfoMap; private final File workingDirectory; private final IMFErrorLogger imfErrorLogger; private final Map<Node, String> essenceDescriptorIDMap = new HashMap<>(); private final List<org.smpte_ra.schemas._2067_3._2013.SegmentType> segments = new ArrayList<>(); private final List<List<org.smpte_ra.schemas._2067_3._2013.SequenceType>> sequenceList = new ArrayList<>(); private final List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList; public final static String defaultHashAlgorithm = "http://www.w3.org/2000/09/xmldsig#sha1"; private final static String defaultContentKindScope = "http://www.smpte-ra.org/schemas/2067-3/XXXX#content-kind"; private final String cplFileName; private final String coreConstraintsSchema; private final Set<String> applicationIds; private final Map<UUID, UUID> trackResourceSourceEncodingMap; /** * A constructor for CompositionPlaylistBuilder class to build a CompositionPlaylist document compliant with st2067-2:2013 schema * @param uuid identifying the CompositionPlaylist document * @param annotationText a free form human readable text * @param issuer a free form human readable text describing the issuer of the CompositionPlaylist document * @param creator a free form human readable text describing the tool used to create the CompositionPlaylist document * @param virtualTracks a list of VirtualTracks of the Composition * @param compositionEditRate the edit rate of the Composition * @param applicationIds ApplicationIds for the composition * @param totalRunningTime a long value representing in seconds the total running time of this composition * @param trackFileInfoMap a map of the IMFTrackFile's UUID to the track file info * @param workingDirectory a folder location where the constructed CPL document can be written to * @param imfEssenceDescriptorBaseTypeList List of IMFEssenceDescriptorBaseType * @param coreConstraintsSchema schema defining core constraints version */ public CompositionPlaylistBuilder_2013(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType issuer, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType creator, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull Set<String> applicationIds, long totalRunningTime, @Nonnull Map<UUID, IMPBuilder.IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList, @Nonnull String coreConstraintsSchema, Map<UUID, UUID> trackFileIdToEssenceDescriptorIdMap){ this.uuid = uuid; this.annotationText = annotationText; this.issuer = issuer; this.creator = creator; this.issueDate = IMFUtils.createXMLGregorianCalendar(); this.virtualTracks = Collections.unmodifiableList(virtualTracks); this.compositionEditRate = Collections.unmodifiableList(Arrays.asList(compositionEditRate.getNumerator(), compositionEditRate.getDenominator())); this.totalRunningTime = totalRunningTime; this.trackFileInfoMap = Collections.unmodifiableMap(trackFileInfoMap); this.workingDirectory = workingDirectory; this.imfErrorLogger = new IMFErrorLoggerImpl(); this.cplFileName = "CPL-" + this.uuid.toString() + ".xml"; this.applicationIds = Collections.unmodifiableSet(applicationIds); this.imfEssenceDescriptorBaseTypeList = Collections.unmodifiableList(imfEssenceDescriptorBaseTypeList); this.coreConstraintsSchema = coreConstraintsSchema; Map<UUID, UUID> trackEncodingMap = new HashMap<>(); //Map of TrackFileId -> SourceEncodingElement of each resource of this VirtualTrack for(Composition.VirtualTrack virtualTrack : virtualTracks) { if (!(virtualTrack instanceof IMFEssenceComponentVirtualTrack)) { continue; // Skip non-essence tracks } IMFEssenceComponentVirtualTrack essenceTrack = (IMFEssenceComponentVirtualTrack) virtualTrack; for (IMFTrackFileResourceType trackResource : essenceTrack.getTrackFileResourceList()) { UUID sourceEncoding = trackEncodingMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId())); if (sourceEncoding == null) { if (trackFileIdToEssenceDescriptorIdMap != null) { trackEncodingMap.put(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId()), trackFileIdToEssenceDescriptorIdMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId())) /*UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getSourceEncoding())*/); } else { trackEncodingMap.put(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId()), UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getSourceEncoding())); } // trackEncodingMap.put(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId()), trackFileIdToEssenceDescriptorIdMap.get(trackResource.getTrackFileId()) /*UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getSourceEncoding())*/); } } } this.trackResourceSourceEncodingMap = Collections.unmodifiableMap(trackEncodingMap); } /** * A constructor for CompositionPlaylistBuilder class to build a CompositionPlaylist document compliant with st2067-2:2013 schema * @param uuid identifying the CompositionPlaylist document * @param annotationText a free form human readable text * @param issuer a free form human readable text describing the issuer of the CompositionPlaylist document * @param creator a free form human readable text describing the tool used to create the CompositionPlaylist document * @param virtualTracks a list of VirtualTracks of the Composition * @param compositionEditRate the edit rate of the Composition * @param applicationId ApplicationId for the composition * @param totalRunningTime a long value representing in seconds the total running time of this composition * @param trackFileInfoMap a map of the IMFTrackFile's UUID to the track file info * @param workingDirectory a folder location where the constructed CPL document can be written to * @param imfEssenceDescriptorBaseTypeList List of IMFEssenceDescriptorBaseType */ @Deprecated public CompositionPlaylistBuilder_2013(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType issuer, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType creator, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, long totalRunningTime, @Nonnull Map<UUID, IMPBuilder.IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList){ this(uuid, annotationText, issuer, creator, virtualTracks, compositionEditRate, Collections.singleton(applicationId), totalRunningTime, trackFileInfoMap, workingDirectory, imfEssenceDescriptorBaseTypeList, CoreConstraints.NAMESPACE_IMF_2013, null); } /** * A constructor for CompositionPlaylistBuilder class to build a CompositionPlaylist document compliant with st2067-2:2013 schema * @param uuid identifying the CompositionPlaylist document * @param annotationText a free form human readable text * @param issuer a free form human readable text describing the issuer of the CompositionPlaylist document * @param creator a free form human readable text describing the tool used to create the CompositionPlaylist document * @param virtualTracks a list of VirtualTracks of the Composition * @param compositionEditRate the edit rate of the Composition * @param applicationId ApplicationId for the composition * @param totalRunningTime a long value representing in seconds the total running time of this composition * @param trackFileInfoMap a map of the IMFTrackFile's UUID to the track file info * @param workingDirectory a folder location where the constructed CPL document can be written to */ @Deprecated public CompositionPlaylistBuilder_2013(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType issuer, @Nonnull org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType creator, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, long totalRunningTime, @Nonnull Map<UUID, IMPBuilder.IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory){ this(uuid, annotationText, issuer, creator, virtualTracks, compositionEditRate, applicationId, totalRunningTime, trackFileInfoMap, workingDirectory, new ArrayList<>()); } /** * A method to build a CompositionPlaylist document conforming to the st2067-2/3:2013 schema * @return a list of errors resulting during the creation of the CPL document * @throws IOException - any I/O related error is exposed through an IOException * @throws ParserConfigurationException if a DocumentBuilder * cannot be created which satisfies the configuration requested */ public List<ErrorLogger.ErrorObject> build() throws IOException, ParserConfigurationException { org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType cplRoot = IMFCPLObjectFieldsFactory.constructCompositionPlaylistType_2013(); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); cplRoot.setId(UUIDHelper.fromUUID(this.uuid)); cplRoot.setAnnotation(this.annotationText); cplRoot.setIssueDate(IMFUtils.createXMLGregorianCalendar()); cplRoot.setIssuer(this.issuer); cplRoot.setCreator(this.creator); cplRoot.setContentOriginator(null); cplRoot.setContentTitle(buildCPLUserTextType_2013("Not Included", "en")); cplRoot.setContentKind(null); org.smpte_ra.schemas._2067_3._2013.ContentVersionType contentVersionType = buildContentVersionType(IMFUUIDGenerator.getInstance().getUrnUUID(), buildCPLUserTextType_2013("Photon CompositionPlaylistBuilder", "en")); List<org.smpte_ra.schemas._2067_3._2013.ContentVersionType> contentVersionTypeList = new ArrayList<>(); contentVersionTypeList.add(contentVersionType); cplRoot.setContentVersionList(buildContentVersionList(contentVersionTypeList)); cplRoot.setLocaleList(null); cplRoot.setCompositionTimecode(null); cplRoot.setExtensionProperties(null); cplRoot.getEditRate().addAll(this.compositionEditRate); cplRoot.setTotalRunningTime(String.format("%02d:%02d:%02d", totalRunningTime / 3600, (totalRunningTime % 3600) / 60, (totalRunningTime % 60))); /** * Process each VirtualTrack that is a part of this Composition */ List<CompositionPlaylistBuilder_2013.SequenceTypeTuple> sequenceTypeTuples = new ArrayList<>(); for(Composition.VirtualTrack virtualTrack : virtualTracks) { /** * Build TrackResourceList */ List<org.smpte_ra.schemas._2067_3._2013.BaseResourceType> trackResourceList = buildTrackResourceList(virtualTrack); /** * Build the Sequence */ UUID sequenceId = IMFUUIDGenerator.getInstance().generateUUID(); UUID trackId = IMFUUIDGenerator.getInstance().generateUUID(); SequenceTypeTuple sequenceTypeTuple = buildSequenceTypeTuple(sequenceId, trackId, buildResourceList(trackResourceList), virtualTrack.getSequenceTypeEnum()); sequenceTypeTuples.add(sequenceTypeTuple); } org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.EssenceDescriptorList essenceDescriptorListType = buildEssenceDescriptorList(this.imfEssenceDescriptorBaseTypeList); cplRoot.setEssenceDescriptorList(essenceDescriptorListType); UUID segmentId = IMFUUIDGenerator.getInstance().generateUUID(); org.smpte_ra.schemas._2067_3._2013.SegmentType segmentType = buildSegment(segmentId, buildCPLUserTextType_2013("Segment-1", "en")); populateSequenceListForSegment(sequenceTypeTuples, segmentType); cplRoot.setSegmentList(buildSegmentList(new ArrayList<org.smpte_ra.schemas._2067_3._2013.SegmentType>(){{add(segmentType);}})); cplRoot.setSigner(null); cplRoot.setSignature(null); if (!this.applicationIds.isEmpty()) { JAXBElement<List<String>> appIdElement = new org.smpte_ra.schemas._2067_2._2013.ObjectFactory() .createApplicationIdentification(new ArrayList<>(this.applicationIds)); org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.ExtensionProperties extensionProperties = new org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.ExtensionProperties(); extensionProperties.getAny().add(appIdElement); cplRoot.setExtensionProperties( extensionProperties); } File outputFile = new File(this.workingDirectory + File.separator + this.cplFileName); List errors = serializeCPLToXML(cplRoot, outputFile); imfErrorLogger.addAllErrors(errors); return imfErrorLogger.getErrors(); } private List<org.smpte_ra.schemas._2067_3._2013.BaseResourceType> buildTrackResourceList(Composition.VirtualTrack virtualTrack){ List<org.smpte_ra.schemas._2067_3._2013.BaseResourceType> trackResourceList = new ArrayList<>(); // Wrap essence track file resources into the JAXB class if (virtualTrack instanceof IMFEssenceComponentVirtualTrack) { IMFEssenceComponentVirtualTrack essenceTrack = (IMFEssenceComponentVirtualTrack) virtualTrack; for (IMFTrackFileResourceType trackFileResource : essenceTrack.getTrackFileResourceList()) { trackResourceList.add(buildTrackFileResource(trackFileResource)); } } // Wrap marker track resources into the JAXB class else if (virtualTrack instanceof IMFMarkerVirtualTrack) { IMFMarkerVirtualTrack markerTrack = (IMFMarkerVirtualTrack) virtualTrack; for (IMFMarkerResourceType markerResource : markerTrack.getMarkerResourceList()) { trackResourceList.add(buildMarkerResource(markerResource)); } } return Collections.unmodifiableList(trackResourceList); } private List<ErrorLogger.ErrorObject> serializeCPLToXML(org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType cplRoot, File outputFile) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); boolean formatted = true; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); InputStream cplSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_3_2013/imf-cpl.xsd"); InputStream dcmlSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd"); try(InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream ("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"); InputStream coreConstraintsSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2013/imf-core-constraints-20130620-pal.xsd"); OutputStream outputStream = new FileOutputStream(outputFile);) { try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource[] schemaSources = new StreamSource[4]; schemaSources[0] = new StreamSource(dsigSchemaAsAStream); schemaSources[1] = new StreamSource(dcmlSchemaAsAStream); schemaSources[2] = new StreamSource(cplSchemaAsAStream); schemaSources[3] = new StreamSource(coreConstraintsSchemaAsAStream); Schema schema = schemaFactory.newSchema(schemaSources); JAXBContext jaxbContext = JAXBContext.newInstance(org.smpte_ra.schemas._2067_3._2013.ObjectFactory.class, // 2013 CPL org.smpte_ra.schemas._2067_2._2013.ObjectFactory.class); // 2013 Core Constraints Marshaller marshaller = jaxbContext.createMarshaller(); ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true); marshaller.setEventHandler(validationEventHandler); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted); /*marshaller.marshal(cplType, output); workaround for 'Error: unable to marshal type "CompositionPlaylistType" as an element because it is missing an @XmlRootElement annotation' as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always */ marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/2067-3/2013", "CompositionPlaylist"), CompositionPlaylistType.class, cplRoot), outputStream); if (validationEventHandler.hasErrors()) { //TODO : Perhaps a candidate for a Lambda for (ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, validationErrorObject .getValidationEventSeverity(), validationErrorObject.getErrorMessage()); } } } catch( SAXException | JAXBException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, e.getMessage()); } } return imfErrorLogger.getErrors(); } /** * A method to construct a UserTextType compliant with the 2013 schema for IMF CompositionPlaylist documents * @param value the string that is a part of the annotation text * @param language the language code of the annotation text * @return a UserTextType conforming to the 2013 schema */ public static org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType buildCPLUserTextType_2013(String value, String language){ org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType userTextType = new org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType(); userTextType.setValue(value); userTextType.setLanguage(language); return userTextType; } /** * A method to construct a ContentKindType object conforming to the 2013 schema * @param value the string correspding to the Content Kind * @param scope a string corresponding to the scope attribute of a Content Kind * @return a ContentKind object conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.ContentKindType buildContentKindType(@Nonnull String value, String scope) { org.smpte_ra.schemas._2067_3._2013.ContentKindType contentKindType = new org.smpte_ra.schemas._2067_3._2013.ContentKindType(); if(!scope.matches("^[a-zA-Z0-9._-]+") == true) { this.imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The ContentKind scope %s does not follow the syntax of a valid URI (a-z, A-Z, 0-9, ., _, -)", scope))); contentKindType.setScope(scope); } else{ contentKindType.setScope(scope); } contentKindType.setValue(value); return contentKindType; } /** * A method to construct a ContentVersionType object conforming to the 2013 schema * @param id urn uuid corresponding to the content version type * @param value a UserTextType representing the value attribute of the ContentVersion * @return a content version object conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.ContentVersionType buildContentVersionType(String id, org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType value) { ContentVersionType contentVersionType = new ContentVersionType(); contentVersionType.setId(id); contentVersionType.setLabelText(value); return contentVersionType; } /** * A method to construct a ContentVersionList object conforming to the 2013 schema * @param contentVersions a list of ContentVersion objects conforming to the 2013 schema * @return a content version list object conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.ContentVersionList buildContentVersionList(List<org.smpte_ra.schemas._2067_3._2013.ContentVersionType> contentVersions){ org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.ContentVersionList contentVersionList = new CompositionPlaylistType.ContentVersionList(); contentVersionList.getContentVersion().addAll(contentVersions); return contentVersionList; } /** * A method to construct an EssenceDescriptorBaseType object conforming to the 2013 schema * @param id a UUID identifying the EssenceDescriptor. Note : This value should be the same as the SourceEncoding Element of * the resource in a VirtualTrack of this composition whose EssenceDescriptor it represents in the EssenceDescriptorList. This cannot be enforced * hence the responsibility is with the caller to ensure this else the generated CPL fail validation checks. * @param node a regxml representation of an EssenceDescriptor * @return a EssenceDescriptorBaseType object conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType buildEssenceDescriptorBaseType(UUID id, Node node){ org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType essenceDescriptorBaseType = new org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType(); essenceDescriptorBaseType.setId(UUIDHelper.fromUUID(id)); this.essenceDescriptorIDMap.put(node, UUIDHelper.fromUUID(id)); essenceDescriptorBaseType.getAny().add(node); return essenceDescriptorBaseType; } /** * A method to construct an EssenceDescriptorList conforming to the 2013 schema * @param imfEssenceDescriptorBaseTypeList a list of IMFEssenceDescriptorBaseType objects * @return EssenceDescriptorList type object */ public org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.EssenceDescriptorList buildEssenceDescriptorList(List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList){ org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.EssenceDescriptorList essenceDescriptorList = new org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.EssenceDescriptorList(); essenceDescriptorList.getEssenceDescriptor().addAll(imfEssenceDescriptorBaseTypeList.stream().map(e -> { org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType essenceDescriptorBaseType = new org.smpte_ra.schemas._2067_3._2013.EssenceDescriptorBaseType(); essenceDescriptorBaseType.setId(UUIDHelper.fromUUID(e.getId())); essenceDescriptorBaseType.getAny().addAll(e.getAny()); return essenceDescriptorBaseType; }).collect(Collectors.toList())); return essenceDescriptorList; } /** * A method to construct a CompositionTimecodeType conforming to the 2013 schema * @param compositionEditRate the EditRate corresponding to the Composition's EditRate * @return a CompositionTimecodeType conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.CompositionTimecodeType buildCompositionTimeCode(BigInteger compositionEditRate){ org.smpte_ra.schemas._2067_3._2013.CompositionTimecodeType compositionTimecodeType = new CompositionTimecodeType(); compositionTimecodeType.setTimecodeDropFrame(false);/*TimecodeDropFrame set to false by default*/ compositionTimecodeType.setTimecodeRate(compositionEditRate); compositionTimecodeType.setTimecodeStartAddress(IMFUtils.generateTimecodeStartAddress()); return compositionTimecodeType; } /** * A method to construct a LocaleType conforming to the 2013 schema * @param annotationText for the localeType * @param languages a list of string representing Language Tags as specified in RFC-5646 * @param regions a list of strings representing regions * @param contentMaturityRatings a list of ContentMaturityRating objects conforming to the 2013 schema * @return a LocaleType object conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.LocaleType buildLocaleType(org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText, List<String> languages, List<String> regions, List<org.smpte_ra.schemas._2067_3._2013.ContentMaturityRatingType> contentMaturityRatings){ org.smpte_ra.schemas._2067_3._2013.LocaleType localeType = new org.smpte_ra.schemas._2067_3._2013.LocaleType(); localeType.setAnnotation(annotationText); org.smpte_ra.schemas._2067_3._2013.LocaleType.LanguageList languageList = new org.smpte_ra.schemas._2067_3._2013.LocaleType.LanguageList(); languageList.getLanguage().addAll(languages); localeType.setLanguageList(languageList); org.smpte_ra.schemas._2067_3._2013.LocaleType.RegionList regionList = new org.smpte_ra.schemas._2067_3._2013.LocaleType.RegionList(); regionList.getRegion().addAll(regions); localeType.setRegionList(regionList); org.smpte_ra.schemas._2067_3._2013.LocaleType.ContentMaturityRatingList contentMaturityRatingList = new org.smpte_ra.schemas._2067_3._2013.LocaleType.ContentMaturityRatingList(); contentMaturityRatingList.getContentMaturityRating().addAll(contentMaturityRatings); return localeType; } /** * A method to construct a ContentMaturityRatingType conforming to the 2013 schema * @param agency a string representing the agency that issued the rating for this Composition * @param rating a human-readable representation of the rating of this Composition * @param audience a human-readable representation of the intended target audience of this Composition * @return a ContentMaturityRating object conforming to the 2013 schema * @throws URISyntaxException any syntax errors with the agency attribute is exposed through a URISyntaxException */ public org.smpte_ra.schemas._2067_3._2013.ContentMaturityRatingType buildContentMaturityRatingType(String agency, String rating, org.smpte_ra.schemas._2067_3._2013.ContentMaturityRatingType.Audience audience) throws URISyntaxException { org.smpte_ra.schemas._2067_3._2013.ContentMaturityRatingType contentMaturityRatingType = new org.smpte_ra.schemas._2067_3._2013.ContentMaturityRatingType(); if(!agency.matches("^[a-zA-Z0-9._-]+") == true) { //this.imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The ContentKind scope %s does not follow the syntax of a valid URI (a-z, A-Z, 0-9, ., _, -)", id))); throw new URISyntaxException("Invalid URI", "The ContentMaturityRating agency %s does not follow the syntax of a valid URI (a-z, A-Z, 0-9, ., _, -)"); } contentMaturityRatingType.setAgency(agency); contentMaturityRatingType.setRating(rating); contentMaturityRatingType.setAudience(audience); return contentMaturityRatingType; } /** * A method to construct a SegmentType conforming to the 2013 schema * @param id a uuid identifying the segment * @param annotationText a human readable annotation describing the Segment conforming to the 2013 schema * @return a SegmentType conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.SegmentType buildSegment(UUID id, org.smpte_ra.schemas._433._2008.dcmltypes.UserTextType annotationText){ org.smpte_ra.schemas._2067_3._2013.SegmentType segment = new org.smpte_ra.schemas._2067_3._2013.SegmentType(); segment.setId(UUIDHelper.fromUUID(uuid)); segment.setAnnotation(annotationText); org.smpte_ra.schemas._2067_3._2013.SegmentType.SequenceList sequenceList = new org.smpte_ra.schemas._2067_3._2013.SegmentType.SequenceList(); segment.setSequenceList(sequenceList); this.segments.add(segment); return segment; } /** * A method to construct a SegmentList conforming to the 2013 schema * @param segments a list of Segments conforming to the 2013 schema * @return a SegmentList conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.SegmentList buildSegmentList(List<org.smpte_ra.schemas._2067_3._2013.SegmentType> segments){ org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.SegmentList segmentList = new org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType.SegmentList(); segmentList.getSegment().addAll(segments); return segmentList; } /** * A method to construct a SequenceTypeTuple object that maintains a reference to the SequenceType object conforming to the 2013 schema * and the type of the sequence * @param id a uuid identifying the sequence * @param trackId a uuid identifying the virtual track to which this SequenceBelongs. Note : This Id should remain constant across Segments for * a Sequence that belongs to a VirtualTrack, please see the definition of a TrackId in st2067-3:2013 * @param resourceList a list of resources corresponding to this Sequence * @param sequenceType an enumeration identifying the contents of this Sequence (Currently we only support serializing * MainImageSequence and MainAudioSequence to a CPL) * @return a SequenceTypeTuple that maintains a reference to a Sequence and its type */ public SequenceTypeTuple buildSequenceTypeTuple(UUID id, UUID trackId, org.smpte_ra.schemas._2067_3._2013.SequenceType.ResourceList resourceList, Composition.SequenceTypeEnum sequenceType){ org.smpte_ra.schemas._2067_3._2013.SequenceType sequence = new org.smpte_ra.schemas._2067_3._2013.SequenceType(); sequence.setId(UUIDHelper.fromUUID(id)); sequence.setTrackId(UUIDHelper.fromUUID(trackId)); sequence.setResourceList(resourceList); return new SequenceTypeTuple(sequence, sequenceType); } /** * A method to construct a ResourceList for a Sequence conforming to the 2013 schema * @param trackResourceList a list of BaseResourceTypes * @return a resource list conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.SequenceType.ResourceList buildResourceList(List<org.smpte_ra.schemas._2067_3._2013.BaseResourceType> trackResourceList){ org.smpte_ra.schemas._2067_3._2013.SequenceType.ResourceList resourceList = new org.smpte_ra.schemas._2067_3._2013.SequenceType.ResourceList(); resourceList.getResource().addAll(trackResourceList); return resourceList; } /** * A method to populate the SequenceList of a VirtualTrack segment * @param sequenceTypeTuples a SequenceTypeTuple that maintains a reference to a Sequence and its type. This type is * deliberately an opaque object whose definition is not known outside this builder. This * is done in order to allow robust construction of a SequenceList serially. * @param segment a VirtualTrack Segment conforming to the 2013 schema */ public void populateSequenceListForSegment(List<SequenceTypeTuple> sequenceTypeTuples, org.smpte_ra.schemas._2067_3._2013.SegmentType segment) { org.smpte_ra.schemas._2067_2._2013.ObjectFactory objectFactory = new org.smpte_ra.schemas._2067_2._2013.ObjectFactory(); List<Object> any = segment.getSequenceList().getAny(); for(SequenceTypeTuple sequenceTypeTuple : sequenceTypeTuples){ switch(sequenceTypeTuple.getSequenceType()){ case MainImageSequence: any.add(objectFactory.createMainImageSequence(sequenceTypeTuple.getSequence())); break; case MainAudioSequence: any.add(objectFactory.createMainAudioSequence(sequenceTypeTuple.getSequence())); break; case MarkerSequence: segment.getSequenceList().setMarkerSequence(sequenceTypeTuple.getSequence()); break; default: throw new IMFAuthoringException(String.format("Currently we only support %s, %s, and %s sequence types in building a Composition Playlist document, the type of sequence being requested is %s", Composition.SequenceTypeEnum.MainAudioSequence, Composition.SequenceTypeEnum.MainImageSequence, Composition.SequenceTypeEnum.MarkerSequence, sequenceTypeTuple.getSequenceType())); } } } /** * A method to construct a TrackFileResourceType conforming to the 2013 schema * @param trackResource an object that roughly models a TrackFileResourceType * @return a BaseResourceType conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.BaseResourceType buildTrackFileResource(IMFTrackFileResourceType trackResource){ org.smpte_ra.schemas._2067_3._2013.TrackFileResourceType trackFileResource = new org.smpte_ra.schemas._2067_3._2013.TrackFileResourceType(); trackFileResource.setId(trackResource.getId()); trackFileResource.setAnnotation(null); trackFileResource.setTrackFileId(trackResource.getTrackFileId()); trackFileResource.getEditRate().add(trackResource.getEditRate().getNumerator()); trackFileResource.getEditRate().add(trackResource.getEditRate().getDenominator()); trackFileResource.setIntrinsicDuration(trackResource.getIntrinsicDuration()); trackFileResource.setEntryPoint(trackResource.getEntryPoint()); trackFileResource.setSourceDuration(trackResource.getSourceDuration()); trackFileResource.setRepeatCount(trackResource.getRepeatCount()); trackFileResource.setSourceEncoding(UUIDHelper.fromUUID(this.trackResourceSourceEncodingMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(trackResource.getTrackFileId())))); trackFileResource.setHash(trackResource.getHash()); return trackFileResource; } /** * A method to construct a MarkerResourceType conforming to the 2013 schema * @param markerResource an object that roughly models a MarkerResourceType * @return a MarkerResourceType conforming to the 2013 schema */ public org.smpte_ra.schemas._2067_3._2013.MarkerResourceType buildMarkerResource(IMFMarkerResourceType markerResource){ org.smpte_ra.schemas._2067_3._2013.MarkerResourceType jaxbMarkerResource = new org.smpte_ra.schemas._2067_3._2013.MarkerResourceType(); jaxbMarkerResource.setId(markerResource.getId()); jaxbMarkerResource.setAnnotation(null); jaxbMarkerResource.getEditRate().add(markerResource.getEditRate().getNumerator()); jaxbMarkerResource.getEditRate().add(markerResource.getEditRate().getDenominator()); jaxbMarkerResource.setIntrinsicDuration(markerResource.getIntrinsicDuration()); jaxbMarkerResource.setEntryPoint(markerResource.getEntryPoint()); jaxbMarkerResource.setSourceDuration(markerResource.getSourceDuration()); jaxbMarkerResource.setRepeatCount(markerResource.getRepeatCount()); for(IMFMarkerType marker : markerResource.getMarkerList()) { // Wrap each Marker into the JAXB class org.smpte_ra.schemas._2067_3._2013.MarkerType jaxbMarker = new org.smpte_ra.schemas._2067_3._2013.MarkerType(); jaxbMarker.setOffset(marker.getOffset()); if (marker.getAnnotation() != null) { jaxbMarker.setAnnotation(buildCPLUserTextType_2013(marker.getAnnotation(), null)); } org.smpte_ra.schemas._2067_3._2013.MarkerType.Label jaxbLabel = new org.smpte_ra.schemas._2067_3._2013.MarkerType.Label(); jaxbLabel.setValue(marker.getLabel().getValue()); if (marker.getLabel().getScope() != null) { jaxbLabel.setScope(marker.getLabel().getScope()); } jaxbMarker.setLabel(jaxbLabel); // Add each marker to the list in marker resource jaxbMarkerResource.getMarker().add(jaxbMarker); } return jaxbMarkerResource; } /** * A method to construct a Default Digest Method Type with a default HashAlgorithm * @return a DigestMethodType object conforming to the 2013 schema with the default HashAlgorithm */ public org.w3._2000._09.xmldsig_.DigestMethodType buildDefaultDigestMethodType(){ org.w3._2000._09.xmldsig_.DigestMethodType digestMethodType = new org.w3._2000._09.xmldsig_.DigestMethodType(); digestMethodType.setAlgorithm(CompositionPlaylistBuilder_2013.defaultHashAlgorithm); return digestMethodType; } /** * A method to construct a Digest Method Type with the HashAlgorithm string that was passed in * @param algorithm a String representing the alogrithm used for generating the Hash * @return a DigestMethodType object conforming to the 2016 schema with the default HashAlgorithm */ public org.w3._2000._09.xmldsig_.DigestMethodType buildDigestMethodType(String algorithm){ org.w3._2000._09.xmldsig_.DigestMethodType digestMethodType = new org.w3._2000._09.xmldsig_.DigestMethodType(); digestMethodType.setAlgorithm(algorithm); return digestMethodType; } /** * Getter for the errors in CompositionPlaylistBuilder_2013 * * @return List of errors in CompositionPlaylistBuilder_2013. */ public List<ErrorLogger.ErrorObject> getErrors() { return imfErrorLogger.getErrors(); } /** * A thin class that maintains a reference to a VirtualTrack Sequence object and the type of the Sequence. * Its state is opaque to classes outside this builder */ public static class SequenceTypeTuple{ private final org.smpte_ra.schemas._2067_3._2013.SequenceType sequence; private final Composition.SequenceTypeEnum sequenceType; private SequenceTypeTuple(org.smpte_ra.schemas._2067_3._2013.SequenceType sequence, Composition.SequenceTypeEnum sequenceType){ this.sequence = sequence; this.sequenceType = sequenceType; } private org.smpte_ra.schemas._2067_3._2013.SequenceType getSequence(){ return this.sequence; } private Composition.SequenceTypeEnum getSequenceType(){ return this.sequenceType; } } /** * Getter for the CPL file name for the Composition * * @return CPL file name for the Composition. */ public String getCPLFileName() { return this.cplFileName; } }
5,078
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/IMPBuilder.java
package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.exceptions.IMFAuthoringException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.st2067_2.*; import com.netflix.imflibrary.utils.ByteArrayByteRangeProvider; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.RegXMLLibHelper; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import com.netflix.imflibrary.writerTools.utils.IMFUUIDGenerator; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import com.sandflow.smpte.klv.Triplet; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.xml.bind.JAXBException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import static com.netflix.imflibrary.st2067_2.AbstractApplicationComposition.getResourceIdTuples; /** * A stateless class that will create the AssetMap, Packing List and CompositionPlaylist that represent a complete IMF Master Package by utilizing the relevant builders */ public class IMPBuilder { /** * To prevent instantiation */ private IMPBuilder(){ } /** * A method to generate the AssetMap, PackingList and CompositionPlaylist documents conforming to the * st0429-9:2007, st2067-2:2013 and st2067-2/3:2013 schemas respectively * @param annotationText a human readable text that will be used to annotate the corresponding elements of the XML documents * @param issuer a human readable text indicating the issuer of the XML documents * @param virtualTracks a list of all VirtualTracks that are a part of the Composition * @param compositionEditRate the EditRate of the composition * @param applicationId ApplicationId for the composition * @param trackFileHeaderPartitionMap a Map of IMFTrackFileId to the HeaderPartition metadata of the track file * @param workingDirectory a folder location for the generated documents * @return a list of errors that occurred while building an IMP * @throws IOException - any I/O related error will be exposed through an IOException * @throws ParserConfigurationException if a DocumentBuilder * cannot be created which satisfies the configuration requested by the underlying builder implementation * @throws SAXException - exposes any issues with instantiating a {@link javax.xml.validation.Schema Schema} object * @throws JAXBException - any issues in serializing the XML document using JAXB are exposed through a JAXBException * @throws URISyntaxException exposes any issues instantiating a {@link java.net.URI URI} object */ public static List<ErrorLogger.ErrorObject> buildIMP_2013(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileMetadata> trackFileHeaderPartitionMap, @Nonnull File workingDirectory) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException { if(trackFileHeaderPartitionMap.entrySet().stream().filter(e -> e.getValue().getHeaderPartition() == null).count() > 0) { throw new IMFAuthoringException(String.format("trackFileHeaderPartitionMap has IMFTrackFileMetadata with null header partition")); } IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Map<UUID, List<Node>> imfEssenceDescriptorMap = buildEDLForVirtualTracks(trackFileHeaderPartitionMap, virtualTracks, imfErrorLogger); Map<UUID, IMFTrackFileInfo> uuidimfTrackFileInfoMap = new HashMap<>(); for(Map.Entry<UUID, IMFTrackFileMetadata> entry: trackFileHeaderPartitionMap.entrySet()) { IMFTrackFileInfo imfTrackFileInfo = new IMFTrackFileInfo(entry.getValue().getHash(), entry.getValue().getHashAlgorithm(), entry.getValue().getOriginalFileName(), entry.getValue().getLength(), entry.getValue().isExcludeFromPackage()); uuidimfTrackFileInfoMap.put(entry.getKey(), imfTrackFileInfo); } imfErrorLogger.addAllErrors(buildIMP_2013(annotationText, issuer, virtualTracks, compositionEditRate, applicationId, uuidimfTrackFileInfoMap, workingDirectory, imfEssenceDescriptorMap)); return imfErrorLogger.getErrors(); } public static List<ErrorLogger.ErrorObject> buildIMPWithoutCreatingNewCPL_2013(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileMetadata> trackFileHeaderPartitionMap, @Nonnull File workingDirectory, @Nonnull File cplFile) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException { if (trackFileHeaderPartitionMap.entrySet().stream().filter(e -> e.getValue().getHeaderPartition() == null).count() > 0) { throw new IMFAuthoringException(String.format("trackFileHeaderPartitionMap has IMFTrackFileMetadata with null header partition")); } IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Map<UUID, IMFTrackFileInfo> uuidimfTrackFileInfoMap = new HashMap<>(); for (Map.Entry<UUID, IMFTrackFileMetadata> entry : trackFileHeaderPartitionMap.entrySet()) { IMFTrackFileInfo imfTrackFileInfo = new IMFTrackFileInfo(entry.getValue().getHash(), entry.getValue().getHashAlgorithm(), entry.getValue().getOriginalFileName(), entry.getValue().getLength(), entry.getValue().isExcludeFromPackage()); uuidimfTrackFileInfoMap.put(entry.getKey(), imfTrackFileInfo); } imfErrorLogger.addAllErrors(buildIMPWithoutCreatingNewCPL_2013(annotationText, issuer, virtualTracks, applicationId, uuidimfTrackFileInfoMap, workingDirectory, cplFile)); return imfErrorLogger.getErrors(); } public static List<ErrorLogger.ErrorObject> buildIMPWithoutCreatingNewCPL_2013(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull File cplFile) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); int numErrors = imfErrorLogger.getNumberOfErrors(); Set<String> applicationIds = Collections.singleton(applicationId); String coreConstraintsSchema = CoreConstraints.fromApplicationId(applicationIds); if (coreConstraintsSchema == null) coreConstraintsSchema = CoreConstraints.NAMESPACE_IMF_2013; Composition.VirtualTrack mainImageVirtualTrack = null; for(Composition.VirtualTrack virtualTrack : virtualTracks){ if(virtualTrack.getSequenceTypeEnum() == Composition.SequenceTypeEnum.MainImageSequence){ mainImageVirtualTrack = virtualTrack; break; } } if(mainImageVirtualTrack == null){ throw new IMFAuthoringException(String.format("Exactly 1 MainImageSequence virtual track is required to create an IMP, none present")); } /* No need to build a new CPL because we already have it in cplFile */ if(!cplFile.exists()){ throw new IMFAuthoringException(String.format("CompositionPlaylist file does not exist, cannot generate the rest of the documents")); } byte[] cplHash = IMFUtils.generateSHA1Hash(cplFile); /** * Build the PackingList */ UUID pklUUID = IMFUUIDGenerator.getInstance().generateUUID(); PackingListBuilder packingListBuilder = new PackingListBuilder(pklUUID, IMFUtils.createXMLGregorianCalendar(), workingDirectory, imfErrorLogger); org.smpte_ra.schemas._429_8._2007.pkl.UserText pklAnnotationText = PackingListBuilder.buildPKLUserTextType_2007(annotationText, "en"); org.smpte_ra.schemas._429_8._2007.pkl.UserText creator = PackingListBuilder.buildPKLUserTextType_2007("Photon PackingListBuilder", "en"); org.smpte_ra.schemas._429_8._2007.pkl.UserText pklIssuer = PackingListBuilder.buildPKLUserTextType_2007(issuer, "en"); List<PackingListBuilder.PackingListBuilderAsset_2007> packingListBuilderAssets = new ArrayList<>(); /** * Build the CPL asset to be entered into the PackingList */ UUID cplUUID = IMFUtils.extractUUIDFromCPLFile(cplFile, imfErrorLogger); PackingListBuilder.PackingListBuilderAsset_2007 cplAsset = new PackingListBuilder.PackingListBuilderAsset_2007(cplUUID, PackingListBuilder.buildPKLUserTextType_2007(annotationText, "en"), Arrays.copyOf(cplHash, cplHash.length), cplFile.length(), PackingListBuilder.PKLAssetTypeEnum.TEXT_XML, PackingListBuilder.buildPKLUserTextType_2007(cplFile.getName(), "en")); packingListBuilderAssets.add(cplAsset); Set<Map.Entry<UUID, IMFTrackFileInfo>> trackFileMetadataEntriesSet = trackFileInfoMap.entrySet().stream().filter( e -> !(e.getValue().isExcludeFromPackage())).collect(Collectors.toSet()); for(Map.Entry<UUID, IMFTrackFileInfo> entry : trackFileMetadataEntriesSet){ PackingListBuilder.PackingListBuilderAsset_2007 asset = new PackingListBuilder.PackingListBuilderAsset_2007(entry.getKey(), PackingListBuilder.buildPKLUserTextType_2007(annotationText, "en"), Arrays.copyOf(entry.getValue().getHash(), entry.getValue().getHash().length), entry.getValue().getLength(), PackingListBuilder.PKLAssetTypeEnum.APP_MXF, PackingListBuilder.buildPKLUserTextType_2007(entry.getValue().getOriginalFileName(), "en")); packingListBuilderAssets.add(asset); } imfErrorLogger.addAllErrors(packingListBuilder.buildPackingList_2007(pklAnnotationText, pklIssuer, creator, packingListBuilderAssets)); imfErrorLogger.addAllErrors(packingListBuilder.getErrors()); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the PackingList. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } numErrors = (imfErrorLogger.getNumberOfErrors() > 0) ? imfErrorLogger.getNumberOfErrors()-1 : 0; File pklFile = new File(workingDirectory + File.separator + packingListBuilder.getPKLFileName()); if(!pklFile.exists()){ throw new IMFAuthoringException(String.format("PackingList file does not exist in the working directory %s, cannot generate the rest of the documents", workingDirectory.getAbsolutePath ())); } /** * Build the AssetMap */ UUID assetMapUUID = IMFUUIDGenerator.getInstance().generateUUID(); List<AssetMapBuilder.Asset> assetMapAssets = new ArrayList<>(); for(PackingListBuilder.PackingListBuilderAsset_2007 pklAsset : packingListBuilderAssets){ AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklAsset.getOriginalFileName().getValue(), pklAsset.getSize().longValue()); List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(UUIDHelper.fromUUIDAsURNStringToUUID(pklAsset.getUUID()), AssetMapBuilder.buildAssetMapUserTextType_2007(pklAsset.getAnnotationText().getValue(), "en"), false, chunkList); assetMapAssets.add(amAsset); } //Add the PKL as an AssetMap asset List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklFile.getName(), pklFile.length()); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(pklUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(pklAnnotationText.getValue(), "en"), true, chunkList); assetMapAssets.add(amAsset); AssetMapBuilder assetMapBuilder = new AssetMapBuilder(assetMapUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(annotationText, "en"), AssetMapBuilder.buildAssetMapUserTextType_2007("Photon AssetMapBuilder", "en"), IMFUtils.createXMLGregorianCalendar(), AssetMapBuilder.buildAssetMapUserTextType_2007(issuer, "en"), assetMapAssets, workingDirectory, imfErrorLogger); assetMapBuilder.build(); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the AssetMap. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } File assetMapFile = new File(workingDirectory + File.separator + assetMapBuilder.getAssetMapFileName()); if(!assetMapFile.exists()){ throw new IMFAuthoringException(String.format("AssetMap file does not exist in the working directory %s", workingDirectory.getAbsolutePath ())); } return imfErrorLogger.getErrors(); } /** * A method to generate the AssetMap, PackingList and CompositionPlaylist documents conforming to the * st0429-9:2007, st0429-8:2007 and st2067-2/3:2013 schemas respectively * @param annotationText a human readable text that will be used to annotate the corresponding elements of the XML documents * @param issuer a human readable text indicating the issuer of the XML documents * @param virtualTracks a list of all VirtualTracks that are a part of the Composition * @param compositionEditRate the EditRate of the composition * @param applicationId ApplicationId for the composition * @param trackFileInfoMap a Map of IMFTrackFileId to IMFTrackFileInfo * @param workingDirectory a folder location for the generated documents * @param essenceDescriptorDomNodeMap Map containing mapping between Track file ID to essence descriptor DOM node list * @return a list of errors that occurred while building an IMP * @throws IOException - any I/O related error will be exposed through an IOException * @throws ParserConfigurationException if a DocumentBuilder * cannot be created which satisfies the configuration requested by the underlying builder implementation * @throws URISyntaxException exposes any issues instantiating a {@link java.net.URI URI} object */ public static List<ErrorLogger.ErrorObject> buildIMP_2013(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull Map<UUID, List<Node>> essenceDescriptorDomNodeMap) throws IOException, ParserConfigurationException, URISyntaxException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); int numErrors = imfErrorLogger.getNumberOfErrors(); UUID cplUUID = IMFUUIDGenerator.getInstance().generateUUID(); Set<String> applicationIds = Collections.singleton(applicationId); String coreConstraintsSchema = CoreConstraints.fromApplicationId(applicationIds); if (coreConstraintsSchema == null) coreConstraintsSchema = CoreConstraints.NAMESPACE_IMF_2013; Composition.VirtualTrack mainImageVirtualTrack = null; for(Composition.VirtualTrack virtualTrack : virtualTracks){ if(virtualTrack.getSequenceTypeEnum() == Composition.SequenceTypeEnum.MainImageSequence){ mainImageVirtualTrack = virtualTrack; break; } } if(mainImageVirtualTrack == null){ throw new IMFAuthoringException(String.format("Exactly 1 MainImageSequence virtual track is required to create an IMP, none present")); } /** * Logic to compute total running time */ long totalRunningTime = 0L; long totalNumberOfImageEditUnits = 0L; for(IMFTrackFileResourceType trackResource : (List<IMFTrackFileResourceType>)mainImageVirtualTrack.getResourceList()){ totalNumberOfImageEditUnits += trackResource.getSourceDuration().longValue() * trackResource.getRepeatCount().longValue(); } totalRunningTime = totalNumberOfImageEditUnits/(compositionEditRate.getNumerator()/compositionEditRate.getDenominator()); List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList = new ArrayList<>(); Map<UUID, UUID> trackFileIdToEssenceDescriptorIdMap = new HashMap<>(); for(AbstractApplicationComposition.ResourceIdTuple resourceIdTuple : getResourceIdTuples(virtualTracks)) { trackFileIdToEssenceDescriptorIdMap.put(resourceIdTuple.getTrackFileId(), resourceIdTuple.getSourceEncoding()); } for(Map.Entry<UUID, List<Node>> entry: essenceDescriptorDomNodeMap.entrySet()) { if(trackFileIdToEssenceDescriptorIdMap.containsKey(entry.getKey())) { imfEssenceDescriptorBaseTypeList.add(new IMFEssenceDescriptorBaseType(UUIDHelper.fromUUID(trackFileIdToEssenceDescriptorIdMap.get(entry.getKey())), new ArrayList<>( entry.getValue()))); } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Resource = %s is not referenced in the virtual track.", UUIDHelper.fromUUID(entry.getKey()))); } } CompositionPlaylistBuilder_2013 compositionPlaylistBuilder_2013 = new CompositionPlaylistBuilder_2013(cplUUID, CompositionPlaylistBuilder_2013.buildCPLUserTextType_2013(annotationText, "en"), CompositionPlaylistBuilder_2013.buildCPLUserTextType_2013(issuer, "en"), CompositionPlaylistBuilder_2013.buildCPLUserTextType_2013("Photon PackingListBuilder", "en"), virtualTracks, compositionEditRate, applicationIds, totalRunningTime, trackFileInfoMap, workingDirectory, imfEssenceDescriptorBaseTypeList, coreConstraintsSchema, trackFileIdToEssenceDescriptorIdMap); imfErrorLogger.addAllErrors(compositionPlaylistBuilder_2013.build()); if(imfErrorLogger.hasFatalErrors()) { throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the CompositionPlaylist. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } numErrors = (imfErrorLogger.getNumberOfErrors() > 0) ? imfErrorLogger.getNumberOfErrors()-1 : 0; File cplFile = new File(workingDirectory + File.separator + compositionPlaylistBuilder_2013.getCPLFileName()); if(!cplFile.exists()){ throw new IMFAuthoringException(String.format("CompositionPlaylist file does not exist in the working directory %s, cannot generate the rest of the documents", workingDirectory.getAbsolutePath())); } byte[] cplHash = IMFUtils.generateSHA1Hash(cplFile); /** * Build the PackingList */ UUID pklUUID = IMFUUIDGenerator.getInstance().generateUUID(); PackingListBuilder packingListBuilder = new PackingListBuilder(pklUUID, IMFUtils.createXMLGregorianCalendar(), workingDirectory, imfErrorLogger); org.smpte_ra.schemas._429_8._2007.pkl.UserText pklAnnotationText = PackingListBuilder.buildPKLUserTextType_2007(annotationText, "en"); org.smpte_ra.schemas._429_8._2007.pkl.UserText creator = PackingListBuilder.buildPKLUserTextType_2007("Photon PackingListBuilder", "en"); org.smpte_ra.schemas._429_8._2007.pkl.UserText pklIssuer = PackingListBuilder.buildPKLUserTextType_2007(issuer, "en"); List<PackingListBuilder.PackingListBuilderAsset_2007> packingListBuilderAssets = new ArrayList<>(); /** * Build the CPL asset to be entered into the PackingList */ PackingListBuilder.PackingListBuilderAsset_2007 cplAsset = new PackingListBuilder.PackingListBuilderAsset_2007(cplUUID, PackingListBuilder.buildPKLUserTextType_2007(annotationText, "en"), Arrays.copyOf(cplHash, cplHash.length), cplFile.length(), PackingListBuilder.PKLAssetTypeEnum.TEXT_XML, PackingListBuilder.buildPKLUserTextType_2007(compositionPlaylistBuilder_2013.getCPLFileName(), "en")); packingListBuilderAssets.add(cplAsset); Set<Map.Entry<UUID, IMFTrackFileInfo>> trackFileMetadataEntriesSet = trackFileInfoMap.entrySet().stream().filter( e -> !(e.getValue().isExcludeFromPackage())).collect(Collectors.toSet()); for(Map.Entry<UUID, IMFTrackFileInfo> entry : trackFileMetadataEntriesSet){ PackingListBuilder.PackingListBuilderAsset_2007 asset = new PackingListBuilder.PackingListBuilderAsset_2007(entry.getKey(), PackingListBuilder.buildPKLUserTextType_2007(annotationText, "en"), Arrays.copyOf(entry.getValue().getHash(), entry.getValue().getHash().length), entry.getValue().getLength(), PackingListBuilder.PKLAssetTypeEnum.APP_MXF, PackingListBuilder.buildPKLUserTextType_2007(entry.getValue().getOriginalFileName(), "en")); packingListBuilderAssets.add(asset); } imfErrorLogger.addAllErrors(packingListBuilder.buildPackingList_2007(pklAnnotationText, pklIssuer, creator, packingListBuilderAssets)); imfErrorLogger.addAllErrors(packingListBuilder.getErrors()); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the PackingList. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } numErrors = (imfErrorLogger.getNumberOfErrors() > 0) ? imfErrorLogger.getNumberOfErrors()-1 : 0; File pklFile = new File(workingDirectory + File.separator + packingListBuilder.getPKLFileName()); if(!pklFile.exists()){ throw new IMFAuthoringException(String.format("PackingList file does not exist in the working directory %s, cannot generate the rest of the documents", workingDirectory.getAbsolutePath ())); } /** * Build the AssetMap */ UUID assetMapUUID = IMFUUIDGenerator.getInstance().generateUUID(); List<AssetMapBuilder.Asset> assetMapAssets = new ArrayList<>(); for(PackingListBuilder.PackingListBuilderAsset_2007 pklAsset : packingListBuilderAssets){ AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklAsset.getOriginalFileName().getValue(), pklAsset.getSize().longValue()); List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(UUIDHelper.fromUUIDAsURNStringToUUID(pklAsset.getUUID()), AssetMapBuilder.buildAssetMapUserTextType_2007(pklAsset.getAnnotationText().getValue(), "en"), false, chunkList); assetMapAssets.add(amAsset); } //Add the PKL as an AssetMap asset List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklFile.getName(), pklFile.length()); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(pklUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(pklAnnotationText.getValue(), "en"), true, chunkList); assetMapAssets.add(amAsset); AssetMapBuilder assetMapBuilder = new AssetMapBuilder(assetMapUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(annotationText, "en"), AssetMapBuilder.buildAssetMapUserTextType_2007("Photon AssetMapBuilder", "en"), IMFUtils.createXMLGregorianCalendar(), AssetMapBuilder.buildAssetMapUserTextType_2007(issuer, "en"), assetMapAssets, workingDirectory, imfErrorLogger); assetMapBuilder.build(); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the AssetMap. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } File assetMapFile = new File(workingDirectory + File.separator + assetMapBuilder.getAssetMapFileName()); if(!assetMapFile.exists()){ throw new IMFAuthoringException(String.format("AssetMap file does not exist in the working directory %s", workingDirectory.getAbsolutePath ())); } return imfErrorLogger.getErrors(); } /** * A method to generate the AssetMap, PackingList and CompositionPlaylist documents conforming to the * st0429-9:2007, st2067-2:2016 and st2067-2/3:2016 schemas respectively * @param annotationText a human readable text that will be used to annotate the corresponding elements of the XML documents * @param issuer a human readable text indicating the issuer of the XML documents * @param virtualTracks a list of all VirtualTracks that are a part of the Composition * @param compositionEditRate the EditRate of the composition * @param applicationId ApplicationId for the composition * @param trackFileHeaderPartitionMap a Map of IMFTrackFileId to the HeaderPartition metadata of the track file * @param workingDirectory a folder location for the generated documents * @return a list of errors that occurred while building an IMP * @throws IOException - any I/O related error will be exposed through an IOException * @throws ParserConfigurationException if a DocumentBuilder * cannot be created which satisfies the configuration requested by the underlying builder implementation * @throws SAXException - exposes any issues with instantiating a {@link javax.xml.validation.Schema Schema} object * @throws JAXBException - any issues in serializing the XML document using JAXB are exposed through a JAXBException * @throws URISyntaxException exposes any issues instantiating a {@link java.net.URI URI} object */ public static List<ErrorLogger.ErrorObject> buildIMP_2016(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileMetadata> trackFileHeaderPartitionMap, @Nonnull File workingDirectory) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException { if(trackFileHeaderPartitionMap.entrySet().stream().filter(e -> e.getValue().getHeaderPartition() == null).count() > 0) { throw new IMFAuthoringException(String.format("trackFileHeaderPartitionMap has IMFTrackFileMetadata with null header partition")); } IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Map<UUID, List<Node>> imfEssenceDescriptorMap = buildEDLForVirtualTracks(trackFileHeaderPartitionMap, virtualTracks, imfErrorLogger); Map<UUID, IMFTrackFileInfo> uuidimfTrackFileInfoMap = new HashMap<>(); for(Map.Entry<UUID, IMFTrackFileMetadata> entry: trackFileHeaderPartitionMap.entrySet()) { IMFTrackFileInfo imfTrackFileInfo = new IMFTrackFileInfo(entry.getValue().getHash(), entry.getValue().getHashAlgorithm(), entry.getValue().getOriginalFileName(), entry.getValue().getLength(), entry.getValue().isExcludeFromPackage()); uuidimfTrackFileInfoMap.put(entry.getKey(), imfTrackFileInfo); } imfErrorLogger.addAllErrors(buildIMP_2016(annotationText, issuer, virtualTracks, compositionEditRate, applicationId, uuidimfTrackFileInfoMap, workingDirectory, imfEssenceDescriptorMap)); return imfErrorLogger.getErrors(); } public static List<ErrorLogger.ErrorObject> buildIMPWithoutCreatingNewCPL_2016(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileMetadata> trackFileHeaderPartitionMap, @Nonnull File workingDirectory, @Nonnull File cplFile) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException { if(trackFileHeaderPartitionMap.entrySet().stream().filter(e -> e.getValue().getHeaderPartition() == null).count() > 0) { throw new IMFAuthoringException(String.format("trackFileHeaderPartitionMap has IMFTrackFileMetadata with null header partition")); } IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Map<UUID, IMFTrackFileInfo> trackFileInfoMap = new HashMap<>(); for(Map.Entry<UUID, IMFTrackFileMetadata> entry: trackFileHeaderPartitionMap.entrySet()) { IMFTrackFileInfo imfTrackFileInfo = new IMFTrackFileInfo(entry.getValue().getHash(), entry.getValue().getHashAlgorithm(), entry.getValue().getOriginalFileName(), entry.getValue().getLength(), entry.getValue().isExcludeFromPackage()); trackFileInfoMap.put(entry.getKey(), imfTrackFileInfo); } imfErrorLogger.addAllErrors(buildIMPWithoutCreatingNewCPL_2016(annotationText, issuer, virtualTracks, applicationId, trackFileInfoMap, workingDirectory, cplFile)); return imfErrorLogger.getErrors(); } public static List<ErrorLogger.ErrorObject> buildIMPWithoutCreatingNewCPL_2016(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull File cplFile) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); int numErrors = imfErrorLogger.getNumberOfErrors(); Set<String> applicationIds = Collections.singleton(applicationId); String coreConstraintsSchema = CoreConstraints.fromApplicationId(applicationIds); if (coreConstraintsSchema == null) coreConstraintsSchema = CoreConstraints.NAMESPACE_IMF_2016; Composition.VirtualTrack mainImageVirtualTrack = null; for(Composition.VirtualTrack virtualTrack : virtualTracks){ if(virtualTrack.getSequenceTypeEnum() == Composition.SequenceTypeEnum.MainImageSequence){ mainImageVirtualTrack = virtualTrack; break; } } if(mainImageVirtualTrack == null){ throw new IMFAuthoringException(String.format("Exactly 1 MainImageSequence virtual track is required to create an IMP, none present")); } if(!cplFile.exists()){ throw new IMFAuthoringException(String.format("CompositionPlaylist file does not exist in the working directory %s, cannot generate the rest of the documents", workingDirectory.getAbsolutePath())); } byte[] cplHash = IMFUtils.generateSHA1Hash(cplFile); /** * Build the PackingList */ UUID pklUUID = IMFUUIDGenerator.getInstance().generateUUID(); PackingListBuilder packingListBuilder = new PackingListBuilder(pklUUID, IMFUtils.createXMLGregorianCalendar(), workingDirectory, imfErrorLogger); org.smpte_ra.schemas._2067_2._2016.pkl.UserText pklAnnotationText = PackingListBuilder.buildPKLUserTextType_2016(annotationText, "en"); org.smpte_ra.schemas._2067_2._2016.pkl.UserText creator = PackingListBuilder.buildPKLUserTextType_2016("Photon PackingListBuilder", "en"); org.smpte_ra.schemas._2067_2._2016.pkl.UserText pklIssuer = PackingListBuilder.buildPKLUserTextType_2016(issuer, "en"); List<PackingListBuilder.PackingListBuilderAsset_2016> packingListBuilderAssets = new ArrayList<>(); /** * Build the CPL asset to be entered into the PackingList */ UUID cplUUID = IMFUtils.extractUUIDFromCPLFile(cplFile, imfErrorLogger); PackingListBuilder.PackingListBuilderAsset_2016 cplAsset = new PackingListBuilder.PackingListBuilderAsset_2016(cplUUID, PackingListBuilder.buildPKLUserTextType_2016(annotationText, "en"), Arrays.copyOf(cplHash, cplHash.length), packingListBuilder.buildDefaultDigestMethodType(), cplFile.length(), PackingListBuilder.PKLAssetTypeEnum.TEXT_XML, PackingListBuilder.buildPKLUserTextType_2016(cplFile.getName(), "en")); packingListBuilderAssets.add(cplAsset); Set<Map.Entry<UUID, IMFTrackFileInfo>> trackFileInfoEntriesSet = trackFileInfoMap.entrySet().stream().filter( e -> !(e.getValue().isExcludeFromPackage())).collect(Collectors.toSet()); for(Map.Entry<UUID, IMFTrackFileInfo> entry : trackFileInfoEntriesSet){ PackingListBuilder.PackingListBuilderAsset_2016 asset = new PackingListBuilder.PackingListBuilderAsset_2016(entry.getKey(), PackingListBuilder.buildPKLUserTextType_2016(annotationText, "en"), Arrays.copyOf(entry.getValue().getHash(), entry.getValue().getHash().length), packingListBuilder.buildDefaultDigestMethodType(), entry.getValue().getLength(), PackingListBuilder.PKLAssetTypeEnum.APP_MXF, PackingListBuilder.buildPKLUserTextType_2016(entry.getValue().getOriginalFileName(), "en")); packingListBuilderAssets.add(asset); } packingListBuilder.buildPackingList_2016(pklAnnotationText, pklIssuer, creator, packingListBuilderAssets); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the PackingList. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } numErrors = (imfErrorLogger.getNumberOfErrors() > 0) ? imfErrorLogger.getNumberOfErrors()-1 : 0; File pklFile = new File(workingDirectory + File.separator + packingListBuilder.getPKLFileName()); if(!pklFile.exists()){ throw new IMFAuthoringException(String.format("PackingList file does not exist in the working directory %s, cannot generate the rest of the documents", workingDirectory.getAbsolutePath ())); } /** * Build the AssetMap */ UUID assetMapUUID = IMFUUIDGenerator.getInstance().generateUUID(); List<AssetMapBuilder.Asset> assetMapAssets = new ArrayList<>(); for(PackingListBuilder.PackingListBuilderAsset_2016 pklAsset : packingListBuilderAssets){ AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklAsset.getOriginalFileName().getValue(), pklAsset.getSize().longValue()); List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(UUIDHelper.fromUUIDAsURNStringToUUID(pklAsset.getUUID()), AssetMapBuilder.buildAssetMapUserTextType_2007(pklAsset.getAnnotationText().getValue(), "en"), false, chunkList); assetMapAssets.add(amAsset); } //Add the PKL as an AssetMap asset List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklFile.getName(), pklFile.length()); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(pklUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(pklAnnotationText.getValue(), "en"), true, chunkList); assetMapAssets.add(amAsset); AssetMapBuilder assetMapBuilder = new AssetMapBuilder(assetMapUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(annotationText, "en"), AssetMapBuilder.buildAssetMapUserTextType_2007("Photon AssetMapBuilder", "en"), IMFUtils.createXMLGregorianCalendar(), AssetMapBuilder.buildAssetMapUserTextType_2007(issuer, "en"), assetMapAssets, workingDirectory, imfErrorLogger); assetMapBuilder.build(); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the AssetMap. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } File assetMapFile = new File(workingDirectory + File.separator + assetMapBuilder.getAssetMapFileName()); if(!assetMapFile.exists()){ throw new IMFAuthoringException(String.format("AssetMap file does not exist in the working directory %s", workingDirectory.getAbsolutePath ())); } return imfErrorLogger.getErrors(); } /** * A method to generate the AssetMap, PackingList and CompositionPlaylist documents conforming to the * st0429-9:2007, st2067-2:2016 and st2067-2/3:2016 schemas respectively * @param annotationText a human readable text that will be used to annotate the corresponding elements of the XML documents * @param issuer a human readable text indicating the issuer of the XML documents * @param virtualTracks a list of all VirtualTracks that are a part of the Composition * @param compositionEditRate the EditRate of the composition * @param applicationId ApplicationId for the composition * @param trackFileInfoMap a Map of IMFTrackFileId to IMFTrackFileInfo * @param workingDirectory a folder location for the generated documents * @param essenceDescriptorDomNodeMap Map containing mapping between Track file ID to essence descriptor DOM node list * @return a list of errors that occurred while building an IMP * @throws IOException - any I/O related error will be exposed through an IOException * @throws ParserConfigurationException if a DocumentBuilder * cannot be created which satisfies the configuration requested by the underlying builder implementation * @throws SAXException - exposes any issues with instantiating a {@link javax.xml.validation.Schema Schema} object * @throws JAXBException - any issues in serializing the XML document using JAXB are exposed through a JAXBException * @throws URISyntaxException exposes any issues instantiating a {@link java.net.URI URI} object */ public static List<ErrorLogger.ErrorObject> buildIMP_2016(@Nonnull String annotationText, @Nonnull String issuer, @Nonnull List<? extends Composition.VirtualTrack> virtualTracks, @Nonnull Composition.EditRate compositionEditRate, @Nonnull String applicationId, @Nonnull Map<UUID, IMFTrackFileInfo> trackFileInfoMap, @Nonnull File workingDirectory, @Nonnull Map<UUID, List<Node>> essenceDescriptorDomNodeMap) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); int numErrors = imfErrorLogger.getNumberOfErrors(); UUID cplUUID = IMFUUIDGenerator.getInstance().generateUUID(); Set<String> applicationIds = Collections.singleton(applicationId); String coreConstraintsSchema = CoreConstraints.fromApplicationId(applicationIds); if (coreConstraintsSchema == null) coreConstraintsSchema = CoreConstraints.NAMESPACE_IMF_2016; Composition.VirtualTrack mainImageVirtualTrack = null; for(Composition.VirtualTrack virtualTrack : virtualTracks){ if(virtualTrack.getSequenceTypeEnum() == Composition.SequenceTypeEnum.MainImageSequence){ mainImageVirtualTrack = virtualTrack; break; } } if(mainImageVirtualTrack == null){ throw new IMFAuthoringException(String.format("Exactly 1 MainImageSequence virtual track is required to create an IMP, none present")); } /** * Logic to compute total running time */ long totalRunningTime = 0L; long totalNumberOfImageEditUnits = 0L; for(IMFTrackFileResourceType trackResource : (List<IMFTrackFileResourceType>)mainImageVirtualTrack.getResourceList()){ totalNumberOfImageEditUnits += trackResource.getSourceDuration().longValue() * trackResource.getRepeatCount().longValue(); } totalRunningTime = totalNumberOfImageEditUnits/(compositionEditRate.getNumerator()/compositionEditRate.getDenominator()); List<IMFEssenceDescriptorBaseType> imfEssenceDescriptorBaseTypeList = new ArrayList<>(); Map<UUID, UUID> trackFileIdToEssenceDescriptorIdMap = new HashMap<>(); for(AbstractApplicationComposition.ResourceIdTuple resourceIdTuple : getResourceIdTuples(virtualTracks)) { trackFileIdToEssenceDescriptorIdMap.put(resourceIdTuple.getTrackFileId(), resourceIdTuple.getSourceEncoding()); } for(Map.Entry<UUID, List<Node>> entry: essenceDescriptorDomNodeMap.entrySet()) { if(trackFileIdToEssenceDescriptorIdMap.containsKey(entry.getKey())) { imfEssenceDescriptorBaseTypeList.add(new IMFEssenceDescriptorBaseType(UUIDHelper.fromUUID(trackFileIdToEssenceDescriptorIdMap.get(entry.getKey())), new ArrayList<>( entry.getValue()))); } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Resource = %s is not referenced in the virtual track.", UUIDHelper.fromUUID(entry.getKey()))); } } CompositionPlaylistBuilder_2016 compositionPlaylistBuilder_2016 = new CompositionPlaylistBuilder_2016(cplUUID, CompositionPlaylistBuilder_2016.buildCPLUserTextType_2016(annotationText, "en"), CompositionPlaylistBuilder_2016.buildCPLUserTextType_2016(issuer, "en"), CompositionPlaylistBuilder_2016.buildCPLUserTextType_2016("Photon PackingListBuilder", "en"), virtualTracks, compositionEditRate, applicationIds, totalRunningTime, trackFileInfoMap, workingDirectory, imfEssenceDescriptorBaseTypeList, coreConstraintsSchema, trackFileIdToEssenceDescriptorIdMap); imfErrorLogger.addAllErrors(compositionPlaylistBuilder_2016.build()); if(compositionPlaylistBuilder_2016.getErrors().stream().filter( e -> e.getErrorLevel().equals(IMFErrorLogger .IMFErrors.ErrorLevels.FATAL)).count() > 0) { throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the CompositionPlaylist. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } numErrors = (imfErrorLogger.getNumberOfErrors() > 0) ? imfErrorLogger.getNumberOfErrors()-1 : 0; File cplFile = new File(workingDirectory + File.separator + compositionPlaylistBuilder_2016.getCPLFileName()); if(!cplFile.exists()){ throw new IMFAuthoringException(String.format("CompositionPlaylist file does not exist in the working directory %s, cannot generate the rest of the documents", workingDirectory.getAbsolutePath())); } byte[] cplHash = IMFUtils.generateSHA1Hash(cplFile); /** * Build the PackingList */ UUID pklUUID = IMFUUIDGenerator.getInstance().generateUUID(); PackingListBuilder packingListBuilder = new PackingListBuilder(pklUUID, IMFUtils.createXMLGregorianCalendar(), workingDirectory, imfErrorLogger); org.smpte_ra.schemas._2067_2._2016.pkl.UserText pklAnnotationText = PackingListBuilder.buildPKLUserTextType_2016(annotationText, "en"); org.smpte_ra.schemas._2067_2._2016.pkl.UserText creator = PackingListBuilder.buildPKLUserTextType_2016("Photon PackingListBuilder", "en"); org.smpte_ra.schemas._2067_2._2016.pkl.UserText pklIssuer = PackingListBuilder.buildPKLUserTextType_2016(issuer, "en"); List<PackingListBuilder.PackingListBuilderAsset_2016> packingListBuilderAssets = new ArrayList<>(); /** * Build the CPL asset to be entered into the PackingList */ PackingListBuilder.PackingListBuilderAsset_2016 cplAsset = new PackingListBuilder.PackingListBuilderAsset_2016(cplUUID, PackingListBuilder.buildPKLUserTextType_2016(annotationText, "en"), Arrays.copyOf(cplHash, cplHash.length), packingListBuilder.buildDefaultDigestMethodType(), cplFile.length(), PackingListBuilder.PKLAssetTypeEnum.TEXT_XML, PackingListBuilder.buildPKLUserTextType_2016(compositionPlaylistBuilder_2016.getCPLFileName(), "en")); packingListBuilderAssets.add(cplAsset); Set<Map.Entry<UUID, IMFTrackFileInfo>> trackFileInfoEntriesSet = trackFileInfoMap.entrySet().stream().filter( e -> !(e.getValue().isExcludeFromPackage())).collect(Collectors.toSet()); for(Map.Entry<UUID, IMFTrackFileInfo> entry : trackFileInfoEntriesSet){ PackingListBuilder.PackingListBuilderAsset_2016 asset = new PackingListBuilder.PackingListBuilderAsset_2016(entry.getKey(), PackingListBuilder.buildPKLUserTextType_2016(annotationText, "en"), Arrays.copyOf(entry.getValue().getHash(), entry.getValue().getHash().length), packingListBuilder.buildDefaultDigestMethodType(), entry.getValue().getLength(), PackingListBuilder.PKLAssetTypeEnum.APP_MXF, PackingListBuilder.buildPKLUserTextType_2016(entry.getValue().getOriginalFileName(), "en")); packingListBuilderAssets.add(asset); } packingListBuilder.buildPackingList_2016(pklAnnotationText, pklIssuer, creator, packingListBuilderAssets); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the PackingList. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } numErrors = (imfErrorLogger.getNumberOfErrors() > 0) ? imfErrorLogger.getNumberOfErrors()-1 : 0; File pklFile = new File(workingDirectory + File.separator + packingListBuilder.getPKLFileName()); if(!pklFile.exists()){ throw new IMFAuthoringException(String.format("PackingList file does not exist in the working directory %s, cannot generate the rest of the documents", workingDirectory.getAbsolutePath ())); } /** * Build the AssetMap */ UUID assetMapUUID = IMFUUIDGenerator.getInstance().generateUUID(); List<AssetMapBuilder.Asset> assetMapAssets = new ArrayList<>(); for(PackingListBuilder.PackingListBuilderAsset_2016 pklAsset : packingListBuilderAssets){ AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklAsset.getOriginalFileName().getValue(), pklAsset.getSize().longValue()); List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(UUIDHelper.fromUUIDAsURNStringToUUID(pklAsset.getUUID()), AssetMapBuilder.buildAssetMapUserTextType_2007(pklAsset.getAnnotationText().getValue(), "en"), false, chunkList); assetMapAssets.add(amAsset); } //Add the PKL as an AssetMap asset List<AssetMapBuilder.Chunk> chunkList = new ArrayList<>(); AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(pklFile.getName(), pklFile.length()); chunkList.add(chunk); AssetMapBuilder.Asset amAsset = new AssetMapBuilder.Asset(pklUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(pklAnnotationText.getValue(), "en"), true, chunkList); assetMapAssets.add(amAsset); AssetMapBuilder assetMapBuilder = new AssetMapBuilder(assetMapUUID, AssetMapBuilder.buildAssetMapUserTextType_2007(annotationText, "en"), AssetMapBuilder.buildAssetMapUserTextType_2007("Photon AssetMapBuilder", "en"), IMFUtils.createXMLGregorianCalendar(), AssetMapBuilder.buildAssetMapUserTextType_2007(issuer, "en"), assetMapAssets, workingDirectory, imfErrorLogger); assetMapBuilder.build(); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the AssetMap. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, numErrors, imfErrorLogger.getNumberOfErrors())))); } File assetMapFile = new File(workingDirectory + File.separator + assetMapBuilder.getAssetMapFileName()); if(!assetMapFile.exists()){ throw new IMFAuthoringException(String.format("AssetMap file does not exist in the working directory %s", workingDirectory.getAbsolutePath ())); } return imfErrorLogger.getErrors(); } public static Map<UUID, List<Node>> buildEDLForVirtualTracks (Map<UUID, IMPBuilder.IMFTrackFileMetadata> imfTrackFileMetadataMap, List<? extends Composition.VirtualTrack> virtualTrackList, IMFErrorLogger imfErrorLogger) throws IOException, ParserConfigurationException{ Map<UUID, List<Node>> imfEssenceDescriptorMap = new HashMap<>(); for(Composition.VirtualTrack virtualTrack : virtualTrackList) { if (!(virtualTrack instanceof IMFEssenceComponentVirtualTrack)) { continue; // Skip non-essence tracks } Set<UUID> trackResourceIds = IMFEssenceComponentVirtualTrack.class.cast(virtualTrack).getTrackResourceIds(); /** * Create the RegXML representation of the EssenceDescriptor metadata for every Resource of every VirtualTrack * of the Composition */ for (UUID uuid : trackResourceIds) { IMPBuilder.IMFTrackFileMetadata imfTrackFileMetadata = imfTrackFileMetadataMap.get(uuid); if (imfTrackFileMetadata == null) { throw new IMFAuthoringException(String.format("TrackFileHeaderMetadata for Track Resource Id %s within VirtualTrack Id %s is absent", uuid.toString(), virtualTrack.getTrackID())); } ByteProvider byteProvider = new ByteArrayDataProvider(imfTrackFileMetadata.getHeaderPartition()); ResourceByteRangeProvider resourceByteRangeProvider = new ByteArrayByteRangeProvider(imfTrackFileMetadata.getHeaderPartition()); //Create the HeaderPartition HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, (long) imfTrackFileMetadata.getHeaderPartition().length, imfErrorLogger); MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); List<InterchangeObject.InterchangeObjectBO> essenceDescriptors = headerPartition.getEssenceDescriptors(); for (InterchangeObject.InterchangeObjectBO essenceDescriptor : essenceDescriptors) { KLVPacket.Header essenceDescriptorHeader = essenceDescriptor.getHeader(); List<KLVPacket.Header> subDescriptorHeaders = new ArrayList<>(); List<InterchangeObject.InterchangeObjectBO> subDescriptors = headerPartition.getSubDescriptors(essenceDescriptor); for (InterchangeObject.InterchangeObjectBO subDescriptorBO : subDescriptors) { if (subDescriptorBO != null) { subDescriptorHeaders.add(subDescriptorBO.getHeader()); } } /*Create a dom*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); RegXMLLibHelper regXMLLibHelper = new RegXMLLibHelper(headerPartition.getPrimerPack().getHeader(), getByteProvider(resourceByteRangeProvider, headerPartition.getPrimerPack().getHeader())); DocumentFragment documentFragment = getEssenceDescriptorAsDocumentFragment(regXMLLibHelper, document, essenceDescriptorHeader, subDescriptorHeaders, resourceByteRangeProvider, imfErrorLogger); Node node = documentFragment.getFirstChild(); imfEssenceDescriptorMap.put(uuid, Arrays.asList(node)); } } } return imfEssenceDescriptorMap; } private static DocumentFragment getEssenceDescriptorAsDocumentFragment(RegXMLLibHelper regXMLLibHelper, Document document, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header>subDescriptors, ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws MXFException, IOException { document.setXmlStandalone(true); Triplet essenceDescriptorTriplet = regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor, getByteProvider(resourceByteRangeProvider, essenceDescriptor)); /*Get the Triplets corresponding to the SubDescriptors*/ List<Triplet> subDescriptorTriplets = new ArrayList<>(); for(KLVPacket.Header subDescriptorHeader : subDescriptors){ subDescriptorTriplets.add(regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, getByteProvider(resourceByteRangeProvider, subDescriptorHeader))); } return regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, imfErrorLogger); } private static ByteProvider getByteProvider(ResourceByteRangeProvider resourceByteRangeProvider, KLVPacket.Header header) throws IOException { byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(header.getByteOffset(), header.getByteOffset() + header.getKLSize() + header.getVSize()); return new ByteArrayDataProvider(bytes); } /** * A thin class representing the EssenceMetadata required to construct a CPL document */ public static class IMFTrackFileMetadata { private final byte[] headerPartition; private final byte[] hash; private final String hashAlgorithm; private final String originalFileName; private final long length; private final boolean excludeFromPackage; /** * A constructor for the EssenceMetadata required to construct a CPL document * @param headerPartition a byte[] containing the EssenceHeaderPartition metadata of the IMFTrack file * @param hash a byte[] containing the SHA-1, Base64 encoded hash of the IMFTrack file * @param hashAlgorithm a string representing the Hash Algorithm used to generate the Hash of the IMFTrack file * @param originalFileName a string representing the FileName of the IMFTrack file * @param length a long integer represeting the length of the IMFTrack file * @param excludeFromPackage a boolean indicating if this track file needs to be excluded from package. * If excluded this file will not be referenced in asset map and packing list but may be referenced in CPL. */ public IMFTrackFileMetadata(byte[] headerPartition, byte[] hash, String hashAlgorithm, String originalFileName, long length, boolean excludeFromPackage){ this.headerPartition = Arrays.copyOf(headerPartition, headerPartition.length); this.hash = Arrays.copyOf(hash, hash.length); this.hashAlgorithm = hashAlgorithm; this.originalFileName = originalFileName; this.length = length; this.excludeFromPackage = excludeFromPackage; } public IMFTrackFileMetadata(byte[] headerPartition, byte[] hash, String hashAlgorithm, String originalFileName, long length){ this( headerPartition, hash, hashAlgorithm, originalFileName, length, false); } /** * Getter for the HeaderPartition metadata for the IMFTrack file corresponding to the IMFTrackFile metadata * @return a byte[] containing the HeaderParition metadata */ public byte[] getHeaderPartition(){ return Arrays.copyOf(headerPartition, headerPartition.length); } /** * Getter for the Hash of the IMFTrackFile * @return a byte[] containing the SHA-1 Base64 encoded hash of the IMFTrackFile */ public byte[] getHash(){ return Arrays.copyOf(this.hash, this.hash.length); } /** * Getter for the HashAlgorithm used to create the Hash of the IMFTrackFile * @return a string representing the Hash of the IMFTrackFile */ public String getHashAlgorithm(){ return this.hashAlgorithm; } /** * Getter for the original file name of the IMFTrackFile * @return a string representing the name of the IMFTrackFile */ public String getOriginalFileName(){ return this.originalFileName; } /** * Getter for the length of the IMFTrackFile * @return a long integer representing the length of the track file in bytes */ public long getLength() { return this.length; } /** * Getter for the excludedFromPackage boolean flag * @return a boolean indicating of this file is excluded from the package */ public boolean isExcludeFromPackage() { return excludeFromPackage; } } /** * A thin class representing the track file info required to construct a CPL document */ public static class IMFTrackFileInfo { private final byte[] hash; private final String hashAlgorithm; private final String originalFileName; private final long length; private final boolean excludeFromPackage; /** * A constructor for the track file info required to construct a CPL document * @param hash a byte[] containing the SHA-1, Base64 encoded hash of the IMFTrack file * @param hashAlgorithm a string representing the Hash Algorithm used to generate the Hash of the IMFTrack file * @param originalFileName a string representing the FileName of the IMFTrack file * @param length a long integer represeting the length of the IMFTrack file * @param excludeFromPackage a boolean indicating if this track file needs to be excluded from package. * If excluded this file will not be referenced in asset map and packing list but may be referenced in CPL. */ public IMFTrackFileInfo(byte[] hash, String hashAlgorithm, String originalFileName, long length, boolean excludeFromPackage){ this.hash = Arrays.copyOf(hash, hash.length); this.hashAlgorithm = hashAlgorithm; this.originalFileName = originalFileName; this.length = length; this.excludeFromPackage = excludeFromPackage; } /** * Getter for the Hash of the IMFTrackFile * @return a byte[] containing the SHA-1 Base64 encoded hash of the IMFTrackFile */ public byte[] getHash(){ return Arrays.copyOf(this.hash, this.hash.length); } /** * Getter for the HashAlgorithm used to create the Hash of the IMFTrackFile * @return a string representing the Hash of the IMFTrackFile */ public String getHashAlgorithm(){ return this.hashAlgorithm; } /** * Getter for the original file name of the IMFTrackFile * @return a string representing the name of the IMFTrackFile */ public String getOriginalFileName(){ return this.originalFileName; } /** * Getter for the length of the IMFTrackFile * @return a long integer representing the length of the track file in bytes */ public long getLength() { return this.length; } /** * Getter for the excludedFromPackage boolean flag * @return a boolean indicating of this file is excluded from the package */ public boolean isExcludeFromPackage() { return excludeFromPackage; } } }
5,079
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/AssetMapBuilder.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFAuthoringException; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import com.netflix.imflibrary.writerTools.utils.ValidationEventHandlerImpl; import org.smpte_ra.schemas._429_9._2007.am.AssetType; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import javax.xml.XMLConstants; import javax.xml.bind.*; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; /** * A class that implements the logic to build a SMPTE st0429-9:2007 schema compliant AssetMap document. */ @Immutable public class AssetMapBuilder { private final UUID uuid; private final org.smpte_ra.schemas._429_9._2007.am.UserText annotationText; private final org.smpte_ra.schemas._429_9._2007.am.UserText creator; private final XMLGregorianCalendar issueDate; private final org.smpte_ra.schemas._429_9._2007.am.UserText issuer; private final List<AssetMapBuilder.Asset> assets; private final File workingDirectory; private final IMFErrorLogger imfErrorLogger; private final String assetMapFileName; /** * A constructor for the AssetMapBuilder object * @param uuid that uniquely identifies the AssetMap document * @param annotationText a free form human readable text * @param creator a free form human readable text describing the tool used to create the AssetMap document * @param issueDate date at which the AssetMap was issued * @param issuer a free form human readable text describing the issuer of the AssetMap document * @param assets a list of AssetMapBuilder.Asset roughly modeling the AssetMap assetlist * @param workingDirectory a folder location for the generated AssetMap document to be written to * @param imfErrorLogger a logger object to record errors that occur during the creation of the AssetMap document */ public AssetMapBuilder(@Nonnull UUID uuid, @Nonnull org.smpte_ra.schemas._429_9._2007.am.UserText annotationText, @Nonnull org.smpte_ra.schemas._429_9._2007.am.UserText creator, @Nonnull XMLGregorianCalendar issueDate, @Nonnull org.smpte_ra.schemas._429_9._2007.am.UserText issuer, @Nonnull List<AssetMapBuilder.Asset> assets, @Nonnull File workingDirectory, @Nonnull IMFErrorLogger imfErrorLogger){ this.uuid = uuid; this.annotationText = annotationText; this.creator = creator; this.issueDate = issueDate; this.issuer = issuer; this.assets = Collections.unmodifiableList(assets); this.workingDirectory = workingDirectory; this.imfErrorLogger = imfErrorLogger; this.assetMapFileName = "ASSETMAP.xml"; } /** * A method to construct a UserTextType compliant with the 2007 schema for IMF AssetMap documents * @param value the string that is a part of the annotation text * @param language the language code of the annotation text * @return a UserTextType */ public static org.smpte_ra.schemas._429_9._2007.am.UserText buildAssetMapUserTextType_2007(String value, String language){ org.smpte_ra.schemas._429_9._2007.am.UserText userTextType = new org.smpte_ra.schemas._429_9._2007.am.UserText(); userTextType.setValue(value); userTextType.setLanguage(language); return userTextType; } /** * A method to build an AssetMap document * @return a list of errors that occurred while generating the AssetMap document * @throws IOException - any I/O related error is exposed through an IOException */ public List<ErrorLogger.ErrorObject> build() throws IOException { org.smpte_ra.schemas._429_9._2007.am.AssetMapType assetMapType = IMFAssetMapObjectFieldsFactory.constructAssetMapType_2007(); assetMapType.setId(UUIDHelper.fromUUID(this.uuid)); assetMapType.setAnnotationText(this.annotationText); assetMapType.setCreator(this.creator); assetMapType.setVolumeCount(new BigInteger("1"));//According to st0429-9:2014 this should be set to 1. assetMapType.setIssueDate(this.issueDate); assetMapType.setIssuer(this.issuer); /** * Constructing the AssetList attribute of the AssetMap */ org.smpte_ra.schemas._429_9._2007.am.AssetMapType.AssetList assetList = new org.smpte_ra.schemas._429_9._2007.am.AssetMapType.AssetList(); List<org.smpte_ra.schemas._429_9._2007.am.AssetType> assetMapTypeAssets = assetList.getAsset(); for(AssetMapBuilder.Asset assetMapBuilderAsset : this.assets){ org.smpte_ra.schemas._429_9._2007.am.AssetType assetType = new AssetType(); assetType.setId(assetMapBuilderAsset.uuid); assetType.setPackingList(assetMapBuilderAsset.packingList); org.smpte_ra.schemas._429_9._2007.am.AssetType.ChunkList chunkList = new org.smpte_ra.schemas._429_9._2007.am.AssetType.ChunkList(); assetType.setChunkList(chunkList); List<org.smpte_ra.schemas._429_9._2007.am.ChunkType> chunkTypes = chunkList.getChunk(); List<AssetMapBuilder.Chunk> chunks = assetMapBuilderAsset.getChunks(); for(Chunk chunk : chunks){ org.smpte_ra.schemas._429_9._2007.am.ChunkType assetMapAssetChunk = new org.smpte_ra.schemas._429_9._2007.am.ChunkType(); assetMapAssetChunk.setPath(chunk.getPath()); assetMapAssetChunk.setVolumeIndex(chunk.getVolumeIndex()); assetMapAssetChunk.setOffset(chunk.getOffset()); assetMapAssetChunk.setLength(chunk.getLength()); chunkTypes.add(assetMapAssetChunk); } assetMapTypeAssets.add(assetType); } assetMapType.setAssetList(assetList); File outputFile = new File(this.workingDirectory + File.separator + this.assetMapFileName); List<ErrorLogger.ErrorObject> errors = serializeAssetMapToXML(assetMapType, outputFile, true); this.imfErrorLogger.addAllErrors(errors); return imfErrorLogger.getErrors(); } /** * A thin Immutable class roughly modeling the Asset Type in an AssetMap */ @Immutable public static final class Asset{ private final String uuid; private final org.smpte_ra.schemas._429_9._2007.am.UserText annotationText; private final boolean packingList; private final List<Chunk> chunks; /** * A constructor of the AssetMapBuilder's Asset class. * @param uuid a raw UUID that identifies this Asset in the AssetMap * @param annotationText org.smpte_ra.schemas._429_9._2007.am.UserText type * @param packingList a boolean indicating if this Asset is a packing list or not * @param chunks a list of AssetMapBuilder.Chunk type roughly modeling an AssetMap Asset's chunk */ public Asset(UUID uuid, org.smpte_ra.schemas._429_9._2007.am.UserText annotationText, boolean packingList, List<Chunk> chunks){ this.uuid = UUIDHelper.fromUUID(uuid); this.annotationText = annotationText; this.packingList = packingList; this.chunks = Collections.unmodifiableList(chunks); } /** * Getter for the urn:uuid: that uniquely identifies this asset * @return a "urn:uuid:" string */ public String getUuid(){ return this.uuid; } /** * Getter for the Asset's annotation text * @return org.smpte_ra.schemas._429_9._2007.am.UserText of the Asset */ public org.smpte_ra.schemas._429_9._2007.am.UserText getAnnotationText(){ return this.annotationText; } /** * Getter for the boolean indicating PackingList * @return boolean to indicate if this asset is a PackingList or not */ public boolean isPackingList(){ return this.packingList; } /** * Getter for the list of Chunks representing the Asset * @return a list of chunks corresponding to the Asset */ public List<Chunk> getChunks(){ return this.chunks; } } /** * A thin immutable class roughly modeling the concept of a Chunk of an AssetMap's asset. */ @Immutable public static final class Chunk { private final String path; private final BigInteger volumeIndex = BigInteger.valueOf(1); //According to st0429-9:2014 this should be 1 or absent. private final BigInteger offset = BigInteger.valueOf(0); //According to st0429-9:2014 this should be 0 or absent. private final BigInteger length; /** * A constructor of the AssetMapBuilder's Chunk class. * @param path a URI compliant with the following RegEx : "^[a-zA-Z0-9._-]+" * @param length in bytes of the chunk of the asset * @throws URISyntaxException - any errors with the path of the Chunk is exposed through a URISyntaxException */ public Chunk(String path, Long length) throws URISyntaxException { String[] pathSegments = path.split("/"); List<String> invalidPathSegments = new ArrayList<>(); for(String pathSegment : pathSegments) { if (pathSegment.matches("^[a-zA-Z0-9._-]+") == false) { invalidPathSegments.add(pathSegment); } } if(invalidPathSegments.size() > 0){ throw new URISyntaxException(path, String.format("The Asset path %s does not conform to the specified URI syntax in Annex-A of st429-9:2014 (a-z, A-Z, 0-9, ., _, -) for a path segment, the following path segments do not comply %s", path, Utilities.serializeObjectCollectionToString(invalidPathSegments))); } this.path = path; this.length = BigInteger.valueOf(length); } /** * Getter for the path of a chunk * @return a string representation of the path to a chunk of an Asset */ public String getPath(){ return this.path; } /** * Getter for the VolumeIndex of a chunk * @return a BigInteger corresponding to the VolumeIndex of the chunk */ @Nonnull public BigInteger getVolumeIndex(){ return this.volumeIndex; } /** * Getter for the offset of a chunk * @return a BigInteger representing the offset of the chunk */ @Nonnull public BigInteger getOffset(){ return this.offset; } /** * Getter for the length of a chunk * @return a BigInteger representing the length of the chunk in bytes */ @Nonnull public BigInteger getLength(){ return this.length; } } private List<IMFErrorLogger.ErrorObject> serializeAssetMapToXML(org.smpte_ra.schemas._429_9._2007.am.AssetMapType assetMapType, File outputFile, boolean formatted) throws IOException { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); try { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); InputStream assetMapSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0429_9_2007/AM/assetMap_schema.xsd"); OutputStream outputStream = new FileOutputStream(outputFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource[] schemaSources = new StreamSource[1]; schemaSources[0] = new StreamSource(assetMapSchemaAsAStream); Schema schema = schemaFactory.newSchema(schemaSources); JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas._429_9._2007.am"); Marshaller marshaller = jaxbContext.createMarshaller(); ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true); marshaller.setEventHandler(validationEventHandler); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted); /*marshaller.marshal(cplType, output); workaround for 'Error: unable to marshal type "AssetMapType" as an element because it is missing an @XmlRootElement annotation' as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always */ marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/429-9/2007/AM", "AssetMap"), org.smpte_ra.schemas._429_9._2007.am.AssetMapType.class, assetMapType), outputStream); outputStream.close(); if (validationEventHandler.hasErrors()) { //TODO : Perhaps a candidate for a Lambda for (ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, validationErrorObject.getValidationEventSeverity(), validationErrorObject.getErrorMessage()); } } } catch( SAXException | JAXBException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_AM_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, e.getMessage()); } return imfErrorLogger.getErrors(); } /** * Getter for the AssetMap file name * * @return File name for the AssetMap */ public String getAssetMapFileName() { return this.assetMapFileName; } }
5,080
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/IMFCPLObjectFieldsFactory.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.writerTools.utils.IMFDocumentsObjectFieldsFactory; public final class IMFCPLObjectFieldsFactory { /*Prevent instantiation*/ private IMFCPLObjectFieldsFactory(){ } /** * A factory method that constructs a 2013 Schema compliant CompositionPlaylistType object and recursively constructs all of its constituent fields. * Note: Fields that are either Java primitives, wrapperTypes or a subclass of Collection * are not constructed by this method for the reason that the field's accessor methods would do so. * * @return A 2013 schema compliant CompositionPlaylistType object */ public static org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType constructCompositionPlaylistType_2013(){ org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType cplType_2013 = new org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType(); IMFDocumentsObjectFieldsFactory.constructObjectFields(cplType_2013); return cplType_2013; } /** * A factory method that constructs a 2016 Schema compliant CompositionPlaylistType object and recursively constructs all of its constituent fields. * Note: Fields that are either Java primitives, wrapperTypes or a subclass of Collection * are not constructed by this method for the reason that the field's accessor methods would do so. * * @return A 2016 schema compliant CompositionPlaylistType object */ public static org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType constructCompositionPlaylistType_2016() { org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType cplType_2016 = new org.smpte_ra.schemas._2067_3._2016.CompositionPlaylistType(); IMFDocumentsObjectFieldsFactory.constructObjectFields(cplType_2016); return cplType_2016; } }
5,081
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/utils/IMFUUIDGenerator.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools.utils; import java.util.HashSet; import java.util.Set; import java.util.UUID; /** * A class that provides the utility of maintaining a list of UUIDs currently in use and generating an UUID for use in an * IMF CPL document */ public class IMFUUIDGenerator { private final Set<UUID> assignedUUIDs = new HashSet<>(); private volatile static IMFUUIDGenerator uniqueInstance; /** * This class is a singleton, hence prevent instantiation by having a private constructor * @return */ private IMFUUIDGenerator(){ } /** * A double checked locking implementation of the getInstance() method to return the singleton instance * @return the uniqueInstance of this class */ public static IMFUUIDGenerator getInstance(){ if(uniqueInstance == null){ synchronized (IMFUUIDGenerator.class){ if(uniqueInstance == null){ uniqueInstance = new IMFUUIDGenerator(); } } } return uniqueInstance; } /** * A method that generates a UUID * Note: this method guarantees uniqueness only as long as the class remains loaded * @return string representation of the UUID */ public String getUrnUUID(){ //Create the UUID string return "urn" + ":" + "uuid" + ":" + generateUUID(); } /** * A method that generates a UUID * Note: This method does not guarantee uniqueness across multiple invocations of the Photon library * @return a UUID */ public UUID generateUUID(){ String uuidString = ""; UUID uuid = null; while(!uuidString.matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") || assignedUUIDs.contains(uuid)) { uuid = UUID.randomUUID(); uuidString = uuid.toString(); } assignedUUIDs.add(uuid); return uuid; } }
5,082
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/utils/IMFDocumentsObjectFieldsFactory.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools.utils; import com.netflix.imflibrary.exceptions.MXFException; import javax.xml.datatype.XMLGregorianCalendar; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.math.BigInteger; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * A class that implements helper methods to construct object fields within IMF documents such as AssetMap, PackingList, * CompositionPlaylist etc. */ public final class IMFDocumentsObjectFieldsFactory { private static final Set<Class<?>> setOfWrapperTypes = Collections.unmodifiableSet(new HashSet<Class<?>>() { { /* Java Wrapper types */ add(Boolean.class); add(Character.class); add(Byte.class); add(Short.class); add(Integer.class); add(Long.class); add(Float.class); add(Double.class); add(Void.class); add(Enum.class); add(BigInteger.class); } }); private static final Set<Class<?>> setOfPrimitiveTypes = Collections.unmodifiableSet(new HashSet<Class<?>>() { { /* Java Primitive types */ add(boolean.class); add(char.class); add(byte.class); add(short.class); add(int.class); add(long.class); add(float.class); add(double.class); add(void.class); add(byte[].class); } }); /** * To prevent instantiation */ private IMFDocumentsObjectFieldsFactory(){ } public static void constructObjectFields(Object object) { try { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { // Skip synthetic fields. They don't need to be recreated if (field.isSynthetic()) continue; Class<?> fieldType = field.getType(); // No need to construct primitive types (int, boolean, ...) if (setOfPrimitiveTypes.contains(fieldType)) continue; // No need to construct wrapper types (Integer, Long, Enum, ...) if (setOfWrapperTypes.contains(fieldType)) continue; // No need to construct String, because it is immutable and will be set when assigned if (fieldType.equals(String.class)) continue; // No need to construct XMLGregorianCalendar, because an already constructed instance will be provided when assigned if(XMLGregorianCalendar.class.isAssignableFrom(fieldType)) continue; // Types that wrap a collection provide access to the collection through // an accessor hence negating the need to construct the collection. if(Collection.class.isAssignableFrom(fieldType)) continue; // Construct a field of a complex type, and construct that types fields recursively Object value = constructObjectByName(fieldType); constructObjectFields(value); // Update this field with the newly constructed object field.setAccessible(true); field.set(object, value); } } catch(IllegalAccessException e){ throw new MXFException(String.format("Error occurred while trying to construct %s", object.getClass().getSimpleName())); } } private static Object constructObjectByName(Class clazz) throws MXFException{ try { Constructor<?> constructor = clazz.getConstructor(); return clazz.cast(constructor.newInstance()); } catch(NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e){ throw new MXFException(String.format("Error occurred while trying to construct %s", clazz.getSimpleName())); } } }
5,083
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/utils/ValidationEventHandlerImpl.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools.utils; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ErrorLogger; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A thread-safe implementation of the ValidationEventHandler interface for validating an XML serializing operation */ public class ValidationEventHandlerImpl implements ValidationEventHandler { private final boolean continueOnError; private final List<ValidationErrorObject> errors = new ArrayList<>(); /** * A constructor for the ValidationEventHandlerImpl object * @param continueOnError - boolean that determines if XML serializing operation should be persisted in the event of an error */ public ValidationEventHandlerImpl(boolean continueOnError){ this.continueOnError = continueOnError; } /** * An event handler callback for the XML serializing operation * @param event the XML validation event that needs to be handled * @return boolean to indicate whether to abort/proceed when an error is encountered */ public boolean handleEvent( ValidationEvent event ){ this.errors.add(new ValidationErrorObject(event.getSeverity(), event.getLocator().getLineNumber(), event.getMessage())); return this.continueOnError; } /** * Checks if any errors occurred while serializing an XML document * @return boolean to signal if serializing the XML document occurred with/without errors */ public boolean hasErrors(){ return (this.errors.size() > 0); } /** * Checks if any errors occurred while serializing an XML document * @return list of ErrorObjects with errors */ public List<ValidationErrorObject> getErrors(){ return Collections.unmodifiableList(this.errors); } /** * A method that returns a string representation of a ValidationEventHandlerImpl object * @return string representing the object */ public String toString(){ StringBuilder stringBuilder = new StringBuilder(); for(ValidationErrorObject error : errors){ stringBuilder.append(error.toString()); } return stringBuilder.toString(); } /** * A class that represents errors that occur while serializing an XML document */ public static class ValidationErrorObject{ private final int validationEventSeverity; private final int lineNumber; private final String errorMessage; private ValidationErrorObject(int validationEventSeverity, int lineNumber, String errorMessage){ this.validationEventSeverity = validationEventSeverity; this.errorMessage = errorMessage; this.lineNumber = lineNumber; } /** * A getter for ValidationEvent error severity * @return a translation of the validation event error severity to IMFErrorLogger's ErrorLevel enumeration */ public IMFErrorLogger.IMFErrors.ErrorLevels getValidationEventSeverity(){ switch(this.validationEventSeverity){ case ValidationEvent.ERROR: return IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL; case ValidationEvent.FATAL_ERROR: return IMFErrorLogger.IMFErrors.ErrorLevels.FATAL; case ValidationEvent.WARNING: return IMFErrorLogger.IMFErrors.ErrorLevels.WARNING; default: return IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL; } } /** * A getter for the ValidationError message * @return a string representing the ValidationError message */ public String getErrorMessage(){ return this.errorMessage; } /** * A getter for the ValidationError line number * @return an integer corresponding to the line number where the error occurs */ public Integer getLineNumber() { return this.lineNumber;} /** * A toString() method to return the String representation of the ValidationErrorObject * @return a string corresponding to the error message with details on error level, code and line number */ @Override public String toString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("%s - %s - %s", getValidationEventSeverity(), getLineNumber(), getErrorMessage())); return stringBuilder.toString(); } } }
5,084
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/utils/IMFUtils.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools.utils; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.smpte_ra.schemas._2067_3._2013.BaseResourceType; import org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType; import org.xml.sax.SAXException; import javax.annotation.Nullable; import javax.xml.bind.JAXBException; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; /** * A class that provides utility methods to help with serializing an IMF CPL to an XML document */ public class IMFUtils { /** * Private constructor to prevent instantiation */ private IMFUtils(){ } /** * A utility method to create an XMLGregorianCalendar * @return the constructed XMLGregorianCalendar */ @Nullable public static XMLGregorianCalendar createXMLGregorianCalendar(){ XMLGregorianCalendar result = null; try { DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); TimeZone utc = TimeZone.getTimeZone("UTC"); GregorianCalendar now = new GregorianCalendar(utc); result = datatypeFactory.newXMLGregorianCalendar(now); } catch (DatatypeConfigurationException e){ throw new IMFException("Could not create a XMLGregorianCalendar instance"); } return result; } /** * A method that generates a CPL schema valid TimecodeStartAddress string * @return a string representing the time code start address compliant with its regex definition */ public static String generateTimecodeStartAddress(){ String delimiter = ":"; String timeCodeStartAddress = "00:00:00:00"; if(timeCodeStartAddress.matches("[0-2][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9]")){ return timeCodeStartAddress; } else{ throw new IMFException(String.format("Could not generate a valid TimecodeStartAddress based on input " + "received")); } } /** * A method that generates a SHA-1 hash of the file. * * @param file - the file whose SHA-1 hash is to be generated * @return a byte[] representing the generated hash of the file * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateSHA1Hash(File file) throws IOException { ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(file); return IMFUtils.generateHash(resourceByteRangeProvider, "SHA-1"); } /** * A method that generates a SHA-1 hash of the incoming resource. * * @param resourceByteRangeProvider representing the resource whose digest is to be generated * @return a byte[] representing the generated hash of the file * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateSHA1Hash(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException { return IMFUtils.generateHash(resourceByteRangeProvider, "SHA-1"); } /** * A method that generates a SHA-1 hash of the file and Base64 encode the result. * * @param file - the file whose SHA-1 hash is to be generated * @return a byte[] representing the generated base64 encoded hash of the file * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateSHA1HashAndBase64Encode(File file) throws IOException { return generateBase64Encode(generateSHA1Hash(file)); } /** * A method to generate a Base64 encoded representation of a byte[] * @param bytes a byte[] that is to be Base64 encoded * @return a byte[] representing the Base64 encode of the input */ public static byte[] generateBase64Encode(byte[] bytes){ byte[] hashCopy = Arrays.copyOf(bytes, bytes.length); return Base64.getEncoder().encode(hashCopy); } /** * A method to generate a digest of the incoming resource for a given algorithm * @param resourceByteRangeProvider representing the resource whose digest is to be generated * @param hashAlgorithm the name of the hash algorithm * @return a byte[] representing the digest of the resource * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateHash(ResourceByteRangeProvider resourceByteRangeProvider, String hashAlgorithm) throws IOException { try { MessageDigest md = MessageDigest.getInstance(hashAlgorithm); long rangeStart = 0; long rangeEnd = (rangeStart + 1023 > resourceByteRangeProvider.getResourceSize() - 1) ? resourceByteRangeProvider.getResourceSize() - 1 : rangeStart + 1023; int nread = 0; while (rangeStart < resourceByteRangeProvider.getResourceSize() && rangeEnd < resourceByteRangeProvider.getResourceSize()) { byte[] dataBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); nread = (int) (rangeEnd - rangeStart + 1); md.update(dataBytes, 0, nread); rangeStart = rangeEnd + 1; rangeEnd = (rangeStart + 1023 > resourceByteRangeProvider.getResourceSize() - 1) ? resourceByteRangeProvider.getResourceSize() - 1 : rangeStart + 1023; } byte[] mdbytes = md.digest(); return Arrays.copyOf(mdbytes, mdbytes.length); } catch (NoSuchAlgorithmException e){ throw new IMFException(e); } } /** * A method to cast the object that was passed in to the specified subclass safely * * @param <T> the type of BaseResource * @param baseResourceType - the object that needs to cast to the subclass of this type * @param cls the Class for the casted type * @return T casted type * @throws IMFException - a class cast failure is exposed through an IMFException */ public static <T extends BaseResourceType> T safeCast(BaseResourceType baseResourceType, Class<T> cls) throws IMFException { if(baseResourceType == null){ return null; } if(!cls.isAssignableFrom(baseResourceType.getClass())) { throw new IMFException(String.format("Unable to cast from Box type %s to %s", baseResourceType.getClass() .getName(), cls.getName())); } return cls.cast(baseResourceType); } /** * A utility method that writes out the serialized IMF CPL document to a file * * @param compositionPlaylistType an instance of the composition playlist type * @param outputFile the file that the serialized XML is written to * @throws IOException - any I/O related error will be exposed through an IOException */ public static void writeCPLToFile(CompositionPlaylistType compositionPlaylistType, File outputFile) throws IOException { try { IMFCPLSerializer imfcplSerializer = new IMFCPLSerializer(); FileOutputStream fileOutputStream = new FileOutputStream(outputFile); imfcplSerializer.write(compositionPlaylistType, fileOutputStream, true); fileOutputStream.close(); } catch (FileNotFoundException e){ throw new IMFException(String.format("Error occurred while trying to serialize the CompositionPlaylistType, file %s not found", outputFile.getName())); } catch(SAXException | JAXBException e ){ throw new IMFException(e); } } public static UUID extractUUIDFromCPLFile(File cplFile, IMFErrorLogger imfErrorLogger) { try { ApplicationComposition applicationComposition = com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.getApplicationComposition(cplFile, imfErrorLogger); return applicationComposition.getUUID(); } catch (IOException e) { throw new IMFException(String.format("Error occurred while parsing CPL File %s", cplFile.toString())); } } }
5,085
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools
Create_ds/photon/src/main/java/com/netflix/imflibrary/writerTools/utils/IMFCPLSerializer.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools.utils; import org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType; import javax.annotation.concurrent.ThreadSafe; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * This class assists in serializing an IMF CPL root element to an XML file */ @ThreadSafe class IMFCPLSerializer { /** * A method that serializes the CompositionPlaylistType root element to an XML file * * @param cplType the composition playlist object * @param output stream to which the resulting serialized XML document is written to * @param formatted a boolean to indicate if the serialized XML should be formatted (good idea to have it set to true always) * @throws IOException - any I/O related error will be exposed through an IOException * @throws org.xml.sax.SAXException - any issues with instantiating a schema object with the schema sources will be exposed * through a SAXException * @throws javax.xml.bind.JAXBException - any issues in serializing the XML document using JAXB will be exposed through a JAXBException */ public void write(CompositionPlaylistType cplType, OutputStream output, boolean formatted) throws IOException, org.xml.sax.SAXException, JAXBException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try( InputStream cplSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_3_2013/imf-cpl.xsd"); InputStream dcmlSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd"); InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd"); InputStream coreConstraintsSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2013/imf-core-constraints-20130620-pal.xsd") ) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI ); StreamSource[] schemaSources = new StreamSource[4]; schemaSources[0] = new StreamSource(dsigSchemaAsAStream); schemaSources[1] = new StreamSource(dcmlSchemaAsAStream); schemaSources[2] = new StreamSource(cplSchemaAsAStream); schemaSources[3] = new StreamSource(coreConstraintsSchemaAsAStream); Schema schema = schemaFactory.newSchema(schemaSources); JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas._2067_3._2013"); Marshaller marshaller = jaxbContext.createMarshaller(); ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true); marshaller.setEventHandler(validationEventHandler); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted); /*marshaller.marshal(cplType, output); workaround for 'Error: unable to marshal type "CompositionPlaylistType" as an element because it is missing an @XmlRootElement annotation' as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always */ marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/2067-3/2013", "CompositionPlaylist"), CompositionPlaylistType.class, cplType), output); if(validationEventHandler.hasErrors()) { throw new IOException(validationEventHandler.toString()); } } } }
5,086
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st379_2/ContainerConstraintsSubDescriptor.java
/* * * Copyright 2020 RheinMain University of Applied Sciences, Wiesbaden, Germany. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.st379_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.st0377.header.SubDescriptor; import com.netflix.imflibrary.st0377.header.StructuralMetadata; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to ContainerConstraintsSubDescriptor as defined in ST 379-2 */ @Immutable public final class ContainerConstraintsSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + ContainerConstraintsSubDescriptor.class.getSimpleName() + " : "; private final ContainerConstraintsSubDescriptorBO subDescriptorBO; /** * Constructor for a ContainerConstraintsSubDescriptor object * @param subDescriptorBO the parsed ContainerConstraintsSubDescriptor object */ public ContainerConstraintsSubDescriptor(ContainerConstraintsSubDescriptorBO subDescriptorBO){ this.subDescriptorBO = subDescriptorBO; } /** * A method that returns a string representation of a ContainerConstraintsSubDescriptor object * * @return string representing the object */ public String toString() { return this.subDescriptorBO.toString(); } /** * Object corresponding to a parsed ContainerConstraintsSubDescriptor as defined in st429-4-2006 */ @Immutable public static final class ContainerConstraintsSubDescriptorBO extends SubDescriptorBO{ /** * Instantiates a new ContainerConstraintsSubDescriptor ByteObject. * * @param header the header * @param byteProvider the mxf byte provider * @param localTagToUIDMap the local tag to uID map * @param imfErrorLogger the imf error logger * @throws IOException - any I/O related error will be exposed through an IOException */ public ContainerConstraintsSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ContainerConstraintsSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a ContainerConstraintsSubDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== ContainerConstraintsSubDescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); return sb.toString(); } } }
5,087
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/Fraction.java
package com.netflix.imflibrary.utils; /** * Created by svenkatrav on 10/26/16. */ public class Fraction { private final Integer numerator; private final Integer denominator; /** * Instantiates a new Fraction. * * @param numerator Numerator value of the Fraction * @param denominator Denominator value of the Fraction */ public Fraction(Integer numerator, Integer denominator) { this.numerator = numerator; this.denominator = denominator; } /** * Instantiates a new Fraction. * * @param numerator Numerator value of the Fraction */ public Fraction(Integer numerator) { this.numerator = numerator; this.denominator = 1; } /** * Returns a fraction holding the value represented by the string argument. * @param s the string to be parsed * @return Returns a fraction holding the value represented by the string argument */ public static Fraction valueOf(String s) { try { String values[] = s.split("(\\s|/)"); if (values.length == 2) { return new Fraction(Integer.valueOf(values[0]), Integer.valueOf(values[1])); } } catch(Exception e) { return null; } return null; } /** * Getter for the numerator of the rational * * @return the numerator */ public Integer getNumerator() { return this.numerator; } /** * Getter for the denominator of the rational * * @return the denominator */ public Integer getDenominator() { return this.denominator; } /** * A method to compare 2 rationals, returns true if the rationals match or false if they do not * Note : If the object that was passed in is not an instance of rational this method will return * false * @param other the object that this rational object should be compared with * @return result of comparing this rational object with the object that was passed in */ public boolean equals(Object other) { if (other == null || !(other instanceof Fraction)) { return false; } Fraction otherObject = (Fraction)other; return (this.numerator.equals(otherObject.getNumerator()) && this.denominator.equals(otherObject.getDenominator())); } /** * A method that returns the sum of hashes corresponding to the numerator and denominator of this rational * @return the sum of hashes corresponding to the numerator and denominator of this rational */ public int hashCode() { Integer hash = 1; hash = hash * 31 + this.numerator; hash = hash * 31 + this.denominator; return hash; } /** * A method that returns a string representation of a Rational object * * @return string representing the object */ public String toString() { return String.format("%d/%d", this.numerator, this.denominator); }}
5,088
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/DOMNodeObjectModel.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.utils; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.st0377.header.UL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; /** * A class that implements the logic of representing a DOM Node into a Hierarchical Hash Map */ public class DOMNodeObjectModel { /*See definitions of NodeType in package org.w3c.dom.Node*/ @Nonnull private final Node node; @Nonnull private final Short nodeType; /*Node's Local Name*/ @Nonnull private final String localName; @Nonnull private final String localNamespaceURI; /*List of child ElementDOMNodes*/ private final Map<DOMNodeObjectModel, Integer> childrenDOMNodes = new LinkedHashMap<>(); /*Store for the Key-Value pairs corresponding of the Text Nodes of this ElementDOMNode*/ private final Map<DOMNodeElementTuple, Map<String, Integer>> fields = new HashMap<>(); private final Map<String, Map<String, Integer>> fieldsLocalNameMap = new HashMap<>(); private static final Logger logger = LoggerFactory.getLogger(DOMNodeObjectModel.class); private final IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); /** * A constructor for the object model of a DOM Node. * @param node the DOM Node whose object model is desired. */ public DOMNodeObjectModel(@Nonnull Node node){ this.node = node; this.nodeType = node.getNodeType(); this.localName = node.getLocalName(); this.localNamespaceURI = node.getNamespaceURI(); if(this.localName == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.NON_FATAL, String.format("DOM Node Local Name is not set for a node of type %d", node.getNodeType())); return; } Node child = node.getFirstChild(); switch(child.getNodeType()){ case Node.ELEMENT_NODE: while(child != null) { Node grandChild = child.getFirstChild(); if (grandChild != null){ if(grandChild.getNodeType() == Node.TEXT_NODE) { DOMNodeElementTuple domNodeElementTuple = new DOMNodeElementTuple(child.getNamespaceURI(), child.getLocalName()); Map<String, Integer> values = fields.get(domNodeElementTuple); Map<String, Integer> fieldsLocalNameValues = fieldsLocalNameMap.get(domNodeElementTuple.getLocalName()); if (values == null) { values = new HashMap<String, Integer>(); fields.put(domNodeElementTuple, values); } if(fieldsLocalNameValues == null){ fieldsLocalNameValues = new HashMap<String, Integer>(); fieldsLocalNameMap.put(domNodeElementTuple.getLocalName(), fieldsLocalNameValues); } Integer count = 0; if(values.containsKey(child.getFirstChild().getNodeValue())) { count = values.get(child.getFirstChild().getNodeValue()); } values.put(child.getFirstChild().getNodeValue(), count+1); Integer localNameCount = 0; if(fieldsLocalNameValues.containsKey(domNodeElementTuple.getNamespaceURI())){ localNameCount = fieldsLocalNameValues.get(domNodeElementTuple.getNamespaceURI()); } fieldsLocalNameValues.put(domNodeElementTuple.getNamespaceURI(), localNameCount+1); } else { Integer count = 0; DOMNodeObjectModel domNode = new DOMNodeObjectModel(child); if(childrenDOMNodes.containsKey(domNode)) { count = childrenDOMNodes.get(domNode); } childrenDOMNodes.put(domNode, count+1); imfErrorLogger.addAllErrors(domNode.getErrors()); } } child = child.getNextSibling(); } break; case Node.COMMENT_NODE: //Ignore comment nodes break; default: String message = String.format("Unsupported DOM Node type %d ", child.getNodeType()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } } private DOMNodeObjectModel(Node node, String localName, String localNamespaceURI, short nodeType, Map<DOMNodeObjectModel, Integer> childrenDOMNodes, Map<DOMNodeElementTuple, Map<String, Integer>> fields, Map<String, Map<String, Integer>> fieldsLocalNamesMap){ this.node = node; this.localName = localName; this.localNamespaceURI = localNamespaceURI; this.nodeType = nodeType; this.childrenDOMNodes.putAll(childrenDOMNodes); this.fields.putAll(fields); this.fieldsLocalNameMap.putAll(fieldsLocalNamesMap); } /** * A static factory method that will create a DOMNodeObjectModel without the fields that were set to be ignored * @param domNodeObjectModel a DOMNodeObjectModel object to derive the statically constructed model from * @param ignoreSet a non-null, empty or non-empty set of strings representing the local names of the DOM Node elements * that should be excluded in from the newly minted DOMNodeObjectModel * @return a DOMNodeObjectModel that excludes the elements indicated in the ignore set. */ public static DOMNodeObjectModel createDOMNodeObjectModelIgnoreSet(DOMNodeObjectModel domNodeObjectModel, @Nonnull Set<String> ignoreSet){ Map<DOMNodeElementTuple, Map<String, Integer>> thisFields = new HashMap<>(); for(Map.Entry<DOMNodeElementTuple, Map<String, Integer>> entry : domNodeObjectModel.getFields().entrySet()){ if(!ignoreSet.contains(entry.getKey().getLocalName())){ thisFields.put(entry.getKey(), entry.getValue()); } } Map<String, Map<String, Integer>> thisFieldsLocalNamesMap = new HashMap<>(); for(Map.Entry<String, Map<String, Integer>> entry : domNodeObjectModel.getFieldsLocalNameMap().entrySet()){ if(!ignoreSet.contains(entry.getKey())){ thisFieldsLocalNamesMap.put(entry.getKey(), entry.getValue()); } } Map<DOMNodeObjectModel, Integer> childrenDOMNodes = new HashMap<>(); for(Map.Entry<DOMNodeObjectModel, Integer> entry : domNodeObjectModel.getChildrenDOMNodes().entrySet()){ if(!ignoreSet.contains(entry.getKey().getLocalName())) { DOMNodeObjectModel child = entry.getKey().createDOMNodeObjectModelIgnoreSet(entry.getKey(), ignoreSet); if (child.getChildrenDOMNodes().size() > 0 || child.getFields().size() > 0) { childrenDOMNodes.put(child, entry.getValue()); } } } return new DOMNodeObjectModel(domNodeObjectModel.getNode(), domNodeObjectModel.getLocalName(), domNodeObjectModel.getLocalNamespaceURI(), domNodeObjectModel.getNodeType(), Collections.unmodifiableMap(childrenDOMNodes), Collections.unmodifiableMap(thisFields), Collections.unmodifiableMap(thisFieldsLocalNamesMap)); } /** * A static factory method that will create a DOMNodeObjectModel with the selected fields only * @param domNodeObjectModel a DOMNodeObjectModel object to derive the statically constructed model from * @param selectionSet a non-null, empty or non-empty set of strings representing the local names of the DOM Node elements * that should be included in the newly minted DOMNodeObjectModel * @return a DOMNodeObjectModel that contains only the elements indicated in the selection set. */ public static DOMNodeObjectModel createDOMNodeObjectModelSelectionSet(DOMNodeObjectModel domNodeObjectModel, @Nonnull Set<String> selectionSet){ Map<DOMNodeElementTuple, Map<String, Integer>> thisFields = new HashMap<>(); for(Map.Entry<DOMNodeElementTuple, Map<String, Integer>> entry : domNodeObjectModel.getFields().entrySet()){ if(selectionSet.contains(entry.getKey().getLocalName())){ thisFields.put(entry.getKey(), entry.getValue()); } } Map<String, Map<String, Integer>> thisFieldsLocalNamesMap = new HashMap<>(); for(Map.Entry<String, Map<String, Integer>> entry : domNodeObjectModel.getFieldsLocalNameMap().entrySet()){ if(selectionSet.contains(entry.getKey())){ thisFieldsLocalNamesMap.put(entry.getKey(), entry.getValue()); } } Map<DOMNodeObjectModel, Integer> childrenDOMNodes = new HashMap<>(); for(Map.Entry<DOMNodeObjectModel, Integer> entry : domNodeObjectModel.getChildrenDOMNodes().entrySet()){ if(selectionSet.contains(entry.getKey().getLocalName())) { DOMNodeObjectModel child = entry.getKey().createDOMNodeObjectModelSelectionSet(entry.getKey(), selectionSet); if (child.getChildrenDOMNodes().size() > 0 || child.getFields().size() > 0) { childrenDOMNodes.put(child, entry.getValue()); } } } return new DOMNodeObjectModel(domNodeObjectModel.getNode(), domNodeObjectModel.getLocalName(), domNodeObjectModel.getLocalNamespaceURI(), domNodeObjectModel.getNodeType(), Collections.unmodifiableMap(childrenDOMNodes), Collections.unmodifiableMap(thisFields), Collections.unmodifiableMap(thisFieldsLocalNamesMap)); } /** * A static factory method that will create a DOMNodeObjectModel without the fields that were set to be ignored * @param domNodeObjectModel a DOMNodeObjectModel object to derive the statically constructed model from * @return a DOMNodeObjectModel that excludes the elements indicated in the ignore set. */ private static DOMNodeObjectModel createDOMNodeObjectModelWOFullyQualifiedFields(DOMNodeObjectModel domNodeObjectModel){ Set<Map.Entry<DOMNodeElementTuple, Map<String, Integer>>> entries = domNodeObjectModel.getFields().entrySet(); Iterator<Map.Entry<DOMNodeElementTuple, Map<String, Integer>>> iterator = entries.iterator(); Map<DOMNodeElementTuple, Map<String, Integer>> thisFields = new HashMap<>(); while(iterator.hasNext()){ Map.Entry<DOMNodeElementTuple, Map<String, Integer>> entry = iterator.next(); DOMNodeElementTuple newKey = new DOMNodeElementTuple("", entry.getKey().getLocalName()); thisFields.put(newKey, entry.getValue()); } Map<DOMNodeObjectModel, Integer> childrenDOMNodes = new HashMap<>(); Iterator<Map.Entry<DOMNodeObjectModel, Integer>> childEntriesIterator = domNodeObjectModel.getChildrenDOMNodes().entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<DOMNodeObjectModel, Integer> entry = childEntriesIterator.next(); DOMNodeObjectModel child = DOMNodeObjectModel.createDOMNodeObjectModelWOFullyQualifiedFields(entry.getKey()); childrenDOMNodes.put(child, entry.getValue()); } return new DOMNodeObjectModel(domNodeObjectModel.getNode(), domNodeObjectModel.getLocalName(), domNodeObjectModel.getLocalNamespaceURI(), domNodeObjectModel.getNodeType(), Collections.unmodifiableMap(childrenDOMNodes), Collections.unmodifiableMap(thisFields), Collections.unmodifiableMap(domNodeObjectModel.getFieldsLocalNameMap())); } /** * A stateless method that can find a matching DOMNodeObjectModel given a Reference DOMNodeObjectModel and a list * of DOMNodeObjectModel objects * @param reference a DOMNodeObjectModel whose matching object needs to be found in the list * @param models a list of DOMNodeObjectModel objects exactly one of which should match the reference * @return a DOMNodeObjectModel corresponding to the DOMNodeObjectModel in the list that matches the reference */ @Nullable public static DOMNodeObjectModel getMatchingDOMNodeObjectModel(DOMNodeObjectModel reference, Collection<DOMNodeObjectModel> models){ DOMNodeObjectModel refDOMNodelObjectModelWONamespaceURI = DOMNodeObjectModel.createDOMNodeObjectModelWOFullyQualifiedFields(reference); for(DOMNodeObjectModel model : models){ DOMNodeObjectModel modelWONamespaceURI = DOMNodeObjectModel.createDOMNodeObjectModelWOFullyQualifiedFields(model); if(refDOMNodelObjectModelWONamespaceURI.equals(modelWONamespaceURI)){ return modelWONamespaceURI; } } return null; } /** * A method to log errors related to NamespaceURI inconsistencies for DOMNode elements * @param reference a DOMNodeObjectModel to compare against * @param other a DOMNodeObjectModel object which needs to be compared against the reference * @return a list of errors related to NamespaceURI mismatches between the reference and other DOMNodeObjectModel object */ public static List<ErrorLogger.ErrorObject> getNamespaceURIMismatchErrors(DOMNodeObjectModel reference, DOMNodeObjectModel other){ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); if(reference == null || other == null){ return imfErrorLogger.getErrors(); } Iterator<Map.Entry<String, Map<String, Integer>>> fieldsLocalNamesIterator = reference.getFieldsLocalNameMap().entrySet().iterator(); while(fieldsLocalNamesIterator.hasNext()){ Map.Entry<String, Map<String, Integer>> entry = fieldsLocalNamesIterator.next(); Map<String, Integer> thisFieldsLocalNameValues = entry.getValue(); Map<String, Integer> otherFieldsLocalNameValues = other.getFieldsLocalNameMap().get(entry.getKey()); if(!thisFieldsLocalNameValues.equals(otherFieldsLocalNameValues)){ if(otherFieldsLocalNameValues != null) { Iterator<Map.Entry<String, Integer>> iterator = thisFieldsLocalNameValues.entrySet().iterator(); StringBuilder stringBuilder1 = new StringBuilder(); while(iterator.hasNext()){ Map.Entry<String, Integer> thisEntry = iterator.next(); stringBuilder1.append(String.format("NameSpaceURI %s, %d times", thisEntry.getKey(), thisEntry.getValue())); } Iterator<Map.Entry<String, Integer>> iterator2 = otherFieldsLocalNameValues.entrySet().iterator(); StringBuilder stringBuilder2 = new StringBuilder(); while(iterator2.hasNext()){ Map.Entry<String, Integer> thisEntry = iterator2.next(); stringBuilder2.append(String.format("NameSpaceURI %s, %d times", thisEntry.getKey(), thisEntry.getValue())); } imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The DOMNodeElement represented by the local name %s, has namespace URI inconsistencies " + "in one DOM Node it appears with the %s " + ", in the other DOM Node it appears with the %s" , entry.getKey() , stringBuilder1.toString() , stringBuilder2.toString())); } else{ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("The DOMNodeElement represented by the local name %s, is absent in the other DOMNodeObjectModel", entry.getKey())); } } } Iterator<Map.Entry<DOMNodeObjectModel, Integer>>iterator = reference.getChildrenDOMNodes().entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<DOMNodeObjectModel, Integer>entry = iterator.next(); Set<DOMNodeObjectModel>otherModels = other.getChildrenDOMNodes().keySet(); DOMNodeObjectModel matchingDOMNodeObjectModel = DOMNodeObjectModel.getMatchingDOMNodeObjectModel(entry.getKey(), otherModels); imfErrorLogger.addAllErrors(DOMNodeObjectModel.getNamespaceURIMismatchErrors(entry.getKey(), matchingDOMNodeObjectModel)); } return imfErrorLogger.getErrors(); } /** * A getter for the DOM node represented by this DOMNodeObjectModel * @return a org.w3c.dom node */ public Node getNode(){ return this.node; } /** * A getter for the DOM node type represented by this object model. * @return a short representing the DOM Node type as defined in org.w3c.dom.Node */ public short getNodeType(){ return this.nodeType; } /** * A getter for the DOM Node local name represented by this object model. * @return a string representing the DOM Node's local name field. */ public String getLocalName(){ return this.localName; } /** * A getter for the DOM Node namespace URI represented by this object model. * @return a string representing the DOM Node's namespace URI field. */ public String getLocalNamespaceURI(){ return this.localNamespaceURI; } /** * A getter for the Fields represented in the DOMNodeObjectModel * @return a map of Key, Value pairs corresponding to the fields on the DOM Node */ public Map<DOMNodeElementTuple, Map<String, Integer>> getFields(){ return Collections.unmodifiableMap(this.fields); } /** * A getter for the Fields Local Name Map represented in the DOMNodeObjectModel * @return a map of Key, Value pairs corresponding to the fieldsLocalName and the corresponding NamespaceURIs */ public Map<String, Map<String, Integer>> getFieldsLocalNameMap(){ return Collections.unmodifiableMap(this.fieldsLocalNameMap); } /** * A getter for the Fields represented in the DOMNodeObjectModel * @return a map of Key, Value pairs corresponding to the fields on the DOM Node */ public Map<DOMNodeObjectModel, Integer> getChildrenDOMNodes(){ return Collections.unmodifiableMap(this.childrenDOMNodes); } /** * A getter for the list of errors that occurred while constructing this DOMNodeObjectModel * @return an unmodifiable list of Errors */ public List<ErrorLogger.ErrorObject> getErrors(){ return imfErrorLogger.getErrors(); } /** * A method to compare 2 DOMObjectNodeModel objects to verify if 2 DOM Nodes have the same * content. * @param other the node to compare with. * @return boolean returns true if the 2 DOMNodeObjectModels have the same content. */ @Override public boolean equals(Object other){ if(other == null || this.getClass() != other.getClass()){ return false; } DOMNodeObjectModel otherDOMNodeObjectModel = (DOMNodeObjectModel) other; if(this.nodeType.equals(otherDOMNodeObjectModel.nodeType) && this.fields.equals(otherDOMNodeObjectModel.fields) && this.childrenDOMNodes.equals(otherDOMNodeObjectModel.childrenDOMNodes)) { return true; } return false; } /** * A method to remove nodes from a DOMNodeObjectNodel that are also present in another DOMNodeObjectModel. * @param other DoMNodeObjectModel * @return DOMNodeObjectModel this DOMNodeObjectModel without any common nodes from other DoMNodeObjectModel */ public DOMNodeObjectModel removeNodes(Object other){ if(other == null || this.getClass() != other.getClass()){ return createDOMNodeObjectModelIgnoreSet(this, new HashSet<>()); } DOMNodeObjectModel otherDOMNodeObjectModel = (DOMNodeObjectModel) other; if(!this.localName.equals(otherDOMNodeObjectModel.localName)) { return createDOMNodeObjectModelIgnoreSet(this, new HashSet<>()); } Map<DOMNodeElementTuple, Map<String, Integer>> thisFields = new HashMap<>(); thisFields.putAll(this.fields); thisFields.entrySet().removeAll(otherDOMNodeObjectModel.fields.entrySet()); Map<DOMNodeObjectModel, Integer> thisChildrenDOMNodes = new HashMap<>(); Map<DOMNodeObjectModel, Integer> outChildrenDOMNodes = new HashMap<>(); Map<DOMNodeObjectModel, Integer> otherChildrenDOMNodes = new HashMap<>(); thisChildrenDOMNodes.putAll(this.childrenDOMNodes); thisChildrenDOMNodes.entrySet().removeAll(otherDOMNodeObjectModel.childrenDOMNodes.entrySet()); otherChildrenDOMNodes.putAll(otherDOMNodeObjectModel.childrenDOMNodes); otherChildrenDOMNodes.entrySet().removeAll(this.childrenDOMNodes.entrySet()); while(!thisChildrenDOMNodes.isEmpty()) { Map.Entry<DOMNodeObjectModel, Integer> entry = thisChildrenDOMNodes.entrySet().iterator().next(); Integer minDiffCount = entry.getKey().getFieldCount(); Map.Entry<DOMNodeObjectModel, Integer> matchingEntry = null; for(Map.Entry<DOMNodeObjectModel, Integer> otherEntry: otherChildrenDOMNodes.entrySet()) { DOMNodeObjectModel diffDOMNodeObjectModel = entry.getKey().removeNodes(otherEntry.getKey()); if(diffDOMNodeObjectModel.getFieldCount() < minDiffCount) { matchingEntry = otherEntry; minDiffCount = diffDOMNodeObjectModel.getFieldCount(); } } if(matchingEntry != null) { Integer remaining = entry.getValue() - matchingEntry.getValue(); Integer count = remaining >= 0 ? matchingEntry.getValue() : entry.getValue(); if(remaining == 0) { otherChildrenDOMNodes.remove(matchingEntry.getKey()); thisChildrenDOMNodes.remove(entry.getKey()); } else if(remaining > 0) { otherChildrenDOMNodes.remove(matchingEntry.getKey()); thisChildrenDOMNodes.put(entry.getKey(), remaining); } else { otherChildrenDOMNodes.put(matchingEntry.getKey(), -remaining); thisChildrenDOMNodes.remove(entry.getKey()); } if(!entry.getKey().equals(matchingEntry.getKey())) { DOMNodeObjectModel diffDOMNodeObjectModel = entry.getKey().removeNodes(matchingEntry.getKey()); if(outChildrenDOMNodes.containsKey(diffDOMNodeObjectModel)) { count += outChildrenDOMNodes.get(diffDOMNodeObjectModel); } outChildrenDOMNodes.put(diffDOMNodeObjectModel, count); } } else { Integer count = entry.getValue(); if(outChildrenDOMNodes.containsKey(entry.getKey())) { count += outChildrenDOMNodes.get(entry.getKey()); } outChildrenDOMNodes.put(entry.getKey(), count); thisChildrenDOMNodes.remove(entry.getKey()); } } return new DOMNodeObjectModel(this.getNode(), this.getLocalName(), this.getLocalNamespaceURI(), this.getNodeType(), Collections.unmodifiableMap(outChildrenDOMNodes), Collections.unmodifiableMap (thisFields), Collections.unmodifiableMap(this.fieldsLocalNameMap)); } /** * A method that returns total number of fields in a DOMNodeObjectModel. * @return Integer total number of fields . */ public Integer getFieldCount(){ Integer entryCount = 0; entryCount += this.fields.size(); for(Map.Entry<DOMNodeObjectModel, Integer> entry: this.childrenDOMNodes.entrySet()) { entryCount += entry.getKey().getFieldCount(); } return entryCount; } /** * A Java compliant implementation of the hashCode() method * @return integer containing the hash code corresponding to this object */ @Override public int hashCode(){ int hash = 1; hash = hash * 31 + localName.hashCode(); hash = hash * 31 + this.nodeType.hashCode(); hash = hash * 31 + this.fields.hashCode(); hash = hash * 31 + this.childrenDOMNodes.hashCode(); return hash; } /** * A method that returns a string representation of a DOMNodeObjectModel object * * @return string representing the object */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("<%s xmlns=\"%s\">", this.localName, this.localNamespaceURI)+"\n"); for(Map.Entry<DOMNodeElementTuple, Map<String, Integer>> entry : fields.entrySet()){ Map<String, Integer> values = (Map<String, Integer>)entry.getValue(); Iterator<Map.Entry<String, Integer>> iterator = values.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<String, Integer> fieldValuesEntry = iterator.next(); for(Integer i = 0; i< fieldValuesEntry.getValue(); i++) { sb.append(String.format(" <%s xmlns=\"%s\">%s</%s>%n", entry.getKey().getLocalName(), entry.getKey().getNamespaceURI(), fieldValuesEntry.getKey(), entry.getKey().getLocalName())); } } } for(Map.Entry<DOMNodeObjectModel, Integer> domEntry : this.childrenDOMNodes.entrySet()) { for(Integer i = 0; i < domEntry.getValue(); i++) { String domNodeString = domEntry.getKey().toString(); sb.append(domNodeString.replaceAll("(?m)(^)", " ")); } } sb.append(String.format("</%s>", this.localName) + "\n"); return sb.toString(); } private String readFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String line = null; StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); try { while((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(ls); } return stringBuilder.toString(); } finally { reader.close(); } } /** * A method to obtain DOMNodeObjectModel with given LocalName * @param name the LocalName of the DOMNodeObjectModel * @return Returns DOMNodeObjectModel */ public List<DOMNodeObjectModel> getDOMNodes(String name) { List<DOMNodeObjectModel> domNodeObjectModelList = new ArrayList<>(); this.getChildrenDOMNodes().entrySet() .stream() .filter(e -> e.getKey().getLocalName().equals(name)) .forEach( e -> { for(int i =0; i <e.getValue(); i++) { domNodeObjectModelList.add(e.getKey()); } }); return Collections.unmodifiableList(domNodeObjectModelList); } /** * A method to obtain DOMNodeObjectModel with given LocalName * @param name the LocalName of the DOMNodeObjectModel * @return Returns DOMNodeObjectModel */ public DOMNodeObjectModel getDOMNode(String name) { List<DOMNodeObjectModel> domNodeObjectModelList = getDOMNodes(name); if(domNodeObjectModelList.size() > 0) { return domNodeObjectModelList.get(0); } else return null; } /** * A method to obtain value of a field within DOMNodeObjectModel as a String * @param name the LocalName for the field * @return Returns field value as a String */ @Nullable public String getFieldAsString(String name) { try { Map<String, Integer> map = this.getFields().entrySet().stream().filter(e -> e.getKey().getLocalName().equals(name)).findFirst().get().getValue(); if (map.size() >= 1) { Map.Entry<String, Integer> entry = map.entrySet().iterator().next(); return entry.getKey(); } } catch(Exception e) { return null; } return null; } /** * A method to obtain value of a field within DOMNodeObjectModel as a UL * @param name the LocalName for the field * @return Returns field value as a UL */ @Nullable public UL getFieldAsUL(String name) { String value = getFieldAsString(name); try { if(value != null) return UL.fromULAsURNStringToUL(value); } catch(Exception e) { return null; } return null; } /** * A method to obtain value of a field within DOMNodeObjectModel as a Long * @param name the LocalName for the field * @return Returns field value as a Long */ @Nullable public Long getFieldAsLong(String name) { String value = getFieldAsString(name); try { if(value != null) return Long.valueOf(value); } catch(Exception e) { return null; } return null; } /** * A method to obtain value of a field within DOMNodeObjectModel as an Integer * @param name the LocalName for the field * @return Returns field value as an Integer */ @Nullable public Integer getFieldAsInteger(String name) { String value = getFieldAsString(name); try { if(value != null) return Integer.valueOf(value); } catch(Exception e) { return null; } return null; } /** * A method to obtain value of a field within DOMNodeObjectModel as a Fraction * @param name the LocalName for the field * @return Returns fields value as a Fraction */ @Nullable public Fraction getFieldAsFraction(String name) { String value = getFieldAsString(name); try { if(value != null) return Fraction.valueOf(value); } catch(Exception e) { return null; } return null; } /** * A method to obtain set of String values for a field within DOMNodeObjectModel * @param name the LocalName for the field * @return Returns a set of field values */ @Nullable public Set<String> getFieldsAsStringRecursive(String name) { Set<String> values = new HashSet<>(); getFieldsAsStringRecursive(values, name); return values; } /** * A method to obtain set of String values for a field within DOMNodeObjectModel * @param name the LocalName for the field * @return Returns a set of field values */ @Nullable void getFieldsAsStringRecursive(Set<String> values, String name) { try { Set<String> matchingValues = this.getFields().entrySet().stream().filter(e -> e.getKey().getLocalName().equals(name)).map(Map.Entry::getValue).map(Map::keySet).flatMap(Set::stream).collect(Collectors.toSet()); values.addAll(matchingValues); for(DOMNodeObjectModel domNodeObjectModel: this.getChildrenDOMNodes().keySet()) { domNodeObjectModel.getFieldsAsStringRecursive(values, name); } return; } catch(Exception e) { return; } } /** * A method to obtain set of Ul values for a field within DOMNodeObjectModel * @param name the LocalName for the field * @return Returns set of UL values */ @Nullable public Set<UL> getFieldsAsUL(String name) { Set<String> values = getFieldsAsStringRecursive(name); try { Set<UL> uls = new HashSet<>(); for(String value: values) { uls.add(UL.fromULAsURNStringToUL(value)); } return uls; } catch(Exception e) { return null; } } /** * A method to obtain set of UUID values for a field within DOMNodeObjectModel * @param name the LocalName for the field * @return Returns set of UUID values */ @Nullable public Set<UUID> getFieldsAsUUID(String name) { Set<String> values = getFieldsAsStringRecursive(name); try { Set<UUID> uuids = new HashSet<>(); for(String value: values) { uuids.add(UUIDHelper.fromUUIDAsURNStringToUUID(value)); } return uuids; } catch(Exception e) { return null; } } /** * A thin class modeling a DOM Node Element Key */ public static class DOMNodeElementTuple { private final String localName; private final String namespaceURI; private DOMNodeElementTuple(@Nonnull String namespaceURI, @Nonnull String localName){ this.namespaceURI = namespaceURI; this.localName = localName; } /** * A getter for the local name property of the fully qualified DOMNode element * @return string representing the local name property of a DOMNode element */ public String getLocalName(){ return this.localName; } /** * A getter for the namespaceURI property of the fully qualified DOMNode element * @return string representing the namespaceURI property of a DOMNode element */ public String getNamespaceURI(){ return this.namespaceURI; } /** * Overriding the equals method of Object to provide a specific implementation for this class * @param other the object to compared with * @return a boolean result of the comparison, false if the passed in object is null or not * of DOMNodeElementTuple type, or if the local name and namespaceURI are not equal to this object. */ @Override public boolean equals(Object other){ if(other == null || other.getClass() != this.getClass()){ return false; } DOMNodeElementTuple otherDOMNodeElementTuple = DOMNodeElementTuple.class.cast(other); boolean result = true; result &= this.localName.equals(otherDOMNodeElementTuple.getLocalName()); result &= this.namespaceURI.equals(otherDOMNodeElementTuple.getNamespaceURI()); return result; } /** * A Java compliant implementation of the hashCode() method * @return integer containing the hash code corresponding to this object */ @Override public int hashCode(){ int hash = 1; hash = hash * 31 + this.localName.hashCode(); /*LocalName can be used since it is non-null*/ hash = hash * 31 + this.namespaceURI.hashCode();/*Another field that is indicated to be non-null*/ return hash; } /** * toString() method of DOMNodeElementTuple * @return a string representing the contents of the DOMNodeElementTuple object */ @Override public String toString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("%nLocalName : %s", this.getLocalName())); stringBuilder.append(String.format("%nNamespaceURI : %s", this.getNamespaceURI())); return stringBuilder.toString(); } } }
5,089
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/ByteProvider.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.utils; import java.io.IOException; /** * This interface is the supertype for classes representing an input sequence of bytes */ public interface ByteProvider { /** * Getter for the raw bytes that this ByteProvider encapsulates * * @param totalNumBytesToRead the total num bytes to read * @return byte[] containing next totalNumBytesToRead number of bytes * @throws java.io.IOException the iO exception */ public byte[] getBytes(int totalNumBytesToRead) throws IOException; /** * A method that lets the caller skip bytes in the encapsulated data * * @param totalNumBytesToSkip the total num bytes to skip from the current position * @throws java.io.IOException the iO exception */ public void skipBytes(long totalNumBytesToSkip) throws IOException; }
5,090
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/RepeatableInputStream.java
package com.netflix.imflibrary.utils; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; /** * A class that provides a repeatable input stream functionality inheriting this behavior from its parent the BufferedInputStream. * This class provides a specialized behavior that clients receiving this object's instances cannot close the underlying input * stream by invoking a close(). * */ public final class RepeatableInputStream extends BufferedInputStream { /** * A constructor to create RepeatableInputStream objects * @param inputStream that needs to be wrapped in a RepeatableInputStream object */ public RepeatableInputStream(InputStream inputStream) { super(inputStream); super.mark(Integer.MAX_VALUE); } /** * Overridden method mark(int) * @param readLimit the maximum limit of bytes that can be read before * the mark position becomes invalid. * */ @Override public synchronized void mark(int readLimit) { super.mark(Integer.MAX_VALUE); } /** * Overridden method reset() to reposition the inputstream to the last marked position. * */ @Override public synchronized void reset() throws IOException { super.reset(); } /** * Overridden method close() to close the input stream. This function does nothing * and that is by design in order to prevent methods receiving this object * instance to not be able to close the underlying input stream. * */ @Override public void close() throws IOException { // Do nothing. } /** * Close this input stream explicitly. * @throws IOException - any I/O related error is exposed through an IOException */ public void forceClose() throws IOException { // Actually close. in.close(); } }
5,091
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/Utilities.java
package com.netflix.imflibrary.utils; import java.util.Collection; import java.util.Iterator; /** * A stateless class that provides general utility methods */ public final class Utilities { //To prevent instantiation private Utilities(){ } /** * A method for serializing an Object collection to a String * @param collection - of objects to be serialized to Strings * @return a string representation of each of the objects in the collection */ public static String serializeObjectCollectionToString(Collection<? extends Object> collection){ StringBuilder stringBuilder = new StringBuilder(); Iterator iterator = collection.iterator(); stringBuilder.append(String.format("%n")); while(iterator.hasNext()){ stringBuilder.append(iterator.next().toString()); stringBuilder.append(String.format("%n")); } return stringBuilder.toString(); } /** * A method for serializing a byte[] to a HexString * @param bytes - collection of bytes * @return a String representing the Hexadecimal representation of the bytes in the byte[] */ public static String serializeBytesToHexString(byte[] bytes){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("0x"); for(int i=0; i < bytes.length; i++){ stringBuilder.append(String.format("%02x", bytes[i])); } return stringBuilder.toString(); } public static String getVersionString(Class<?> theClass) { String version = "0.0.0"; if(theClass.getPackage() != null && theClass.getPackage().getImplementationVersion() != null) { return theClass.getPackage().getImplementationVersion(); } return version; } public static String appendPhotonVersionString(String message) { return message + " [Photon version: " + Utilities.getVersionString(Utilities.class) + "]"; } }
5,092
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/ResourceByteRangeProvider.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * This interface is a supertype of classes that represent resources to which byte range requests can be made */ public interface ResourceByteRangeProvider { /** * A method that returns the size in bytes of the underlying resource * @return size of resource in bytes */ long getResourceSize(); /** * A method to obtain bytes in the inclusive range [start, end] as a file * * @param rangeStart zero indexed inclusive start offset; ranges from 0 through (resourceSize -1) both included * @param rangeEnd zero indexed inclusive end offset; ranges from 0 through (resourceSize -1) both included * @param workingDirectory the working directory where the output file is placed * @return file containing desired byte range * @throws IOException - any I/O related error will be exposed through an IOException */ File getByteRange(long rangeStart, long rangeEnd, File workingDirectory) throws IOException; /** * A method to obtain bytes in the inclusive range [start, end] as a byte[] * * @param rangeStart zero indexed inclusive start offset; ranges from 0 through (resourceSize -1) both included * @param rangeEnd zero indexed inclusive end offset; ranges from 0 through (resourceSize -1) both included * @return byte array containing desired byte range * @throws IOException - any I/O related error is exposed through an IOException */ byte[] getByteRangeAsBytes(long rangeStart, long rangeEnd) throws IOException; /** * A method to obtain bytes in the inclusive range [start, end] as a byte[] * * @param rangeStart zero indexed inclusive start offset; ranges from 0 through (resourceSize -1) both included * @param rangeEnd zero indexed inclusive end offset; ranges from 0 through (resourceSize -1) both included * @return inputStream corresponding to the desired byte range * @throws IOException - any I/O related error is exposed through an IOException */ InputStream getByteRangeAsStream(long rangeStart, long rangeEnd) throws IOException; class Utilities { public static void validateRangeRequest(long resourceSize, long rangeStart, long rangeEnd) { if (rangeStart < 0) { throw new IllegalArgumentException(String.format("rangeStart = %d is < 0", rangeStart)); } if (rangeStart > rangeEnd) { throw new IllegalArgumentException(String.format("rangeStart = %d is not <= %d rangeEnd", rangeStart, rangeEnd)); } if (rangeEnd > (resourceSize - 1)) { throw new IllegalArgumentException(String.format("rangeEnd = %d is not <= (resourceSize -1) = %d", rangeEnd, (resourceSize-1))); } } } }
5,093
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/IMFTrackFilePartitionsExtractor.java
package com.netflix.imflibrary.utils; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.RandomIndexPack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; /** * A tool that is capable of extracting partitions present within an IMFTrack file and * represent them in the form of a file with a specific extension, for e.g. ".hdr" for HeaderPartition. */ public class IMFTrackFilePartitionsExtractor { private static final Logger logger = LoggerFactory.getLogger(IMFTrackFilePartitionsExtractor.class); private static File extractHeaderPartition(File input, File workingDirectory) throws IOException { //Code to extract the HeaderPartition and write to a file ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(input); Long archiveFileSize = resourceByteRangeProvider.getResourceSize(); Long randomIndexPackSize; {//logic to provide as an input stream the portion of the archive that contains randomIndexPack size long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; File fileWithRandomIndexPackSize = resourceByteRangeProvider.getByteRange(rangeStart, rangeEnd, workingDirectory); byte[] bytes = Files.readAllBytes(Paths.get(fileWithRandomIndexPackSize.toURI())); randomIndexPackSize = (long)(ByteBuffer.wrap(bytes).getInt()); } RandomIndexPack randomIndexPack; //logic to provide as an input stream the portion of the archive that contains randomIndexPack long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - randomIndexPackSize; if (rangeStart < 0) { throw new MXFException(String.format("randomIndexPackSize = %d obtained from last 4 bytes of the MXF file is larger than archiveFile size = %d, implying that this file does not contain a RandomIndexPack", randomIndexPackSize, archiveFileSize)); } File fileWithRandomIndexPack = resourceByteRangeProvider.getByteRange(rangeStart, rangeEnd, workingDirectory); ByteProvider byteProvider = new FileDataProvider(fileWithRandomIndexPack); randomIndexPack = new RandomIndexPack(byteProvider, rangeStart, randomIndexPackSize); List<Long> partitionByteOffsets = randomIndexPack.getAllPartitionByteOffsets(); File headerPartition = resourceByteRangeProvider.getByteRange(partitionByteOffsets.get(0), partitionByteOffsets.get(1) - 1, workingDirectory); String inputPath = input.getAbsolutePath(); if(!headerPartition.renameTo(new File(inputPath + ".hdr"))){ logger.info(String.format("Couldn't rename the file containing the header partition")); } return headerPartition; } private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage:%n")); sb.append(String.format("%s <inputFilePath> <workingDirectory>%n", IMFTrackFilePartitionsExtractor.class.getName())); return sb.toString(); } public static void main(String[] args)throws IOException { if(args.length < 2){ usage(); System.exit(-1); } File input = new File(args[0]); File workingDirectory = new File(args[1]); File fileWithHeaderPartition = extractHeaderPartition(input, workingDirectory); assert fileWithHeaderPartition.length() > 0; } }
5,094
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/RegXMLLibHelper.java
/* * * * Copyright 2015 Netflix, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.netflix.imflibrary.utils; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.exceptions.IMFException; import com.sandflow.smpte.klv.Group; import com.sandflow.smpte.klv.LocalSet; import com.sandflow.smpte.klv.LocalTagRegister; import com.sandflow.smpte.klv.MemoryTriplet; import com.sandflow.smpte.klv.Triplet; import com.sandflow.smpte.klv.exceptions.KLVException; import com.sandflow.smpte.mxf.PrimerPack; import com.sandflow.smpte.mxf.Set; import com.sandflow.smpte.register.ElementsRegister; import com.sandflow.smpte.register.GroupsRegister; import com.sandflow.smpte.register.TypesRegister; import com.sandflow.smpte.regxml.FragmentBuilder; import com.sandflow.smpte.regxml.dict.DefinitionResolver; import com.sandflow.smpte.regxml.dict.MetaDictionaryCollection; import com.sandflow.smpte.regxml.dict.definitions.Definition; import com.sandflow.smpte.regxml.dict.definitions.EnumerationTypeDefinition; import com.sandflow.smpte.util.AUID; import com.sandflow.smpte.util.UL; import com.sandflow.smpte.util.UUID; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.utils.ByteProvider; import com.sandflow.util.events.Event; import com.sandflow.util.events.EventHandler; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import static com.sandflow.smpte.regxml.dict.importers.RegisterImporter.fromRegister; /** * A utility class that provides the methods to obtain a RegXML representation of a MXF metadata set */ public final class RegXMLLibHelper { private final RegXMLLibDictionary regXMLLibDictionary; private final LocalTagRegister localTagRegister; /** * Constructor for the RegXMLLibHelper * * @param primerPack the Triplet representing the primer pack * @param primerPackByteProvider the data provider for the primer pack * @throws IOException - any I/O related error will be exposed through an IOException */ public RegXMLLibHelper(KLVPacket.Header primerPack, ByteProvider primerPackByteProvider) throws IOException{ try { this.regXMLLibDictionary = new RegXMLLibDictionary(); this.localTagRegister = PrimerPack.createLocalTagRegister(this.getTripletFromKLVHeader(primerPack, primerPackByteProvider)); } catch (Exception e){ throw new IOException(String.format("Unable to load resources corresponding to registers")); } } /** * A utility method that provides an XML Document fragment representing an MXF KLV triplet * @param triplet the KLV triplet that needs to be serialized to an XML document fragment * @param document the XML document that the document fragment is associated with * @param imfErrorLogger Logger for recording any errors * @return An XML DOM DocumentFragment * @throws MXFException if any error occurs while trying to create the document fragment */ public DocumentFragment getDocumentFragment(Triplet triplet, Document document, IMFErrorLogger imfErrorLogger) throws MXFException { try { HashMap<UUID, Set> setResolver = new HashMap<>(); Group group = LocalSet.fromTriplet(triplet, this.localTagRegister); Set set = Set.fromGroup(group); setResolver.put(set.getInstanceID(), set); RegxmlValidationEventHandlerImpl handler = new RegxmlValidationEventHandlerImpl(true); FragmentBuilder fragmentBuilder = new FragmentBuilder(this.regXMLLibDictionary.getMetaDictionaryCollection(), setResolver, null, handler); DocumentFragment documentFragment = fragmentBuilder.fromTriplet(group, document); if (handler.hasErrors()) { handler.getErrors().stream() .map(e -> new ErrorLogger.ErrorObject( IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, e.getValidationEventSeverity(), "Error code : " + e.getCode().name() + " - " + e.getErrorMessage()) ) .forEach(imfErrorLogger::addError); if(imfErrorLogger.hasFatalErrors()) { throw new MXFException(handler.toString(), imfErrorLogger); } } return documentFragment; } catch (FragmentBuilder.RuleException | KLVException e){ throw new MXFException(String.format("Could not generate MXFFragment for the KLV Set")); } } /** * A utility method that provides an XML Document fragment representing an Essence Descriptor in the MXF file * @param essenceDescriptorTriplet - a KLV triplet corresponding to an Essence Descriptor * @param document an XML document * @param subDescriptorTriplets list of triplets corresponding to the subdescriptors referred by the essenceDescriptor * @param imfErrorLogger Logger for recording any errors * @return An XML DOM DocumentFragment * @throws MXFException if any error occurs while trying to create the document fragment */ public DocumentFragment getEssenceDescriptorDocumentFragment(Triplet essenceDescriptorTriplet, List<Triplet> subDescriptorTriplets, Document document, IMFErrorLogger imfErrorLogger) throws MXFException { try { HashMap<UUID, Set> setResolver = new HashMap<>(); Group group = LocalSet.fromTriplet(essenceDescriptorTriplet, this.localTagRegister); Set set = Set.fromGroup(group); setResolver.put(set.getInstanceID(), set); /*Add all the subdescriptors into the setResolver*/ for(Triplet subDescriptorTriplet:subDescriptorTriplets){ Group subDescriptorGroup = LocalSet.fromTriplet(subDescriptorTriplet, this.localTagRegister); Set subDescriptorSet = Set.fromGroup(subDescriptorGroup); setResolver.put(subDescriptorSet.getInstanceID(), subDescriptorSet); } RegxmlValidationEventHandlerImpl handler = new RegxmlValidationEventHandlerImpl(true); FragmentBuilder fragmentBuilder = new FragmentBuilder(this.regXMLLibDictionary.getMetaDictionaryCollection(), setResolver, null, handler); DocumentFragment documentFragment = fragmentBuilder.fromTriplet(group, document); if (handler.hasErrors()) { handler.getErrors().stream() .map(e -> new ErrorLogger.ErrorObject( IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, e.getValidationEventSeverity(), "Error code : " + e.getCode().name() + " - " + e.getErrorMessage()) ) .forEach(imfErrorLogger::addError); if(imfErrorLogger.hasFatalErrors()) { throw new MXFException(handler.toString(), imfErrorLogger); } } return documentFragment; } catch (FragmentBuilder.RuleException | KLVException e){ throw new MXFException(String.format("Could not generate MXFFragment for the KLV Set")); } } /** * A utility method that provides an in-memory triplet representing an MXF KLV packet * @param header - the MXF KLV header corresponding to an MXF KLV packet * @param byteProvider - data provider for the MXF KLV packet * @return A memory triplet representing the MXF KLV packet * @throws IOException - any I/O related error will be exposed through an IOException */ public MemoryTriplet getTripletFromKLVHeader(KLVPacket.Header header, ByteProvider byteProvider) throws IOException { UL key = new UL(byteProvider.getBytes(KLVPacket.KEY_FIELD_SIZE)); KLVPacket.LengthField lengthField = KLVPacket.getLength(byteProvider); if(lengthField.value != header.getVSize()){ throw new MXFException(String.format("KLVPacket length %d read from the bitstream does not match the size of the value %d", lengthField.value, header.getVSize())); } if (header.getVSize() > Integer.MAX_VALUE) { throw new MXFException(String.format("Essence Descriptors that are larger than %d bytes are not supported", Integer.MAX_VALUE)); } byte[] value = byteProvider.getBytes((int) header.getVSize()); return new MemoryTriplet(new AUID(key), value); } /** * A utility method that gets Symbol name provided URN for an element * @param URN - URN of the element * @return Symbol name of the element */ public String getElementSymbolNameFromUL(String URN) { DefinitionResolver definitionResolver = this.regXMLLibDictionary.getMetaDictionaryCollection(); Definition definition = definitionResolver.getDefinition(AUID.fromURN(URN)); return definition.getSymbol(); } /** * A utility method that gets Symbol name provided URN for an element * @param typeURN - URN for the Enumeration type * @param value - String value for the Enumeration * @return Integer value for the Enumeration */ public Integer getEnumerationValueFromUL(String typeURN, String value) { Integer intValue = null; DefinitionResolver definitionResolver = this.regXMLLibDictionary.getMetaDictionaryCollection(); Definition definition = definitionResolver.getDefinition(AUID.fromURN(typeURN)); if (definition instanceof EnumerationTypeDefinition) { EnumerationTypeDefinition enumerationTypeDefinition = EnumerationTypeDefinition.class.cast(definition); intValue = enumerationTypeDefinition.getElements().stream().filter(e -> e.getName().equals(value)).map(e -> e.getValue()).findFirst().get(); } return intValue; } }
5,095
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/FileDataProvider.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.utils; import javax.annotation.concurrent.NotThreadSafe; import java.io.*; /** * This class is an non-thread-safe implementation of {@link com.netflix.imflibrary.utils.ByteProvider}. The underlying input * sequence of bytes is sourced from a file. While this implementation could be enhanced to make it thread-safe, it is * difficult to envision an application scenario where an input stream could be shared meaningfully among multiple callers */ @NotThreadSafe public final class FileDataProvider implements ByteProvider { private final File inputFile; private Long position = 0L; /** * Instantiates a new FileDataProvider object * * @param file the input file */ public FileDataProvider(File file) { this.inputFile = file; } /** * Getter for the raw bytes from the encapsulated resource in this case a file * * @param totalNumBytesToRead the total num bytes to read from current position in the file * @return byte[] containing next totalNumBytesToRead * @throws IOException - any I/O related error will be exposed through an IOException */ public byte[] getBytes(int totalNumBytesToRead) throws IOException { if(totalNumBytesToRead < 0){ throw new IOException(String.format("Cannot read %d bytes, should be non-negative and non-zero", totalNumBytesToRead)); } byte[] bytes = new byte[totalNumBytesToRead]; Integer bytesRead = 0; Integer totalBytesRead = 0; try(BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(this.inputFile))) { skipBytes(inputStream, this.position); //reach current position while (bytesRead != -1 && totalBytesRead < totalNumBytesToRead) { bytesRead = inputStream.read(bytes, totalBytesRead, totalNumBytesToRead - totalBytesRead); if (bytesRead != -1) { totalBytesRead += bytesRead; } } } if(totalBytesRead < totalNumBytesToRead) { throw new IOException(String.format("Could not read %d bytes of data, only read %d bytes of data, possible truncated data", totalNumBytesToRead, totalBytesRead)); } this.position += totalBytesRead; return bytes; } /** * A method that lets the caller skip bytes in the encapsulated resource in this case a file * * @param totalNumBytesToSkip the total num bytes to skip from the current position in the file * @throws IOException - any I/O related error will be exposed through an IOException */ public void skipBytes(long totalNumBytesToSkip) throws IOException { try(BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(this.inputFile))) { skipBytes(inputStream, this.position + totalNumBytesToSkip); this.position += totalNumBytesToSkip; } } private void skipBytes(InputStream inputStream, long totalNumBytesToSkip) throws IOException { long bytesSkipped = 0; long totalBytesSkipped = 0; while ((bytesSkipped != -1) && (totalBytesSkipped < totalNumBytesToSkip)) { bytesSkipped = inputStream.skip(totalNumBytesToSkip - totalBytesSkipped); { totalBytesSkipped += bytesSkipped; } } if(totalBytesSkipped != totalNumBytesToSkip){ throw new IOException(String.format("Could not skip %d bytes of data, possible truncated data", totalNumBytesToSkip)); } } }
5,096
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/ByteArrayDataProvider.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.utils; import javax.annotation.concurrent.NotThreadSafe; import java.io.IOException; import java.util.Arrays; /** * This class is a non-thread-safe implementation of {@link com.netflix.imflibrary.utils.ByteProvider}. The underlying input * sequence of bytes is sourced from an array of bytes. While this implementation could be enhanced to make it thread-safe, it is * difficult to envision an application scenario where an input stream could be shared meaningfully among multiple callers */ @NotThreadSafe public final class ByteArrayDataProvider implements ByteProvider { private final byte[] bytes; private int position = 0; /** * Instantiates a new MXF byte array data provider. * * @param bytes the input stream */ public ByteArrayDataProvider(byte[] bytes) { this.bytes = Arrays.copyOf(bytes, bytes.length); } /** * Getter for the raw bytes from the byte[] that this data provider encapsulates * * @param totalNumBytesToRead the total num bytes to read * @return byte[] containing next totalNumBytesToRead number of bytes * @throws IOException - any I/O related error is exposed through an IOException */ public byte[] getBytes(int totalNumBytesToRead) throws IOException { if ((this.position + totalNumBytesToRead) > bytes.length) { throw new IOException(String.format("Cannot read %d bytes from zero-index position %d as total length = %d", totalNumBytesToRead, this.position, bytes.length)); } this.position += totalNumBytesToRead; return Arrays.copyOfRange(this.bytes, this.position - totalNumBytesToRead, this.position); } /** * A method that lets the caller skip bytes in the encapsulated byte[] * * @param totalNumBytesToSkip the total num bytes to skip from the current position * @throws IOException - any I/O related error is exposed through an IOException */ public void skipBytes(long totalNumBytesToSkip) throws IOException { if ((this.position + totalNumBytesToSkip) > bytes.length) { throw new IOException(String.format("Cannot skip %d bytes from zero-index position %d as total length = %d", totalNumBytesToSkip, this.position, bytes.length)); } this.position += totalNumBytesToSkip; } }
5,097
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/ByteArrayByteRangeProvider.java
package com.netflix.imflibrary.utils; import javax.annotation.concurrent.Immutable; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** This class is an implementation of {@link com.netflix.imflibrary.utils.ResourceByteRangeProvider} - the underlying * resource is a byte[]. Unless the underlying byte[] is changed externally, this can be considered to be an immutable * implementation */ @Immutable public class ByteArrayByteRangeProvider implements ResourceByteRangeProvider { private static final int EOF = -1; private static final int BUFFER_SIZE = 1024; private final byte[] bytes; private final long resourceSize; /** * Constructor for a ByteArrayByteRangeProvider * @param bytes - a byte[] whose data will be read by this data provider */ public ByteArrayByteRangeProvider(byte[] bytes) { this.bytes = Arrays.copyOf(bytes, bytes.length); this.resourceSize = this.bytes.length; } /** * A method that returns the size in bytes of the underlying resource, in this case a File * @return the size in bytes of the underlying resource, in this case a File */ public long getResourceSize() { return this.resourceSize; } /** * A method to obtain bytes in the inclusive range [start, endOfFile] as a file * * @param rangeStart zero indexed inclusive start offset; ranges from 0 through (resourceSize -1) both included * @param workingDirectory the working directory where the output file is placed * @return file containing desired byte range from rangeStart through end of file * @throws IOException - any I/O related error will be exposed through an IOException */ public File getByteRange(long rangeStart, File workingDirectory) throws IOException { return this.getByteRange(rangeStart, this.resourceSize - 1, workingDirectory); } /** * A method to obtain bytes in the inclusive range [start, end] as a file * * @param rangeStart zero indexed inclusive start offset; range from [0, (resourceSize -1)] inclusive * @param rangeEnd zero indexed inclusive end offset; range from [0, (resourceSize -1)] inclusive * @param workingDirectory the working directory where the output file is placed * @return file containing desired byte range * @throws IOException - any I/O related error will be exposed through an IOException */ public File getByteRange(long rangeStart, long rangeEnd, File workingDirectory) throws IOException { //validation of range request guarantees that 0 <= rangeStart <= rangeEnd <= (resourceSize - 1) ResourceByteRangeProvider.Utilities.validateRangeRequest(this.resourceSize, rangeStart, rangeEnd); File rangeFile = new File(workingDirectory, "range"); try(ByteArrayInputStream bis = new ByteArrayInputStream(this.bytes); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(rangeFile))) { long numBytesSkipped = 0; while (numBytesSkipped < rangeStart) { numBytesSkipped += bis.skip(rangeStart - numBytesSkipped); } long totalNumberOfBytesRead = 0; byte[] bytes = new byte[BUFFER_SIZE]; while (totalNumberOfBytesRead < (rangeEnd - rangeStart + 1)) { int numBytesToRead = (int)Math.min(BUFFER_SIZE, rangeEnd - rangeStart + 1 - totalNumberOfBytesRead); int numBytesRead = bis.read(bytes, 0, numBytesToRead); if (numBytesRead == EOF) { throw new EOFException(); } bos.write(bytes, 0, numBytesRead); totalNumberOfBytesRead += numBytesRead; } } return rangeFile; } /** * This method provides a way to obtain a byte range from the resource in-memory. A limitation of this method is * that the total size of the byte range request is capped at 0x7fffffff (the maximum value possible for type int * in java) * * @param rangeStart zero indexed inclusive start offset; ranges from 0 through (resourceSize -1) both included * @param rangeEnd zero indexed inclusive end offset; ranges from 0 through (resourceSize -1) both included * @return byte[] containing desired byte range * @throws IOException - any I/O related error will be exposed through an IOException */ public byte[] getByteRangeAsBytes(long rangeStart, long rangeEnd) throws IOException { //validation of range request guarantees that 0 <= rangeStart <= rangeEnd <= (resourceSize - 1) ResourceByteRangeProvider.Utilities.validateRangeRequest(this.resourceSize, rangeStart, rangeEnd); if((rangeEnd - rangeStart + 1) > Integer.MAX_VALUE){ throw new IOException(String.format("Number of bytes requested = %d is greater than %d", (rangeEnd - rangeStart + 1), Integer.MAX_VALUE)); } int totalNumBytesToRead = (int)(rangeEnd - rangeStart + 1); byte[] bytes = new byte[totalNumBytesToRead]; try(ByteArrayInputStream bis = new ByteArrayInputStream(this.bytes)) { long bytesSkipped = bis.skip(rangeStart); if(bytesSkipped != rangeStart){ throw new IOException(String.format("Could not skip %d bytes of data, possible truncated data", rangeStart)); } int totalNumBytesRead = 0; while (totalNumBytesRead < totalNumBytesToRead) { int numBytesRead; numBytesRead = bis.read(bytes, totalNumBytesRead, totalNumBytesToRead - totalNumBytesRead); if (numBytesRead != -1) { totalNumBytesRead += numBytesRead; } else { throw new EOFException(String.format("Tried to read %d bytes from input stream, which ended after reading %d bytes", totalNumBytesToRead, totalNumBytesRead)); } } } return bytes; } public InputStream getByteRangeAsStream(long rangeStart, long rangeEnd) throws IOException { byte[] bytes = this.getByteRangeAsBytes(rangeStart, rangeEnd); return new ByteArrayInputStream(bytes); } }
5,098
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/RegxmlValidationEventHandlerImpl.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.utils; import com.netflix.imflibrary.IMFErrorLogger; import com.sandflow.util.events.Event; import com.sandflow.util.events.EventHandler; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A thread-safe implementation of the ValidationEventHandler interface for validating an XML serializing operation */ public class RegxmlValidationEventHandlerImpl implements EventHandler { private final boolean continueOnError; private final List<ValidationErrorObject> errors = new ArrayList<>(); /** * A constructor for the ValidationEventHandlerImpl object * @param continueOnError - boolean that determines if XML serializing operation should be persisted in the event of an error */ public RegxmlValidationEventHandlerImpl(boolean continueOnError){ this.continueOnError = continueOnError; } /** * An event handler callback for the XML serializing operation * @param event the XML validation event that needs to be handled * @return boolean to indicate whether to abort/proceed when an error is encountered */ public boolean handle( Event event ){ this.errors.add(new ValidationErrorObject(event.getSeverity(), event.getCode(), event.getMessage())); return this.continueOnError; } /** * Checks if any errors occurred while serializing an XML document * @return boolean to signal if serializing the XML document occurred with/without errors */ public boolean hasErrors(){ return (this.errors.size() > 0); } /** * Checks if any errors occurred while serializing an XML document * @return list of ErrorObjects with errors */ public List<ValidationErrorObject> getErrors(){ return Collections.unmodifiableList(this.errors); } /** * A method that returns a string representation of a ValidationEventHandlerImpl object * @return string representing the object */ public String toString(){ StringBuilder stringBuilder = new StringBuilder(); for(ValidationErrorObject error : errors){ stringBuilder.append(error.toString()); } return stringBuilder.toString(); } /** * A class that represents errors that occur while serializing an XML document */ public static class ValidationErrorObject{ private final Event.Severity validationEventSeverity; private final Enum code; private final String errorMessage; private ValidationErrorObject(Event.Severity validationEventSeverity, Enum code, String errorMessage){ this.validationEventSeverity = validationEventSeverity; this.errorMessage = errorMessage; this.code = code; } /** * A getter for ValidationEvent error severity * @return a translation of the validation event error severity to IMFErrorLogger's ErrorLevel enumeration */ public IMFErrorLogger.IMFErrors.ErrorLevels getValidationEventSeverity(){ switch(this.validationEventSeverity){ case ERROR: return IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL; case FATAL: return IMFErrorLogger.IMFErrors.ErrorLevels.FATAL; case WARN: case INFO: default: return IMFErrorLogger.IMFErrors.ErrorLevels.WARNING; } } /** * A getter for the ValidationError message * @return a string representing the ValidationError message */ public String getErrorMessage(){ return this.errorMessage; } /** * A getter for the ValidationError line number * @return an integer corresponding to the line number where the error occurs */ public Enum getCode() { return this.code;} /** * A toString() method to return the String representation of the ValidationErrorObject * @return a string corresponding to the error message with details on error level, code and line number */ @Override public String toString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("%s - %s - %s", getValidationEventSeverity(), getCode(), getErrorMessage())); return stringBuilder.toString(); } } }
5,099