code
stringlengths
11
173k
docstring
stringlengths
2
593k
func_name
stringlengths
2
189
language
stringclasses
1 value
repo
stringclasses
833 values
path
stringlengths
11
294
url
stringlengths
60
339
license
stringclasses
4 values
public void readString(String timeStamp, int offset) { if (timeStamp == null) { throw new NullPointerException("Image is null"); } if ((offset < 0) || (offset >= timeStamp.length())) { throw new IndexOutOfBoundsException("Offset to timeStamp is out of bounds: offset = " + offset + ", timeStamp.length()" + timeStamp.length()); } timeStamp = timeStamp.substring(offset); if (timeStamp.length() == 7) { minute = Integer.parseInt(timeStamp.substring(1, 3)); second = Integer.parseInt(timeStamp.substring(4, 6)); } else { minute = 0; second = 0; } }
@param timeStamp @param offset @throws NullPointerException @throws IndexOutOfBoundsException
Lyrics3TimeStamp::readString
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/Lyrics3TimeStamp.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/Lyrics3TimeStamp.java
Apache-2.0
public BooleanByte(String identifier, AbstractTagFrameBody frameBody, int bitPosition) { super(identifier, frameBody); if ((bitPosition < 0) || (bitPosition > 7)) { throw new IndexOutOfBoundsException("Bit position needs to be from 0 - 7 : " + bitPosition); } this.bitPosition = bitPosition; }
Creates a new ObjectBooleanByte datatype. @param identifier @param frameBody @param bitPosition @throws IndexOutOfBoundsException
BooleanByte::BooleanByte
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/BooleanByte.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/BooleanByte.java
Apache-2.0
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException { logger.finest("Reading from array from offset:" + offset); //Decode sliced inBuffer ByteBuffer inBuffer; if(TagOptionSingleton.getInstance().isAndroid()) { //#302 [dallen] truncating array manually since the decoder.decode() does not honor the offset in the in buffer byte[] truncArr = new byte[arr.length - offset]; System.arraycopy(arr, offset, truncArr, 0, truncArr.length); inBuffer = ByteBuffer.wrap(truncArr); } else { inBuffer = ByteBuffer.wrap(arr, offset, arr.length - offset).slice(); } CharBuffer outBuffer = CharBuffer.allocate(arr.length - offset); CharsetDecoder decoder = getCorrectDecoder(inBuffer); CoderResult coderResult = decoder.decode(inBuffer, outBuffer, true); if (coderResult.isError()) { logger.warning("Decoding error:" + coderResult); } decoder.flush(outBuffer); outBuffer.flip(); //If using UTF16 with BOM we then search through the text removing any BOMs that could exist //for multiple values, BOM could be Big Endian or Little Endian if (StandardCharsets.UTF_16.equals(getTextEncodingCharSet())) { value = outBuffer.toString().replace("\ufeff","").replace("\ufffe",""); } else { value = outBuffer.toString(); } //SetSize, important this is correct for finding the next datatype setSize(arr.length - offset); logger.finest("Read SizeTerminatedString:" + value + " size:" + size); }
Read a 'n' bytes from buffer into a String where n is the framesize - offset so therefore cannot use this if there are other objects after it because it has no delimiter. Must take into account the text encoding defined in the Encoding Object ID3 Text Frames often allow multiple strings seperated by the null char appropriate for the encoding. @param arr this is the buffer for the frame @param offset this is where to start reading in the buffer for this field @throws NullPointerException @throws IndexOutOfBoundsException
TextEncodedStringSizeTerminated::readByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
protected ByteBuffer writeString( CharsetEncoder encoder, String next, int i, int noOfValues) throws CharacterCodingException { ByteBuffer bb; if(( i + 1) == noOfValues ) { bb = encoder.encode(CharBuffer.wrap(next)); } else { bb = encoder.encode(CharBuffer.wrap(next + '\0')); } bb.rewind(); return bb; }
Write String using specified encoding When this is called multiple times, all but the last value has a trailing null @param encoder @param next @param i @param noOfValues @return @throws CharacterCodingException
TextEncodedStringSizeTerminated::writeString
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
protected ByteBuffer writeStringUTF16LEBOM(final String next, final int i, final int noOfValues) throws CharacterCodingException { final CharsetEncoder encoder = StandardCharsets.UTF_16LE.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); ByteBuffer bb; //Note remember LE BOM is ff fe but this is handled by encoder Unicode char is fe ff if(( i + 1)==noOfValues) { bb = encoder.encode(CharBuffer.wrap('\ufeff' + next )); } else { bb = encoder.encode(CharBuffer.wrap('\ufeff' + next + '\0')); } bb.rewind(); return bb; }
Write String in UTF-LEBOM format When this is called multiple times, all but the last value has a trailing null Remember we are using this charset because the charset that writes BOM does it the wrong way for us so we use this none and then manually add the BOM ourselves. @param next @param i @param noOfValues @return @throws CharacterCodingException
TextEncodedStringSizeTerminated::writeStringUTF16LEBOM
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
protected ByteBuffer writeStringUTF16BEBOM(final String next, final int i, final int noOfValues) throws CharacterCodingException { final CharsetEncoder encoder = StandardCharsets.UTF_16BE.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); ByteBuffer bb; //Add BOM if(( i + 1)==noOfValues) { bb = encoder.encode(CharBuffer.wrap('\ufeff' + next )); } else { bb = encoder.encode(CharBuffer.wrap('\ufeff' + next + '\0')); } bb.rewind(); return bb; }
Write String in UTF-BEBOM format When this is called multiple times, all but the last value has a trailing null @param next @param i @param noOfValues @return @throws CharacterCodingException
TextEncodedStringSizeTerminated::writeStringUTF16BEBOM
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
protected void stripTrailingNull() { if (TagOptionSingleton.getInstance().isRemoveTrailingTerminatorOnWrite()) { String stringValue = (String) value; if (stringValue.length() > 0) { if (stringValue.charAt(stringValue.length() - 1) == '\0') { stringValue = (stringValue).substring(0, stringValue.length() - 1); value = stringValue; } } } }
Removing trailing null from end of String, this should not be there but some applications continue to write this unnecessary null char.
TextEncodedStringSizeTerminated::stripTrailingNull
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
protected void checkTrailingNull( List<String> values, String stringValue) { if(!TagOptionSingleton.getInstance().isRemoveTrailingTerminatorOnWrite()) { if (stringValue.length() > 0 && stringValue.charAt(stringValue.length() - 1) == '\0') { String lastVal = values.get(values.size() - 1); String newLastVal = lastVal + '\0'; values.set(values.size() - 1,newLastVal); } } }
Because nulls are stripped we need to check if not removing trailing nulls whether the original value ended with a null and if so add it back in. @param values @param stringValue
TextEncodedStringSizeTerminated::checkTrailingNull
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
public static List<String> splitByNullSeperator(String value) { String[] valuesarray = value.split("\\u0000"); List<String> values = Arrays.asList(valuesarray); //Read only list so if empty have to create new list if (values.size() == 0) { values = new ArrayList<String>(1); values.add(""); } return values; }
Split the values separated by null character @param value the raw value @return list of values, guaranteed to be at least one value
TextEncodedStringSizeTerminated::splitByNullSeperator
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
public void addValue(String value) { setValue(this.value + "\u0000" + value); }
Add an additional String to the current String value @param value
TextEncodedStringSizeTerminated::addValue
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringSizeTerminated.java
Apache-2.0
public NumberFixedLength(String identifier, AbstractTagFrameBody frameBody, int size) { super(identifier, frameBody); if (size < 0) { throw new IllegalArgumentException("Length is less than zero: " + size); } this.size = size; }
Creates a new ObjectNumberFixedLength datatype. @param identifier @param frameBody @param size the number of significant places that the number is held to @throws IllegalArgumentException
NumberFixedLength::NumberFixedLength
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
Apache-2.0
public void setSize(int size) { if (size > 0) { this.size = size; } }
Set Size in Bytes of this Object @param size in bytes that this number will be held as
NumberFixedLength::setSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
Apache-2.0
public boolean equals(Object obj) { if (!(obj instanceof NumberFixedLength object)) { return false; } return this.size == object.size && super.equals(obj); }
@param obj @return true if obj equivalent to this
NumberFixedLength::equals
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
Apache-2.0
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException { if (arr == null) { throw new NullPointerException("Byte array is null"); } if ((offset < 0) || (offset >= arr.length)) { throw new InvalidDataTypeException("Offset to byte array is out of bounds: offset = " + offset + ", array.length = " + arr.length); } if(offset + size > arr.length) { throw new InvalidDataTypeException("Offset plus size to byte array is out of bounds: offset = " + offset + ", size = "+size +" + arr.length "+ arr.length ); } long lvalue = 0; for (int i = offset; i < (offset + size); i++) { lvalue <<= 8; lvalue += (arr[i] & 0xff); } value = lvalue; logger.config("Read NumberFixedlength:" + value); }
Read the number from the byte array @param arr @param offset @throws NullPointerException @throws IndexOutOfBoundsException
NumberFixedLength::readByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
Apache-2.0
public byte[] writeByteArray() { byte[] arr; arr = new byte[size]; if (value != null) { //Convert value to long long temp = ID3Tags.getWholeNumber(value); for (int i = size - 1; i >= 0; i--) { arr[i] = (byte) (temp & 0xFF); temp >>= 8; } } return arr; }
Write data to byte array @return the datatype converted to a byte array
NumberFixedLength::writeByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/NumberFixedLength.java
Apache-2.0
public Integer getIdForValue(String value) { return valueToId.get(value); }
Get Id for Value @param value @return
AbstractIntStringValuePair::getIdForValue
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractIntStringValuePair.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractIntStringValuePair.java
Apache-2.0
public String getValueForId(int id) { return idToValue.get(id); }
Get value for Id @param id @return
AbstractIntStringValuePair::getValueForId
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractIntStringValuePair.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractIntStringValuePair.java
Apache-2.0
public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody) { super(identifier, frameBody); }
Creates a new TextEncodedStringNullTerminated datatype. @param identifier identifies the frame type @param frameBody
TextEncodedStringNullTerminated::TextEncodedStringNullTerminated
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
Apache-2.0
public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody, String value) { super(identifier, frameBody, value); }
Creates a new TextEncodedStringNullTerminated datatype, with value @param identifier @param frameBody @param value
TextEncodedStringNullTerminated::TextEncodedStringNullTerminated
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
Apache-2.0
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException { if(offset>=arr.length) { throw new InvalidDataTypeException("Unable to find null terminated string"); } int bufferSize; logger.finer("Reading from array starting from offset:" + offset); int size; //Get the Specified Decoder final Charset charset = getTextEncodingCharSet(); //We only want to load up to null terminator, data after this is part of different //field and it may not be possible to decode it so do the check before we do //do the decoding,encoding dependent. ByteBuffer buffer = ByteBuffer.wrap(arr, offset, arr.length - offset); int endPosition = 0; //Latin-1 and UTF-8 strings are terminated by a single-byte null, //while UTF-16 and its variants need two bytes for the null terminator. final boolean nullIsOneByte = StandardCharsets.ISO_8859_1 == charset || StandardCharsets.UTF_8 == charset; boolean isNullTerminatorFound = false; while (buffer.hasRemaining()) { byte nextByte = buffer.get(); if (nextByte == 0x00) { if (nullIsOneByte) { buffer.mark(); buffer.reset(); endPosition = buffer.position() - 1; logger.finest("Null terminator found starting at:" + endPosition); isNullTerminatorFound = true; break; } else { // Looking for two-byte null if (buffer.hasRemaining()) { nextByte = buffer.get(); if (nextByte == 0x00) { buffer.mark(); buffer.reset(); endPosition = buffer.position() - 2; logger.finest("UTF16:Null terminator found starting at:" + endPosition); isNullTerminatorFound = true; break; } else { //Nothing to do, we have checked 2nd value of pair it was not a null terminator //so will just start looking again in next invocation of loop } } else { buffer.mark(); buffer.reset(); endPosition = buffer.position() - 1; logger.warning("UTF16:Should be two null terminator marks but only found one starting at:" + endPosition); isNullTerminatorFound = true; break; } } } else { //If UTF16, we should only be looking on 2 byte boundaries if (!nullIsOneByte) { if (buffer.hasRemaining()) { buffer.get(); } } } } if (!isNullTerminatorFound) { throw new InvalidDataTypeException("Unable to find null terminated string"); } logger.finest("End Position is:" + endPosition + "Offset:" + offset); //Set Size so offset is ready for next field (includes the null terminator) size = endPosition - offset; size++; if (!nullIsOneByte) { size++; } setSize(size); //Decode buffer if runs into problems should throw exception which we //catch and then set value to empty string. (We don't read the null terminator //because we dont want to display this) bufferSize = endPosition - offset; logger.finest("Text size is:" + bufferSize); if (bufferSize == 0) { value = ""; } else { //Decode sliced inBuffer ByteBuffer inBuffer = ByteBuffer.wrap(arr, offset, bufferSize).slice(); CharBuffer outBuffer = CharBuffer.allocate(bufferSize); final CharsetDecoder decoder = getCorrectDecoder(inBuffer); CoderResult coderResult = decoder.decode(inBuffer, outBuffer, true); if (coderResult.isError()) { logger.warning("Problem decoding text encoded null terminated string:" + coderResult); } decoder.flush(outBuffer); outBuffer.flip(); value = outBuffer.toString(); } //Set Size so offset is ready for next field (includes the null terminator) logger.config("Read NullTerminatedString:" + value + " size inc terminator:" + size); }
Read a string from buffer upto null character (if exists) Must take into account the text encoding defined in the Encoding Object ID3 Text Frames often allow multiple strings separated by the null char appropriate for the encoding. @param arr this is the buffer for the frame @param offset this is where to start reading in the buffer for this field
TextEncodedStringNullTerminated::readByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
Apache-2.0
public byte[] writeByteArray() { logger.config("Writing NullTerminatedString." + value); byte[] data; //Write to buffer using the CharSet defined by getTextEncodingCharSet() //Add a null terminator which will be encoded based on encoding. final Charset charset = getTextEncodingCharSet(); try { if (StandardCharsets.UTF_16.equals(charset)) { if(TagOptionSingleton.getInstance().isEncodeUTF16BomAsLittleEndian()) { final CharsetEncoder encoder = StandardCharsets.UTF_16LE.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); //Note remember LE BOM is ff fe but this is handled by encoder Unicode char is fe ff final ByteBuffer bb = encoder.encode(CharBuffer.wrap('\ufeff' + (String) value + '\0')); data = new byte[bb.limit()]; bb.get(data, 0, bb.limit()); } else { final CharsetEncoder encoder = StandardCharsets.UTF_16BE.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); //Note BE BOM will leave as fe ff final ByteBuffer bb = encoder.encode(CharBuffer.wrap('\ufeff' + (String) value + '\0')); data = new byte[bb.limit()]; bb.get(data, 0, bb.limit()); } } else { final CharsetEncoder encoder = charset.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final ByteBuffer bb = encoder.encode(CharBuffer.wrap((String) value + '\0')); data = new byte[bb.limit()]; bb.get(data, 0, bb.limit()); } } //https://bitbucket.org/ijabz/jaudiotagger/issue/1/encoding-metadata-to-utf-16-can-fail-if catch (CharacterCodingException ce) { logger.severe(ce.getMessage()+":"+charset.name()+":"+value); throw new RuntimeException(ce); } setSize(data.length); return data; }
Write String into byte array, adding a null character to the end of the String @return the data as a byte array in format to write to file
TextEncodedStringNullTerminated::writeByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java
Apache-2.0
public List<V> getAlphabeticalValueList() { return valueList; }
Get list in alphabetical order @return
AbstractValuePair::getAlphabeticalValueList
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractValuePair.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractValuePair.java
Apache-2.0
public int getSize() { return valueList.size(); }
@return the number of elements in the mapping
AbstractValuePair::getSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractValuePair.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractValuePair.java
Apache-2.0
protected AbstractDataType(String identifier, AbstractTagFrameBody frameBody) { this.identifier = identifier; this.frameBody = frameBody; }
Construct an abstract datatype identified by identifier and linked to a framebody without setting an initial value. @param identifier to allow retrieval of this datatype by name from framebody @param frameBody that the dataype is associated with
AbstractDataType::AbstractDataType
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
protected AbstractDataType(String identifier, AbstractTagFrameBody frameBody, Object value) { this.identifier = identifier; this.frameBody = frameBody; setValue(value); }
Construct an abstract datatype identified by identifier and linked to a framebody initilised with a value @param identifier to allow retrieval of this datatype by name from framebody @param frameBody that the dataype is associated with @param value of this DataType
AbstractDataType::AbstractDataType
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
public AbstractDataType(AbstractDataType copyObject) { // no copy constructor in super class this.identifier = copyObject.identifier; if (copyObject.value == null) { this.value = null; } else if (copyObject.value instanceof String) { this.value = copyObject.value; } else if (copyObject.value instanceof Boolean) { this.value = copyObject.value; } else if (copyObject.value instanceof Byte) { this.value = copyObject.value; } else if (copyObject.value instanceof Character) { this.value = copyObject.value; } else if (copyObject.value instanceof Double) { this.value = copyObject.value; } else if (copyObject.value instanceof Float) { this.value = copyObject.value; } else if (copyObject.value instanceof Integer) { this.value = copyObject.value; } else if (copyObject.value instanceof Long) { this.value = copyObject.value; } else if (copyObject.value instanceof Short) { this.value = copyObject.value; } else if(copyObject.value instanceof MultipleTextEncodedStringNullTerminated.Values) { this.value = copyObject.value; } else if(copyObject.value instanceof PairedTextEncodedStringNullTerminated.ValuePairs) { this.value = copyObject.value; } else if(copyObject.value instanceof PartOfSet.PartOfSetValue) { this.value = copyObject.value; } else if (copyObject.value instanceof boolean[]) { this.value = ((boolean[]) copyObject.value).clone(); } else if (copyObject.value instanceof byte[]) { this.value = ((byte[]) copyObject.value).clone(); } else if (copyObject.value instanceof char[]) { this.value = ((char[]) copyObject.value).clone(); } else if (copyObject.value instanceof double[]) { this.value = ((double[]) copyObject.value).clone(); } else if (copyObject.value instanceof float[]) { this.value = ((float[]) copyObject.value).clone(); } else if (copyObject.value instanceof int[]) { this.value = ((int[]) copyObject.value).clone(); } else if (copyObject.value instanceof long[]) { this.value = ((long[]) copyObject.value).clone(); } else if (copyObject.value instanceof short[]) { this.value = ((short[]) copyObject.value).clone(); } else if (copyObject.value instanceof Object[]) { this.value = ((Object[]) copyObject.value).clone(); } else if (copyObject.value instanceof ArrayList) { this.value = ((ArrayList) copyObject.value).clone(); } else if (copyObject.value instanceof LinkedList) { this.value = ((LinkedList) copyObject.value).clone(); } else { throw new UnsupportedOperationException("Unable to create copy of class " + copyObject.getClass()); } }
This is used by subclasses, to clone the data within the copyObject TODO:It seems to be missing some of the more complex value types. @param copyObject
AbstractDataType::AbstractDataType
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
public void setBody(AbstractTagFrameBody frameBody) { this.frameBody = frameBody; }
Set the framebody that this datatype is associated with @param frameBody
AbstractDataType::setBody
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
public AbstractTagFrameBody getBody() { return frameBody; }
Get the framebody associated with this datatype @return the framebody that this datatype is associated with
AbstractDataType::getBody
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
public void setValue(Object value) { this.value = value; }
Set the value held by this datatype, this is used typically used when the user wants to modify the value in an existing frame. @param value
AbstractDataType::setValue
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
public Object getValue() { return value; }
Get value held by this Object @return value held by this Object
AbstractDataType::getValue
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
final public void readByteArray(byte[] arr) throws InvalidDataTypeException { readByteArray(arr, 0); }
Simplified wrapper for reading bytes from file into Object. Used for reading Strings, this class should be overridden for non String Objects @param arr @throws org.jaudiotagger.tag.InvalidDataTypeException
AbstractDataType::readByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
public boolean equals(Object obj) { if(this==obj) { return true; } if (!(obj instanceof AbstractDataType object)) { return false; } if (!this.identifier.equals(object.identifier)) { return false; } if ((this.value == null) && (object.value == null)) { return true; } else if ((this.value == null) || (object.value == null)) { return false; } // boolean[] if (this.value instanceof boolean[] && object.value instanceof boolean[]) { return Arrays.equals((boolean[]) this.value, (boolean[]) object.value); // byte[] } else if (this.value instanceof byte[] && object.value instanceof byte[]) { return Arrays.equals((byte[]) this.value, (byte[]) object.value); // char[] } else if (this.value instanceof char[] && object.value instanceof char[]) { return Arrays.equals((char[]) this.value, (char[]) object.value); // double[] } else if (this.value instanceof double[] && object.value instanceof double[]) { return Arrays.equals((double[]) this.value, (double[]) object.value); // float[] } else if (this.value instanceof float[] && object.value instanceof float[]) { return Arrays.equals((float[]) this.value, (float[]) object.value); // int[] } else if (this.value instanceof int[] && object.value instanceof int[]) { return Arrays.equals((int[]) this.value, (int[]) object.value); // long[] } else if (this.value instanceof long[] && object.value instanceof long[]) { return Arrays.equals((long[]) this.value, (long[]) object.value); // Object[] } else if (this.value instanceof Object[] && object.value instanceof Object[]) { return Arrays.equals((Object[]) this.value, (Object[]) object.value); // short[] } else if (this.value instanceof short[] && object.value instanceof short[]) { return Arrays.equals((short[]) this.value, (short[]) object.value); } else return this.value.equals(object.value); }
@param obj @return whether this and obj are deemed equivalent
AbstractDataType::equals
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataType.java
Apache-2.0
protected AbstractDataTypeList(final AbstractDataTypeList<T> copy) { super(copy); }
Copy constructor. By convention, subclasses <em>must</em> implement a constructor, accepting an argument of their own class type and call this constructor for {@link org.jaudiotagger.tag.id3.ID3Tags#copyObject(Object)} to work. A parametrized {@code AbstractDataTypeList} is not sufficient. @param copy instance
AbstractDataTypeList::AbstractDataTypeList
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
Apache-2.0
public int getSize() { int size = 0; for (final T t : getValue()) { size+=t.getSize(); } return size; }
Return the size in byte of this datatype list. @return the size in bytes
AbstractDataTypeList::getSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
Apache-2.0
public void readByteArray(final byte[] buffer, final int offset) throws InvalidDataTypeException { if (buffer == null) { throw new NullPointerException("Byte array is null"); } if (offset < 0) { throw new IndexOutOfBoundsException("Offset to byte array is out of bounds: offset = " + offset + ", array.length = " + buffer.length); } // no events if (offset >= buffer.length) { getValue().clear(); return; } for (int currentOffset = offset; currentOffset<buffer.length;) { final T data = createListElement(); data.readByteArray(buffer, currentOffset); data.setBody(frameBody); getValue().add(data); currentOffset+=data.getSize(); } }
Reads list of {@link EventTimingCode}s from buffer starting at the given offset. @param buffer buffer @param offset initial offset into the buffer @throws NullPointerException @throws IndexOutOfBoundsException
AbstractDataTypeList::readByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
Apache-2.0
public byte[] writeByteArray() { logger.config("Writing DataTypeList " + this.getIdentifier()); final byte[] buffer = new byte[getSize()]; int offset = 0; for (final AbstractDataType data : getValue()) { final byte[] bytes = data.writeByteArray(); System.arraycopy(bytes, 0, buffer, offset, bytes.length); offset+=bytes.length; } return buffer; }
Write contents to a byte array. @return a byte array that that contains the data that should be persisted to file
AbstractDataTypeList::writeByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/AbstractDataTypeList.java
Apache-2.0
public BooleanString(String identifier, AbstractTagFrameBody frameBody) { super(identifier, frameBody); }
Creates a new ObjectBooleanString datatype. @param identifier @param frameBody
BooleanString::BooleanString
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/BooleanString.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/BooleanString.java
Apache-2.0
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException { byte b = arr[offset]; value = b != '0'; }
@param offset @throws NullPointerException @throws IndexOutOfBoundsException
BooleanString::readByteArray
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/tag/datatype/BooleanString.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/tag/datatype/BooleanString.java
Apache-2.0
public boolean accept(File f) { if (f.isHidden() || !f.canRead()) { return false; } if (f.isDirectory()) { return allowDirectories; } String ext = Utils.getExtension(f); try { if (SupportedFileFormat.valueOf(ext.toUpperCase()) != null) { return true; } } catch(IllegalArgumentException iae) { //Not known enum value return false; } return false; }
<p>Check whether the given file meet the required conditions (supported by the library OR directory). The File must also be readable and not hidden. @param f The file to test @return a boolean indicating if the file is accepted or not
AudioFileFilter::accept
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileFilter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileFilter.java
Apache-2.0
public static void delete(AudioFile f) throws CannotReadException, CannotWriteException { getDefaultAudioFileIO().deleteTag(f); }
Delete the tag, if any, contained in the given file. @param f The file where the tag will be deleted @throws org.jaudiotagger.audio.exceptions.CannotWriteException If the file could not be written/accessed, the extension wasn't recognized, or other IO error occurred. @throws org.jaudiotagger.audio.exceptions.CannotReadException
AudioFileIO::delete
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public static AudioFileIO getDefaultAudioFileIO() { if (defaultInstance == null) { defaultInstance = new AudioFileIO(); } return defaultInstance; }
This method returns the default instance for static use.<br> @return The default instance.
AudioFileIO::getDefaultAudioFileIO
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public static AudioFile readAs(File f,String ext) throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException { return getDefaultAudioFileIO().readFileAs(f,ext); }
Read the tag contained in the given file. @param f The file to read. @param ext The extension to be used. @return The AudioFile with the file tag and the file encoding info. @throws org.jaudiotagger.audio.exceptions.CannotReadException If the file could not be read, the extension wasn't recognized, or an IO error occurred during the read. @throws org.jaudiotagger.tag.TagException @throws org.jaudiotagger.audio.exceptions.ReadOnlyFileException @throws java.io.IOException @throws org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
AudioFileIO::readAs
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public static AudioFile readMagic(File f) throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException { return getDefaultAudioFileIO().readFileMagic(f); }
Read the tag contained in the given file. @param f The file to read. @return The AudioFile with the file tag and the file encoding info. @throws org.jaudiotagger.audio.exceptions.CannotReadException If the file could not be read, the extension wasn't recognized, or an IO error occurred during the read. @throws org.jaudiotagger.tag.TagException @throws org.jaudiotagger.audio.exceptions.ReadOnlyFileException @throws java.io.IOException @throws org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
AudioFileIO::readMagic
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public static void write(AudioFile f) throws CannotWriteException { getDefaultAudioFileIO().writeFile(f,null); }
Write the tag contained in the audioFile in the actual file on the disk. @param f The AudioFile to be written @throws NoWritePermissionsException if the file could not be written to due to file permissions @throws CannotWriteException If the file could not be written/accessed, the extension wasn't recognized, or other IO error occurred.
AudioFileIO::write
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public static void writeAs(AudioFile f, String targetPath) throws CannotWriteException { if (targetPath == null || targetPath.isEmpty()) { throw new CannotWriteException("Not a valid target path: " + targetPath); } getDefaultAudioFileIO().writeFile(f,targetPath); }
Write the tag contained in the audioFile in the actual file on the disk. @param f The AudioFile to be written @param targetPath The AudioFile path to which to be written without the extension. Cannot be null @throws NoWritePermissionsException if the file could not be written to due to file permissions @throws CannotWriteException If the file could not be written/accessed, the extension wasn't recognized, or other IO error occurred.
AudioFileIO::writeAs
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public void addAudioFileModificationListener( AudioFileModificationListener listener) { this.modificationHandler.addAudioFileModificationListener(listener); }
Adds an listener for all file formats. @param listener listener
AudioFileIO::addAudioFileModificationListener
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
private void prepareReadersAndWriters() { // Tag Readers readers.put(SupportedFileFormat.OGG.getFilesuffix(), new OggFileReader()); readers.put(SupportedFileFormat.FLAC.getFilesuffix(),new FlacFileReader()); readers.put(SupportedFileFormat.MP3.getFilesuffix(), new MP3FileReader()); readers.put(SupportedFileFormat.MP4.getFilesuffix(), new Mp4FileReader()); readers.put(SupportedFileFormat.M4A.getFilesuffix(), new Mp4FileReader()); readers.put(SupportedFileFormat.M4P.getFilesuffix(), new Mp4FileReader()); readers.put(SupportedFileFormat.M4B.getFilesuffix(), new Mp4FileReader()); readers.put(SupportedFileFormat.WAV.getFilesuffix(), new WavFileReader()); readers.put(SupportedFileFormat.WMA.getFilesuffix(), new AsfFileReader()); readers.put(SupportedFileFormat.AIF.getFilesuffix(), new AiffFileReader()); readers.put(SupportedFileFormat.AIFC.getFilesuffix(), new AiffFileReader()); readers.put(SupportedFileFormat.AIFF.getFilesuffix(), new AiffFileReader()); readers.put(SupportedFileFormat.DSF.getFilesuffix(), new DsfFileReader()); final RealFileReader realReader = new RealFileReader(); readers.put(SupportedFileFormat.RA.getFilesuffix(), realReader); readers.put(SupportedFileFormat.RM.getFilesuffix(), realReader); // Tag Writers writers.put(SupportedFileFormat.OGG.getFilesuffix(), new OggFileWriter()); writers.put(SupportedFileFormat.FLAC.getFilesuffix(), new FlacFileWriter()); writers.put(SupportedFileFormat.MP3.getFilesuffix(), new MP3FileWriter()); writers.put(SupportedFileFormat.MP4.getFilesuffix(), new Mp4FileWriter()); writers.put(SupportedFileFormat.M4A.getFilesuffix(), new Mp4FileWriter()); writers.put(SupportedFileFormat.M4P.getFilesuffix(), new Mp4FileWriter()); writers.put(SupportedFileFormat.M4B.getFilesuffix(), new Mp4FileWriter()); writers.put(SupportedFileFormat.WAV.getFilesuffix(), new WavFileWriter()); writers.put(SupportedFileFormat.WMA.getFilesuffix(), new AsfFileWriter()); writers.put(SupportedFileFormat.AIF.getFilesuffix(), new AiffFileWriter()); writers.put(SupportedFileFormat.AIFC.getFilesuffix(), new AiffFileWriter()); writers.put(SupportedFileFormat.AIFF.getFilesuffix(), new AiffFileWriter()); writers.put(SupportedFileFormat.DSF.getFilesuffix(), new DsfFileWriter()); // Register modificationHandler Iterator<AudioFileWriter> it = writers.values().iterator(); for (AudioFileWriter curr : writers.values()) { curr.setAudioFileModificationListener(this.modificationHandler); } }
Creates the readers and writers.
AudioFileIO::prepareReadersAndWriters
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public void checkFileExists(File file)throws FileNotFoundException { logger.config("Reading file:" + "path" + file.getPath() + ":abs:" + file.getAbsolutePath()); if (!file.exists()) { logger.severe("Unable to find:" + file.getPath()); throw new FileNotFoundException(ErrorMessage.UNABLE_TO_FIND_FILE.getMsg(file.getPath())); } }
Check does file exist @param file @throws java.io.FileNotFoundException
AudioFileIO::checkFileExists
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public void removeAudioFileModificationListener( AudioFileModificationListener listener) { this.modificationHandler.removeAudioFileModificationListener(listener); }
Removes a listener for all file formats. @param listener listener
AudioFileIO::removeAudioFileModificationListener
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public void writeFile(AudioFile f, String targetPath) throws CannotWriteException { String ext = f.getExt(); if (targetPath != null && !targetPath.isEmpty()) { final File destination = new File(targetPath + "." + ext); try { Utils.copyThrowsOnException(f.getFile(), destination); f.setFile(destination); } catch (IOException e) { throw new CannotWriteException("Error While Copying" + e.getMessage()); } } AudioFileWriter afw = writers.get(ext); if (afw == null) { throw new CannotWriteException(ErrorMessage.NO_WRITER_FOR_THIS_FORMAT.getMsg(ext)); } afw.write(f); }
Write the tag contained in the audioFile in the actual file on the disk. @param f The AudioFile to be written @param targetPath a file path, without an extension, which provides a "save as". If null, then normal "save" function @throws NoWritePermissionsException if the file could not be written to due to file permissions @throws CannotWriteException If the file could not be written/accessed, the extension wasn't recognized, or other IO error occurred.
AudioFileIO::writeFile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFileIO.java
Apache-2.0
public AudioFile(File f, AudioHeader audioHeader, Tag tag) { this.file = f; this.audioHeader = audioHeader; this.tag = tag; }
<p>These constructors are used by the different readers, users should not use them, but use the <code>AudioFileIO.read(File)</code> method instead !. <p>Create the AudioFile representing file f, the encoding audio headers and containing the tag @param f The file of the audio file @param audioHeader the encoding audioHeaders over this file @param tag the tag contained in this file or null if no tag exists
AudioFile::AudioFile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public AudioFile(String s, AudioHeader audioHeader, Tag tag) { this.file = new File(s); this.audioHeader = audioHeader; this.tag = tag; }
<p>These constructors are used by the different readers, users should not use them, but use the <code>AudioFileIO.read(File)</code> method instead !. <p>Create the AudioFile representing file denoted by pathnames, the encoding audio Headers and containing the tag @param s The pathname of the audio file @param audioHeader the encoding audioHeaders over this file @param tag the tag contained in this file
AudioFile::AudioFile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public void commit() throws CannotWriteException { AudioFileIO.write(this); }
<p>Write the tag contained in this AudioFile in the actual file on the disk, this is the same as calling the <code>AudioFileIO.write(this)</code> method. @throws NoWritePermissionsException if the file could not be written to due to file permissions @throws CannotWriteException If the file could not be written/accessed, the extension wasn't recognized, or other IO error occured. @see AudioFileIO
AudioFile::commit
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public void delete() throws CannotReadException, CannotWriteException { AudioFileIO.delete(this); }
<p>Delete any tags that exist in the fie , this is the same as calling the <code>AudioFileIO.delete(this)</code> method. @throws CannotWriteException If the file could not be written/accessed, the extension wasn't recognized, or other IO error occured. @see AudioFileIO
AudioFile::delete
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public void setExt(String ext) { this.extension = ext; }
Set the file extension @param ext
AudioFile::setExt
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public String getExt() { return extension; }
Retrieve the file extension @return
AudioFile::getExt
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public void setTag(Tag tag) { this.tag = tag; }
Assign a tag to this audio file @param tag Tag to be assigned
AudioFile::setTag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public AudioHeader getAudioHeader() { return audioHeader; }
Return audio header information @return
AudioFile::getAudioHeader
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public Tag getTag() { return tag; }
<p>Returns the tag contained in this AudioFile, the <code>Tag</code> contains any useful meta-data, like artist, album, title, etc. If the file does not contain any tag the null is returned. Some audio formats do not allow there to be no tag so in this case the reader would return an empty tag whereas for others such as mp3 it is purely optional. @return Returns the tag contained in this AudioFile, or null if no tag exists.
AudioFile::getTag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public String toString() { return "AudioFile " + getFile().getAbsolutePath() + " --------\n" + audioHeader.toString() + "\n" + ((tag == null) ? "" : tag.toString()) + "\n-------------------"; }
<p>Returns a multi-line string with the file path, the encoding audioHeader, and the tag contents. @return A multi-line string with the file path, the encoding audioHeader, and the tag contents. TODO Maybe this can be changed ?
AudioFile::toString
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
protected RandomAccessFile checkFilePermissions(File file, boolean readOnly) throws ReadOnlyFileException, FileNotFoundException, CannotReadException { Path path = file.toPath(); RandomAccessFile newFile; checkFileExists(file); // Unless opened as readonly the file must be writable if (readOnly) { //May not even be readable if(!Files.isReadable(path)) { logger.severe("Unable to read file:" + path); logger.severe(Permissions.displayPermissions(path)); throw new NoReadPermissionsException(ErrorMessage.GENERAL_READ_FAILED_DO_NOT_HAVE_PERMISSION_TO_READ_FILE.getMsg(path)); } newFile = new RandomAccessFile(file, "r"); } else { if (TagOptionSingleton.getInstance().isCheckIsWritable() && !Files.isWritable(path)) { logger.severe(Permissions.displayPermissions(file.toPath())); logger.severe(Permissions.displayPermissions(path)); throw new ReadOnlyFileException(ErrorMessage.NO_PERMISSIONS_TO_WRITE_TO_FILE.getMsg(path)); } newFile = new RandomAccessFile(file, "rw"); } return newFile; }
Checks the file is accessible with the correct permissions, otherwise exception occurs @param file @param readOnly @throws ReadOnlyFileException @throws FileNotFoundException @return
AudioFile::checkFilePermissions
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public String displayStructureAsXML() { return ""; }
Optional debugging method. Must override to do anything interesting. @return Empty string.
AudioFile::displayStructureAsXML
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public String displayStructureAsPlainText() { return ""; }
Optional debugging method. Must override to do anything interesting. @return
AudioFile::displayStructureAsPlainText
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public Tag createDefaultTag() { String extension = getExt(); if(extension == null) { String fileName = file.getName(); extension = fileName.substring(fileName.lastIndexOf('.') + 1); setExt(extension); } if(SupportedFileFormat.FLAC.getFilesuffix().equals(extension)) { return new FlacTag(VorbisCommentTag.createNewTag(), new ArrayList< MetadataBlockDataPicture >()); } else if(SupportedFileFormat.OGG.getFilesuffix().equals(extension)) { return VorbisCommentTag.createNewTag(); } else if(SupportedFileFormat.MP4.getFilesuffix().equals(extension)) { return new Mp4Tag(); } else if(SupportedFileFormat.M4A.getFilesuffix().equals(extension)) { return new Mp4Tag(); } else if(SupportedFileFormat.M4P.getFilesuffix().equals(extension)) { return new Mp4Tag(); } else if(SupportedFileFormat.WMA.getFilesuffix().equals(extension)) { return new AsfTag(); } else if(SupportedFileFormat.WAV.getFilesuffix().equals(extension)) { return new WavTag(TagOptionSingleton.getInstance().getWavOptions()); } else if(SupportedFileFormat.RA.getFilesuffix().equals(extension)) { return new RealTag(); } else if(SupportedFileFormat.RM.getFilesuffix().equals(extension)) { return new RealTag(); } else if(SupportedFileFormat.AIF.getFilesuffix().equals(extension)) { return new AiffTag(); } else if(SupportedFileFormat.AIFC.getFilesuffix().equals(extension)) { return new AiffTag(); } else if(SupportedFileFormat.AIFF.getFilesuffix().equals(extension)) { return new AiffTag(); } else if(SupportedFileFormat.DSF.getFilesuffix().equals(extension)) { return Dsf.createDefaultTag(); } else { throw new RuntimeException("Unable to create default tag for this file format"); } }
Create Default Tag @return
AudioFile::createDefaultTag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public Tag getTagOrCreateDefault() { Tag tag = getTag(); if(tag==null) { return createDefaultTag(); } return tag; }
Get the tag or if the file doesn't have one at all, create a default tag and return @return
AudioFile::getTagOrCreateDefault
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public Tag getTagOrCreateAndSetDefault() { Tag tag = getTagOrCreateDefault(); setTag(tag); return tag; }
Get the tag or if the file doesn't have one at all, create a default tag and set it as the tag of this file @return
AudioFile::getTagOrCreateAndSetDefault
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public Tag getTagAndConvertOrCreateAndSetDefault() { Tag tag = getTagOrCreateDefault(); /* TODO Currently only works for Dsf We need additional check here for Wav and Aif because they wrap the ID3 tag so never return * null for getTag() and the wrapper stores the location of the existing tag, would that be broken if tag set to something else */ if(tag instanceof AbstractID3v2Tag) { Tag convertedTag = convertID3Tag((AbstractID3v2Tag)tag, TagOptionSingleton.getInstance().getID3V2Version()); if(convertedTag!=null) { setTag(convertedTag); } else { setTag(tag); } } else { setTag(tag); } return getTag(); }
Get the tag and convert to the default tag version or if the file doesn't have one at all, create a default tag set as tag for this file Conversions are currently only necessary/available for formats that support ID3 @return
AudioFile::getTagAndConvertOrCreateAndSetDefault
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public static String getBaseFilename(File file) { int index=file.getName().toLowerCase().lastIndexOf("."); if(index>0) { return file.getName().substring(0,index); } return file.getName(); }
@param file @return filename with audioFormat separator stripped off.
AudioFile::getBaseFilename
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
public AbstractID3v2Tag convertID3Tag(AbstractID3v2Tag tag, ID3V2Version id3V2Version) { if(tag instanceof ID3v24Tag) { switch(id3V2Version) { case ID3_V22: return new ID3v22Tag(tag); case ID3_V23: return new ID3v23Tag(tag); case ID3_V24: return null; } } else if(tag instanceof ID3v23Tag) { switch(id3V2Version) { case ID3_V22: return new ID3v22Tag(tag); case ID3_V23: return null; case ID3_V24: return new ID3v24Tag(tag); } } else if(tag instanceof ID3v22Tag) { switch(id3V2Version) { case ID3_V22: return null; case ID3_V23: return new ID3v23Tag(tag); case ID3_V24: return new ID3v24Tag(tag); } } return null; }
If using ID3 format convert tag from current version to another as specified by id3V2Version, @return null if no conversion necessary
AudioFile::convertID3Tag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/AudioFile.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/AudioFile.java
Apache-2.0
SupportedFileFormat(String filesuffix) { this.filesuffix = filesuffix; }
Constructor for internal use by this enum.
SupportedFileFormat::SupportedFileFormat
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/SupportedFileFormat.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/SupportedFileFormat.java
Apache-2.0
public String getFilesuffix() { return filesuffix; }
Returns the file suffix (lower case without initial .) associated with the format.
SupportedFileFormat::getFilesuffix
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/SupportedFileFormat.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/SupportedFileFormat.java
Apache-2.0
public Mp4AtomTree(RandomAccessFile raf) throws IOException, CannotReadException { buildTree(raf, true); }
Create Atom Tree @param raf @throws IOException @throws CannotReadException
Mp4AtomTree::Mp4AtomTree
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
Apache-2.0
public Mp4AtomTree(RandomAccessFile raf, boolean closeOnExit) throws IOException, CannotReadException { buildTree(raf, closeOnExit); }
Create Atom Tree and maintain open channel to raf, should only be used if will continue to use raf after this call, you will have to close raf yourself. @param raf @param closeOnExit to keep randomfileaccess open, only used when randomaccessfile already being used @throws IOException @throws CannotReadException
Mp4AtomTree::Mp4AtomTree
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
Apache-2.0
public DefaultTreeModel buildTree(RandomAccessFile raf, boolean closeExit) throws IOException, CannotReadException { FileChannel fc = null; try { fc = raf.getChannel(); //make sure at start of file fc.position(0); //Build up map of nodes rootNode = new DefaultMutableTreeNode(); dataTree = new DefaultTreeModel(rootNode); //Iterate though all the top level Nodes ByteBuffer headerBuffer = ByteBuffer.allocate(Mp4BoxHeader.HEADER_LENGTH); while (fc.position() < fc.size()) { Mp4BoxHeader boxHeader = new Mp4BoxHeader(); headerBuffer.clear(); fc.read(headerBuffer); headerBuffer.rewind(); try { boxHeader.update(headerBuffer); } catch(NullBoxIdException ne) { //If we only get this error after all the expected data has been found we allow it if(moovNode!=null&mdatNode!=null) { NullPadding np = new NullPadding(fc.position() - Mp4BoxHeader.HEADER_LENGTH,fc.size()); DefaultMutableTreeNode trailingPaddingNode = new DefaultMutableTreeNode(np); rootNode.add(trailingPaddingNode); logger.warning(ErrorMessage.NULL_PADDING_FOUND_AT_END_OF_MP4.getMsg(np.getFilePos())); break; } else { //File appears invalid throw ne; } } boxHeader.setFilePos(fc.position() - Mp4BoxHeader.HEADER_LENGTH); DefaultMutableTreeNode newAtom = new DefaultMutableTreeNode(boxHeader); //Go down moov if (boxHeader.getId().equals(Mp4AtomIdentifier.MOOV.getFieldName())) { //A second Moov atom, this is illegal but may just be mess at the end of the file so ignore //and finish if(moovNode!=null&mdatNode!=null) { logger.warning(ErrorMessage.ADDITIONAL_MOOV_ATOM_AT_END_OF_MP4.getMsg(fc.position() - Mp4BoxHeader.HEADER_LENGTH)); break; } moovNode = newAtom; moovHeader = boxHeader; long filePosStart = fc.position(); moovBuffer = ByteBuffer.allocate(boxHeader.getDataLength()); int bytesRead = fc.read(moovBuffer); //If Moov atom is incomplete we are not going to be able to read this file properly if(bytesRead < boxHeader.getDataLength()) { String msg = ErrorMessage.ATOM_LENGTH_LARGER_THAN_DATA.getMsg(boxHeader.getId(), boxHeader.getDataLength(),bytesRead); throw new CannotReadException(msg); } moovBuffer.rewind(); buildChildrenOfNode(moovBuffer, newAtom); fc.position(filePosStart); } else if (boxHeader.getId().equals(Mp4AtomIdentifier.FREE.getFieldName())) { //Might be multiple in different locations freeNodes.add(newAtom); } else if (boxHeader.getId().equals(Mp4AtomIdentifier.MDAT.getFieldName())) { //mdatNode always points to the last mDatNode, normally there is just one mdatnode but do have //a valid example of multiple mdatnode //if(mdatNode!=null) //{ // throw new CannotReadException(ErrorMessage.MP4_FILE_CONTAINS_MULTIPLE_DATA_ATOMS.getMsg()); //} mdatNode = newAtom; mdatNodes.add(newAtom); } rootNode.add(newAtom); fc.position(fc.position() + boxHeader.getDataLength()); } return dataTree; } finally { //If we cant find the audio then we cannot modify this file so better to throw exception //now rather than later when try and write to it. if(mdatNode==null) { throw new CannotReadException(ErrorMessage.MP4_CANNOT_FIND_AUDIO.getMsg()); } if (closeExit) { fc.close(); } } }
Build a tree of the atoms in the file @param raf @param closeExit false to keep randomfileacces open, only used when randomaccessfile already being used @return @throws java.io.IOException @throws org.jaudiotagger.audio.exceptions.CannotReadException
Mp4AtomTree::buildTree
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
Apache-2.0
public void buildChildrenOfNode(ByteBuffer moovBuffer, DefaultMutableTreeNode parentNode) throws IOException, CannotReadException { Mp4BoxHeader boxHeader; //Preprocessing for nodes that contain data before their children atoms Mp4BoxHeader parentBoxHeader = (Mp4BoxHeader) parentNode.getUserObject(); //We set the buffers position back to this after processing the children int justAfterHeaderPos = moovBuffer.position(); //Preprocessing for meta that normally contains 4 data bytes, but doesn't where found under track or tags atom if (parentBoxHeader.getId().equals(Mp4AtomIdentifier.META.getFieldName())) { Mp4MetaBox meta = new Mp4MetaBox(parentBoxHeader, moovBuffer); meta.processData(); try { boxHeader = new Mp4BoxHeader(moovBuffer); } catch(NullBoxIdException nbe) { //It might be that the meta box didn't actually have any additional data after it so we adjust the buffer //to be immediately after metabox and code can retry moovBuffer.position(moovBuffer.position()-Mp4MetaBox.FLAGS_LENGTH); } finally { //Skip back last header cos this was only a test moovBuffer.position(moovBuffer.position()- Mp4BoxHeader.HEADER_LENGTH); } } //Defines where to start looking for the first child node int startPos = moovBuffer.position(); while (moovBuffer.position() < ((startPos + parentBoxHeader.getDataLength()) - Mp4BoxHeader.HEADER_LENGTH)) { boxHeader = new Mp4BoxHeader(moovBuffer); if (boxHeader != null) { boxHeader.setFilePos(moovHeader.getFilePos() + moovBuffer.position()); logger.finest("Atom " + boxHeader.getId() + " @ " + boxHeader.getFilePos() + " of size:" + boxHeader.getLength() + " ,ends @ " + (boxHeader.getFilePos() + boxHeader.getLength())); DefaultMutableTreeNode newAtom = new DefaultMutableTreeNode(boxHeader); parentNode.add(newAtom); if (boxHeader.getId().equals(Mp4AtomIdentifier.UDTA.getFieldName())) { udtaNode = newAtom; } //only interested in metaNode that is child of udta node else if (boxHeader.getId().equals(Mp4AtomIdentifier.META.getFieldName())&&parentBoxHeader.getId().equals(Mp4AtomIdentifier.UDTA.getFieldName())) { metaNode = newAtom; } else if (boxHeader.getId().equals(Mp4AtomIdentifier.HDLR.getFieldName())&&parentBoxHeader.getId().equals(Mp4AtomIdentifier.META.getFieldName())) { hdlrWithinMetaNode = newAtom; } else if (boxHeader.getId().equals(Mp4AtomIdentifier.HDLR.getFieldName())) { hdlrWithinMdiaNode = newAtom; } else if (boxHeader.getId().equals(Mp4AtomIdentifier.TAGS.getFieldName())) { tagsNode = newAtom; } else if (boxHeader.getId().equals(Mp4AtomIdentifier.STCO.getFieldName())) { stcos.add(new Mp4StcoBox(boxHeader, moovBuffer)); stcoNodes.add(newAtom); } else if (boxHeader.getId().equals(Mp4AtomIdentifier.ILST.getFieldName())) { DefaultMutableTreeNode parent = (DefaultMutableTreeNode)parentNode.getParent(); if(parent!=null) { Mp4BoxHeader parentsParent = (Mp4BoxHeader)(parent).getUserObject(); if(parentsParent!=null) { if(parentBoxHeader.getId().equals(Mp4AtomIdentifier.META.getFieldName())&&parentsParent.getId().equals(Mp4AtomIdentifier.UDTA.getFieldName())) { ilstNode = newAtom; } } } } else if (boxHeader.getId().equals(Mp4AtomIdentifier.FREE.getFieldName())) { //Might be multiple in different locations freeNodes.add(newAtom); } else if (boxHeader.getId().equals(Mp4AtomIdentifier.TRAK.getFieldName())) { //Might be multiple in different locations, although only one should be audio track trakNodes.add(newAtom); } //For these atoms iterate down to build their children if ((boxHeader.getId().equals(Mp4AtomIdentifier.TRAK.getFieldName())) || (boxHeader.getId().equals(Mp4AtomIdentifier.MDIA.getFieldName())) || (boxHeader.getId().equals(Mp4AtomIdentifier.MINF.getFieldName())) || (boxHeader.getId().equals(Mp4AtomIdentifier.STBL.getFieldName())) || (boxHeader.getId().equals(Mp4AtomIdentifier.UDTA.getFieldName())) || (boxHeader.getId().equals(Mp4AtomIdentifier.META.getFieldName())) || (boxHeader.getId().equals(Mp4AtomIdentifier.ILST.getFieldName()))) { buildChildrenOfNode(moovBuffer, newAtom); } //Now adjust buffer for the next atom header at this level moovBuffer.position(moovBuffer.position() + boxHeader.getDataLength()); } } moovBuffer.position(justAfterHeaderPos); }
@param moovBuffer @param parentNode @throws IOException @throws CannotReadException
Mp4AtomTree::buildChildrenOfNode
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
Apache-2.0
public Mp4BoxHeader getBoxHeader(DefaultMutableTreeNode node) { if (node == null) { return null; } return (Mp4BoxHeader) node.getUserObject(); }
@param node @return
Mp4AtomTree::getBoxHeader
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AtomTree.java
Apache-2.0
private void writeMetadataSameSize(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader ilstHeader, ByteBuffer newIlstData, Mp4BoxHeader tagsHeader) throws CannotWriteException, IOException { logger.config("Writing:Option 1:Same Size"); fileReadChannel.position(0); fileWriteChannel.transferFrom(fileReadChannel, 0, ilstHeader.getFilePos()); fileWriteChannel.position(ilstHeader.getFilePos()); fileWriteChannel.write(newIlstData); fileReadChannel.position(ilstHeader.getFileEndPos()); writeDataAfterIlst(fileReadChannel, fileWriteChannel, tagsHeader); }
Replace the {@code ilst} metadata. <p/> Because it is the same size as the original data nothing else has to be modified. @param fileReadChannel @param fileWriteChannel @param newIlstData @throws CannotWriteException @throws IOException
Mp4TagWriter::writeMetadataSameSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeNeroData(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader tagsHeader) throws IOException, CannotWriteException { //Write from after ilst upto tags atom long writeBetweenIlstAndTags = tagsHeader.getFilePos() - fileReadChannel.position(); fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), writeBetweenIlstAndTags); fileWriteChannel.position(fileWriteChannel.position() + writeBetweenIlstAndTags); //Replace tags atom (and children) by a free atom convertandWriteTagsAtomToFreeAtom(fileWriteChannel, tagsHeader); //Write after tags atom fileReadChannel.position(tagsHeader.getFileEndPos()); writeDataInChunks(fileReadChannel, fileWriteChannel); }
If the existing files contains a tags atom and chp1 atom underneath the meta atom that means the file was encoded by Nero. Applications such as foobar read this non-standard tag before the more usual data within {@code ilst} causing problems. So the solution is to convert the tags atom and its children into a free atom whilst leaving the chp1 atom alone. @param fileReadChannel @param fileWriteChannel @param tagsHeader @throws IOException
Mp4TagWriter::writeNeroData
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void adjustSizeOfMoovHeader(Mp4BoxHeader moovHeader, ByteBuffer moovBuffer, int sizeAdjustment, Mp4BoxHeader udtaHeader, Mp4BoxHeader metaHeader) throws IOException { //Adjust moov header size, adjusts the underlying buffer moovHeader.setLength(moovHeader.getLength() + sizeAdjustment); //Edit the fields in moovBuffer (note moovbuffer doesnt include header) if (udtaHeader != null) { //Write the updated udta atom header to moov buffer udtaHeader.setLength(udtaHeader.getLength() + sizeAdjustment); moovBuffer.position((int) (udtaHeader.getFilePos() - moovHeader.getFilePos() - Mp4BoxHeader.HEADER_LENGTH)); moovBuffer.put(udtaHeader.getHeaderData()); } if (metaHeader != null) { //Write the updated udta atom header to moov buffer metaHeader.setLength(metaHeader.getLength() + sizeAdjustment); moovBuffer.position((int) (metaHeader.getFilePos() - moovHeader.getFilePos() - Mp4BoxHeader.HEADER_LENGTH)); moovBuffer.put(metaHeader.getHeaderData()); } }
When the size of the metadata has changed and it can't be compensated for by {@code free} atom we have to adjust the size of the size field up to the moovheader level for the {@code udta} atom and its child {@code meta} atom. @param moovHeader @param moovBuffer @param sizeAdjustment can be negative or positive * @param udtaHeader @param metaHeader @return @throws java.io.IOException
Mp4TagWriter::adjustSizeOfMoovHeader
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeOldMetadataLargerThanNewMetadata(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader moovHeader, Mp4BoxHeader udtaHeader, Mp4BoxHeader metaHeader, Mp4BoxHeader ilstHeader, Mp4BoxHeader mdatHeader, Mp4BoxHeader neroTagsHeader, ByteBuffer moovBuffer, ByteBuffer newIlstData, List<Mp4StcoBox> stcos, int sizeOfExistingMetaLevelFreeAtom) throws IOException, CannotWriteException { logger.config("Writing:Option 1:Smaller Size"); int ilstPositionRelativeToAfterMoovHeader = (int) (ilstHeader.getFilePos() - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH)); //Create an amended freeBaos atom and write it if it previously existed as a free atom immediately //after ilst as a child of meta int sizeRequiredByNewIlstAtom = newIlstData.limit(); if (sizeOfExistingMetaLevelFreeAtom > 0) { logger.config("Writing:Option 2:Smaller Size have free atom:" + ilstHeader.getLength() + ":" + sizeRequiredByNewIlstAtom); writeDataUptoIncludingIlst(fileReadChannel, fileWriteChannel, ilstHeader, newIlstData); //Write the modified free atom that comes after ilst int newFreeSize = sizeOfExistingMetaLevelFreeAtom + (ilstHeader.getLength() - sizeRequiredByNewIlstAtom); Mp4FreeBox newFreeBox = new Mp4FreeBox(newFreeSize - Mp4BoxHeader.HEADER_LENGTH); fileWriteChannel.write(newFreeBox.getHeader().getHeaderData()); fileWriteChannel.write(newFreeBox.getData()); //Skip over the read channel old free atom fileReadChannel.position(fileReadChannel.position() + sizeOfExistingMetaLevelFreeAtom); writeDataAfterIlst(fileReadChannel, fileWriteChannel, neroTagsHeader); } //No free atom we need to create a new one or adjust top level free atom else { int newFreeSize = (ilstHeader.getLength() - sizeRequiredByNewIlstAtom) - Mp4BoxHeader.HEADER_LENGTH; //We need to create a new one, so dont have to adjust all the headers but only works if the size //of tags has decreased by more 8 characters so there is enough room for the free boxes header we take //into account size of new header in calculating size of box if (newFreeSize > 0) { logger.config("Writing:Option 3:Smaller Size can create free atom"); writeDataUptoIncludingIlst(fileReadChannel, fileWriteChannel, ilstHeader, newIlstData); //Create new free box Mp4FreeBox newFreeBox = new Mp4FreeBox(newFreeSize); fileWriteChannel.write(newFreeBox.getHeader().getHeaderData()); fileWriteChannel.write(newFreeBox.getData()); writeDataAfterIlst(fileReadChannel, fileWriteChannel, neroTagsHeader); } //Ok everything in this bit of tree has to be recalculated because eight or less bytes smaller else { logger.config("Writing:Option 4:Smaller Size <=8 cannot create free atoms"); //Size will be this amount smaller int sizeReducedBy = ilstHeader.getLength() - sizeRequiredByNewIlstAtom; //Write stuff before Moov (ftyp) fileReadChannel.position(0); fileWriteChannel.transferFrom(fileReadChannel, 0, moovHeader.getFilePos()); fileWriteChannel.position(moovHeader.getFilePos()); //Edit stcos atoms within moov header, we need to adjust offsets by the amount mdat is going to be shifted //unless mdat is at start of file if (mdatHeader.getFilePos() > moovHeader.getFilePos()) { for (final Mp4StcoBox stoc : stcos) { stoc.adjustOffsets(-sizeReducedBy); } } //Edit and rewrite the moov, udta and meta header in moov buffer adjustSizeOfMoovHeader(moovHeader, moovBuffer, -sizeReducedBy, udtaHeader, metaHeader); fileWriteChannel.write(moovHeader.getHeaderData()); moovBuffer.rewind(); moovBuffer.limit(ilstPositionRelativeToAfterMoovHeader); fileWriteChannel.write(moovBuffer); //Write ilst data fileWriteChannel.write(newIlstData); //Write rest of moov, as we may have adjusted stcos atoms that occur after ilst moovBuffer.limit(moovBuffer.capacity()); moovBuffer.position(ilstPositionRelativeToAfterMoovHeader + ilstHeader.getLength()); fileWriteChannel.write(moovBuffer); //Write the rest after moov fileReadChannel.position(moovHeader.getFileEndPos() + sizeReducedBy); writeDataAfterIlst(fileReadChannel, fileWriteChannel, neroTagsHeader); } } }
Existing metadata larger than new metadata, so we can just add a free atom. @param fileReadChannel @param fileWriteChannel @param moovHeader @param udtaHeader @param metaHeader @param ilstHeader @param mdatHeader @param neroTagsHeader @param moovBuffer @param newIlstData @param stcos @param sizeOfExistingMetaLevelFreeAtom @throws IOException @throws CannotWriteException
Mp4TagWriter::writeOldMetadataLargerThanNewMetadata
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeNewMetadataLargerButCanUseFreeAtom(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader ilstHeader, Mp4BoxHeader neroTagsHeader, int sizeOfExistingMetaLevelFreeAtom, ByteBuffer newIlstData, int additionalSpaceRequiredForMetadata) throws IOException, CannotWriteException { int newFreeSize = sizeOfExistingMetaLevelFreeAtom - (additionalSpaceRequiredForMetadata); logger.config("Writing:Option 5;Larger Size can use meta free atom need extra:" + newFreeSize + "bytes"); writeDataUptoIncludingIlst(fileReadChannel, fileWriteChannel, ilstHeader, newIlstData); //Create an amended smaller freeBaos atom and write it to file Mp4FreeBox newFreeBox = new Mp4FreeBox(newFreeSize - Mp4BoxHeader.HEADER_LENGTH); fileWriteChannel.write(newFreeBox.getHeader().getHeaderData()); fileWriteChannel.write(newFreeBox.getData()); //Skip over the read channel old free atom fileReadChannel.position(fileReadChannel.position() + sizeOfExistingMetaLevelFreeAtom); writeDataAfterIlst(fileReadChannel, fileWriteChannel, neroTagsHeader); }
We can fit the metadata in under the meta item just by using some of the padding available in the {@code free} atom under the {@code meta} atom need to take of the side of free header otherwise might end up with solution where can fit in data, but can't fit in free atom header. @param fileReadChannel @param fileWriteChannel @param neroTagsHeader @param sizeOfExistingMetaLevelFreeAtom @param newIlstData @param additionalSpaceRequiredForMetadata @throws IOException @throws CannotWriteException
Mp4TagWriter::writeNewMetadataLargerButCanUseFreeAtom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
public void write(Tag tag, RandomAccessFile raf, RandomAccessFile rafTemp) throws CannotWriteException, IOException { logger.config("Started writing tag data"); FileChannel fileReadChannel = raf.getChannel(); FileChannel fileWriteChannel = rafTemp.getChannel(); int sizeOfExistingIlstAtom = 0; int sizeRequiredByNewIlstAtom; int positionOfNewIlstAtomRelativeToMoovAtom; int positionInExistingFileOfWhereNewIlstAtomShouldBeWritten; int sizeOfExistingMetaLevelFreeAtom; int positionOfTopLevelFreeAtom; int sizeOfExistingTopLevelFreeAtom; long endOfMoov = 0; //Found top level free atom that comes after moov and before mdat, (also true if no free atom ?) boolean topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata; Mp4BoxHeader topLevelFreeHeader; Mp4AtomTree atomTree; //Build AtomTree try { atomTree = new Mp4AtomTree(raf, false); } catch (CannotReadException cre) { throw new CannotWriteException(cre.getMessage()); } Mp4BoxHeader mdatHeader = atomTree.getBoxHeader(atomTree.getMdatNode()); //Unable to find audio so no chance of saving any changes if (mdatHeader == null) { throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_CANNOT_FIND_AUDIO.getMsg()); } //Go through every field constructing the data that will appear starting from ilst box ByteBuffer newIlstData = tc.convert(tag); newIlstData.rewind(); sizeRequiredByNewIlstAtom = newIlstData.limit(); //Moov Box header Mp4BoxHeader moovHeader = atomTree.getBoxHeader(atomTree.getMoovNode()); List<Mp4StcoBox> stcos = atomTree.getStcos(); Mp4BoxHeader ilstHeader = atomTree.getBoxHeader(atomTree.getIlstNode()); Mp4BoxHeader udtaHeader = atomTree.getBoxHeader(atomTree.getUdtaNode()); Mp4BoxHeader metaHeader = atomTree.getBoxHeader(atomTree.getMetaNode()); Mp4BoxHeader hdlrMetaHeader = atomTree.getBoxHeader(atomTree.getHdlrWithinMetaNode()); Mp4BoxHeader neroTagsHeader = atomTree.getBoxHeader(atomTree.getTagsNode()); Mp4BoxHeader trakHeader = atomTree.getBoxHeader(atomTree.getTrakNodes().get(atomTree.getTrakNodes().size()-1)); ByteBuffer moovBuffer = atomTree.getMoovBuffer(); //Work out if we/what kind of metadata hierarchy we currently have in the file //Udta if (udtaHeader != null) { //Meta if (metaHeader != null) { //ilst - record where ilst is,and where it ends if (ilstHeader != null) { sizeOfExistingIlstAtom = ilstHeader.getLength(); //Relative means relative to moov buffer after moov header positionInExistingFileOfWhereNewIlstAtomShouldBeWritten = (int) ilstHeader.getFilePos(); positionOfNewIlstAtomRelativeToMoovAtom = (int) (positionInExistingFileOfWhereNewIlstAtomShouldBeWritten - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH)); } else { //Place ilst immediately after existing hdlr atom if (hdlrMetaHeader != null) { positionInExistingFileOfWhereNewIlstAtomShouldBeWritten = (int) hdlrMetaHeader.getFileEndPos(); positionOfNewIlstAtomRelativeToMoovAtom = (int) (positionInExistingFileOfWhereNewIlstAtomShouldBeWritten - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH)); } //Place ilst after data fields in meta atom //TODO Should we create a hdlr atom else { positionInExistingFileOfWhereNewIlstAtomShouldBeWritten = (int) metaHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH + Mp4MetaBox.FLAGS_LENGTH; positionOfNewIlstAtomRelativeToMoovAtom = (int) ((positionInExistingFileOfWhereNewIlstAtomShouldBeWritten) - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH)); } } } else { //There no ilst or meta header so we set to position where it would be if it existed positionOfNewIlstAtomRelativeToMoovAtom = moovHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH; positionInExistingFileOfWhereNewIlstAtomShouldBeWritten = (int) (moovHeader.getFileEndPos()); } } //There no udta header so we are going to create a new structure, but we have to be aware that there might be //an existing meta box structure in which case we preserve it but with our new structure before it. else { //Create new structure just after the end of the last trak atom, as that means // all modifications to trak atoms and its children (stco atoms) are *explicitly* written // as part of the moov atom (and not just bulk copied via writeDataAfterIlst()) if (metaHeader != null) { positionInExistingFileOfWhereNewIlstAtomShouldBeWritten = (int) trakHeader.getFileEndPos(); positionOfNewIlstAtomRelativeToMoovAtom = (int) (positionInExistingFileOfWhereNewIlstAtomShouldBeWritten - (moovHeader.getFilePos() + Mp4BoxHeader.HEADER_LENGTH)); } else { //There no udta,ilst or meta header so we set to position where it would be if it existed positionInExistingFileOfWhereNewIlstAtomShouldBeWritten = (int) (moovHeader.getFileEndPos()); positionOfNewIlstAtomRelativeToMoovAtom = moovHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH; } } //Find size of Level-4 Free atom (if any) immediately after ilst atom sizeOfExistingMetaLevelFreeAtom = getMetaLevelFreeAtomSize(atomTree); //Level-1 free atom positionOfTopLevelFreeAtom = 0; sizeOfExistingTopLevelFreeAtom = 0; topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata = true; for (DefaultMutableTreeNode freeNode : atomTree.getFreeNodes()) { DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) freeNode.getParent(); if (parentNode.isRoot()) { topLevelFreeHeader = ((Mp4BoxHeader) freeNode.getUserObject()); sizeOfExistingTopLevelFreeAtom = topLevelFreeHeader.getLength(); positionOfTopLevelFreeAtom = (int) topLevelFreeHeader.getFilePos(); break; } } if (sizeOfExistingTopLevelFreeAtom > 0) { if (positionOfTopLevelFreeAtom > mdatHeader.getFilePos()) { topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata = false; } else if (positionOfTopLevelFreeAtom < moovHeader.getFilePos()) { topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata = false; } } else { positionOfTopLevelFreeAtom = (int) mdatHeader.getFilePos(); } logger.config("Read header successfully ready for writing"); //The easiest option since no difference in the size of the metadata so all we have to do is //create a new file identical to first file but with replaced ilst if (sizeOfExistingIlstAtom == sizeRequiredByNewIlstAtom) { writeMetadataSameSize(fileReadChannel, fileWriteChannel, ilstHeader, newIlstData, neroTagsHeader); } //.. we just need to increase the size of the free atom below the meta atom, and replace the metadata //no other changes necessary and total file size remains the same else if (sizeOfExistingIlstAtom > sizeRequiredByNewIlstAtom) { writeOldMetadataLargerThanNewMetadata(fileReadChannel, fileWriteChannel, moovHeader, udtaHeader, metaHeader, ilstHeader, mdatHeader, neroTagsHeader, moovBuffer, newIlstData, stcos, sizeOfExistingMetaLevelFreeAtom); } //Size of metadata has increased, the most complex situation, more atoms affected else { int additionalSpaceRequiredForMetadata = sizeRequiredByNewIlstAtom - sizeOfExistingIlstAtom; if (additionalSpaceRequiredForMetadata <= (sizeOfExistingMetaLevelFreeAtom - Mp4BoxHeader.HEADER_LENGTH)) { writeNewMetadataLargerButCanUseFreeAtom( fileReadChannel, fileWriteChannel, ilstHeader, neroTagsHeader, sizeOfExistingMetaLevelFreeAtom, newIlstData, additionalSpaceRequiredForMetadata); } //There is not enough padding in the metadata free atom anyway else { int additionalMetaSizeThatWontFitWithinMetaAtom = additionalSpaceRequiredForMetadata - (sizeOfExistingMetaLevelFreeAtom); //Write stuff before Moov (ftyp) writeUpToMoovHeader(fileReadChannel, fileWriteChannel, moovHeader); if (udtaHeader == null) { writeNoExistingUdtaAtom(fileReadChannel, fileWriteChannel, newIlstData, moovHeader, moovBuffer, mdatHeader, stcos, sizeOfExistingTopLevelFreeAtom, topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, neroTagsHeader, sizeOfExistingMetaLevelFreeAtom, positionInExistingFileOfWhereNewIlstAtomShouldBeWritten, sizeOfExistingIlstAtom, positionOfTopLevelFreeAtom, additionalMetaSizeThatWontFitWithinMetaAtom); } else if (metaHeader == null) { writeNoExistingMetaAtom( udtaHeader, fileReadChannel, fileWriteChannel, newIlstData, moovHeader, moovBuffer, mdatHeader, stcos, sizeOfExistingTopLevelFreeAtom, topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, neroTagsHeader, sizeOfExistingMetaLevelFreeAtom, positionInExistingFileOfWhereNewIlstAtomShouldBeWritten, sizeOfExistingIlstAtom, positionOfTopLevelFreeAtom, additionalMetaSizeThatWontFitWithinMetaAtom); } else { writeHaveExistingMetadata(udtaHeader, metaHeader, fileReadChannel, fileWriteChannel, positionOfNewIlstAtomRelativeToMoovAtom, moovHeader, moovBuffer, mdatHeader, stcos, additionalMetaSizeThatWontFitWithinMetaAtom, sizeOfExistingTopLevelFreeAtom, topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, newIlstData, neroTagsHeader, sizeOfExistingMetaLevelFreeAtom, positionInExistingFileOfWhereNewIlstAtomShouldBeWritten, sizeOfExistingIlstAtom); } } } //Close all channels to original file fileReadChannel.close(); raf.close(); //Ensure we have written correctly, reject if not checkFileWrittenCorrectly(rafTemp, mdatHeader, fileWriteChannel, stcos); }
Write tag to {@code rafTemp} file. @param tag tag data @param raf current file @param rafTemp temporary file for writing @throws CannotWriteException @throws IOException
Mp4TagWriter::write
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeDataInChunks(FileChannel fileReadChannel, FileChannel fileWriteChannel) throws IOException, CannotWriteException { long amountToBeWritten = fileReadChannel.size() - fileReadChannel.position(); long written = 0; long chunksize = TagOptionSingleton.getInstance().getWriteChunkSize(); long count = amountToBeWritten / chunksize; long mod = amountToBeWritten % chunksize; for (int i = 0; i < count; i++) { written += fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), chunksize); fileWriteChannel.position(fileWriteChannel.position() + chunksize); } if(mod > 0) { written += fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), mod); if (written != amountToBeWritten) { throw new CannotWriteException("Was meant to write " + amountToBeWritten + " bytes but only written " + written + " bytes"); } } }
Write the remainder of data in read channel to write channel data in {@link TagOptionSingleton#getWriteChunkSize()} chunks, needed if writing large amounts of data. @param fileReadChannel @param fileWriteChannel @throws IOException @throws CannotWriteException
Mp4TagWriter::writeDataInChunks
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void convertandWriteTagsAtomToFreeAtom(FileChannel fileWriteChannel, Mp4BoxHeader tagsHeader) throws IOException { Mp4FreeBox freeBox = new Mp4FreeBox(tagsHeader.getDataLength()); fileWriteChannel.write(freeBox.getHeader().getHeaderData()); fileWriteChannel.write(freeBox.getData()); }
Replace tags atom (and children) by a {@code free} atom. @param fileWriteChannel @param tagsHeader @throws IOException
Mp4TagWriter::convertandWriteTagsAtomToFreeAtom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeDataUptoIncludingIlst(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader ilstHeader, ByteBuffer newIlstAtomData) throws IOException { fileReadChannel.position(0); fileWriteChannel.transferFrom(fileReadChannel, 0, ilstHeader.getFilePos()); fileWriteChannel.position(ilstHeader.getFilePos()); fileWriteChannel.write(newIlstAtomData); fileReadChannel.position(ilstHeader.getFileEndPos()); }
Write the data including new {@code ilst}. <p>Can be used as long as we don't have to adjust the size of {@code moov} header. @param fileReadChannel @param fileWriteChannel @param ilstHeader @param newIlstAtomData @throws IOException
Mp4TagWriter::writeDataUptoIncludingIlst
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeDataAfterIlst(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader tagsHeader) throws IOException, CannotWriteException { if (tagsHeader != null) { //Write from after free upto tags atom writeNeroData(fileReadChannel, fileWriteChannel, tagsHeader); } else { //Now write the rest of the file which won't have changed writeDataInChunks(fileReadChannel, fileWriteChannel); } }
Write data after {@code ilst} up to the end of the file. <p/> <p>Can be used if don't need to adjust size of {@code moov} header of modify top level {@code free} atoms @param fileReadChannel @param fileWriteChannel @param tagsHeader @throws IOException
Mp4TagWriter::writeDataAfterIlst
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private int getMetaLevelFreeAtomSize(Mp4AtomTree atomTree) { int oldMetaLevelFreeAtomSize;//Level 4 - Free oldMetaLevelFreeAtomSize = 0; for (DefaultMutableTreeNode freeNode : atomTree.getFreeNodes()) { DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) freeNode.getParent(); DefaultMutableTreeNode brotherNode = freeNode.getPreviousSibling(); if (!parentNode.isRoot()) { Mp4BoxHeader parentHeader = ((Mp4BoxHeader) parentNode.getUserObject()); Mp4BoxHeader freeHeader = ((Mp4BoxHeader) freeNode.getUserObject()); //We are only interested in free atoms at this level if they come after the ilst node if (brotherNode != null) { Mp4BoxHeader brotherHeader = ((Mp4BoxHeader) brotherNode.getUserObject()); if (parentHeader.getId().equals(Mp4AtomIdentifier.META.getFieldName()) && brotherHeader.getId().equals(Mp4AtomIdentifier.ILST.getFieldName())) { oldMetaLevelFreeAtomSize = freeHeader.getLength(); break; } } } } return oldMetaLevelFreeAtomSize; }
Determine the size of the {@code free} atom immediately after {@code ilst} atom at the same level (if any), we can use this if {@code ilst} needs to grow or shrink because of more less metadata. @param atomTree @return
Mp4TagWriter::getMetaLevelFreeAtomSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void checkFileWrittenCorrectly(RandomAccessFile rafTemp, Mp4BoxHeader mdatHeader, FileChannel fileWriteChannel, List<Mp4StcoBox> stcos) throws CannotWriteException, IOException { logger.config("Checking file has been written correctly"); try { //Create a tree from the new file Mp4AtomTree newAtomTree; newAtomTree = new Mp4AtomTree(rafTemp, false); //Check we still have audio data file, and check length Mp4BoxHeader newMdatHeader = newAtomTree.getBoxHeader(newAtomTree.getMdatNode()); if (newMdatHeader == null) { throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_NO_DATA.getMsg()); } if (newMdatHeader.getLength() != mdatHeader.getLength()) { throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_DATA_CORRUPT.getMsg()); } //Should always have udta atom after writing to file Mp4BoxHeader newUdtaHeader = newAtomTree.getBoxHeader(newAtomTree.getUdtaNode()); if (newUdtaHeader == null) { throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_NO_TAG_DATA.getMsg()); } //Should always have meta atom after writing to file Mp4BoxHeader newMetaHeader = newAtomTree.getBoxHeader(newAtomTree.getMetaNode()); if (newMetaHeader == null) { throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_NO_TAG_DATA.getMsg()); } // Check that we at the very least have the same number of chunk offsets final List<Mp4StcoBox> newStcos = newAtomTree.getStcos(); if (newStcos.size() != stcos.size()) { // at the very least, we have to have the same number of 'stco' atoms throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_INCORRECT_NUMBER_OF_TRACKS.getMsg(stcos.size(), newStcos.size())); } //Check offsets are correct, may not match exactly in original file so just want to make //sure that the discrepancy if any is preserved // compare the first new stco offset with mdat, // and ensure that all following ones have a constant shift int shift = 0; for (int i=0; i<newStcos.size(); i++) { final Mp4StcoBox newStco = newStcos.get(i); final Mp4StcoBox stco = stcos.get(i); logger.finer("stco:Original First Offset" + stco.getFirstOffSet()); logger.finer("stco:Original Diff" + (int) (stco.getFirstOffSet() - mdatHeader.getFilePos())); logger.finer("stco:Original Mdat Pos" + mdatHeader.getFilePos()); logger.finer("stco:New First Offset" + newStco.getFirstOffSet()); logger.finer("stco:New Diff" + (int) ((newStco.getFirstOffSet() - newMdatHeader.getFilePos()))); logger.finer("stco:New Mdat Pos" + newMdatHeader.getFilePos()); if (i == 0) { final int diff = (int) (stco.getFirstOffSet() - mdatHeader.getFilePos()); if ((newStco.getFirstOffSet() - newMdatHeader.getFilePos()) != diff) { int discrepancy = (int) ((newStco.getFirstOffSet() - newMdatHeader.getFilePos()) - diff); throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_INCORRECT_OFFSETS.getMsg(discrepancy)); } shift = stco.getFirstOffSet() - newStco.getFirstOffSet(); } else { if (shift != stco.getFirstOffSet() - newStco.getFirstOffSet()) { throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED_INCORRECT_OFFSETS.getMsg(shift)); } } } } catch (Exception e) { if (e instanceof CannotWriteException) { throw (CannotWriteException) e; } else { e.printStackTrace(); throw new CannotWriteException(ErrorMessage.MP4_CHANGES_TO_FILE_FAILED.getMsg() + ":" + e.getMessage()); } } finally { //Close references to new file rafTemp.close(); fileWriteChannel.close(); } logger.config("File has been written correctly"); }
Check file written correctly. @param rafTemp @param mdatHeader @param fileWriteChannel @param stcos @throws CannotWriteException @throws IOException
Mp4TagWriter::checkFileWrittenCorrectly
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
public void delete(RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException { Mp4Tag tag = new Mp4Tag(); try { write(tag, raf, rafTemp); } catch (CannotWriteException cwe) { throw new IOException(cwe.getMessage()); } }
Delete the tag. <p/> <p>This is achieved by writing an empty {@code ilst} atom. @param raf @param rafTemp @throws IOException
Mp4TagWriter::delete
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeNoExistingUdtaAtom(FileChannel fileReadChannel, FileChannel fileWriteChannel, ByteBuffer newIlstData, Mp4BoxHeader moovHeader, ByteBuffer moovBuffer, Mp4BoxHeader mdatHeader, List<Mp4StcoBox> stcos, int sizeOfExistingTopLevelFreeAtom, boolean topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, Mp4BoxHeader neroTagsHeader, int sizeOfExistingMetaLevelFreeAtom, int positionInExistingFileOfWhereNewIlstAtomShouldBeWritten, int existingSizeOfIlstData, int topLevelFreeSize, int additionalMetaSizeThatWontFitWithinMetaAtom) throws IOException, CannotWriteException { logger.severe("Writing:Option 5.1;No udta atom"); long endOfMoov = moovHeader.getFileEndPos(); Mp4HdlrBox hdlrBox = Mp4HdlrBox.createiTunesStyleHdlrBox(); Mp4MetaBox metaBox = Mp4MetaBox.createiTunesStyleMetaBox(hdlrBox.getHeader().getLength() + newIlstData.limit()); Mp4BoxHeader udtaHeader = new Mp4BoxHeader(Mp4AtomIdentifier.UDTA.getFieldName()); udtaHeader.setLength(Mp4BoxHeader.HEADER_LENGTH + metaBox.getHeader().getLength()); boolean isMdatDataMoved = adjustStcosIfNoSuitableTopLevelAtom(sizeOfExistingTopLevelFreeAtom, topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, udtaHeader.getLength(), stcos, moovHeader, mdatHeader); //Edit the Moov header to length and rewrite to account for new udta atom moovHeader.setLength(moovHeader.getLength() + udtaHeader.getLength()); fileWriteChannel.write(moovHeader.getHeaderData()); moovBuffer.rewind(); fileWriteChannel.write(moovBuffer); //Write new atoms required for holding metadata in itunes format fileWriteChannel.write(udtaHeader.getHeaderData()); fileWriteChannel.write(metaBox.getHeader().getHeaderData()); fileWriteChannel.write(metaBox.getData()); fileWriteChannel.write(hdlrBox.getHeader().getHeaderData()); fileWriteChannel.write(hdlrBox.getData()); //Now write ilst data fileWriteChannel.write(newIlstData); //Skip over the read channel existing ilst(if exists) and metadata free atom fileReadChannel.position(positionInExistingFileOfWhereNewIlstAtomShouldBeWritten + existingSizeOfIlstData + sizeOfExistingMetaLevelFreeAtom); //Write the remainder of any data in the moov buffer thats comes after existing ilst/metadata level free atoms //but we replace any neroTags atoms with free atoms as these cause problems if (neroTagsHeader != null) { writeFromEndOfIlstToNeroTagsAndMakeNeroFree(endOfMoov, fileReadChannel, fileWriteChannel, neroTagsHeader); } else { //Write the remaining children under moov that come after ilst/free which wont have changed long extraData = endOfMoov - fileReadChannel.position(); fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), extraData); fileWriteChannel.position(fileWriteChannel.position() + extraData); } if (!isMdatDataMoved) { adjustFreeAtom(fileReadChannel, fileWriteChannel, topLevelFreeSize, additionalMetaSizeThatWontFitWithinMetaAtom); } else { logger.config("Writing:Option 9;Top Level Free comes after Mdat or before Metadata or not large enough"); } writeDataInChunks(fileReadChannel, fileWriteChannel); }
Use when we need to write metadata and there is no existing {@code udta} atom so we have to create the complete udta/metadata structure. @param fileWriteChannel @param newIlstData @param moovHeader @param moovBuffer @param mdatHeader @param stcos @param sizeOfExistingTopLevelFreeAtom @param topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata @throws IOException @throws CannotWriteException
Mp4TagWriter::writeNoExistingUdtaAtom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeNoExistingMetaAtom(Mp4BoxHeader udtaHeader, FileChannel fileReadChannel, FileChannel fileWriteChannel, ByteBuffer newIlstData, Mp4BoxHeader moovHeader, ByteBuffer moovBuffer, Mp4BoxHeader mdatHeader, List<Mp4StcoBox> stcos, int sizeOfExistingTopLevelFreeAtom, boolean topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, Mp4BoxHeader neroTagsHeader, int sizeOfExistingMetaLevelFreeAtom, int positionInExistingFileOfWhereNewIlstAtomShouldBeWritten, int existingSizeOfIlstData, int topLevelFreeSize, int additionalMetaSizeThatWontFitWithinMetaAtom) throws IOException, CannotWriteException { //Create a new udta atom logger.severe("Writing:Option 5.2;No meta atom"); long endOfMoov = moovHeader.getFileEndPos(); int newIlstDataSize = newIlstData.limit(); int existingMoovHeaderDataLength = moovHeader.getDataLength(); //Udta didnt have a meta atom but it may have some other data we want to preserve (I think) int existingUdtaLength = udtaHeader.getLength(); int existingUdtaDataLength = udtaHeader.getDataLength(); Mp4HdlrBox hdlrBox = Mp4HdlrBox.createiTunesStyleHdlrBox(); Mp4MetaBox metaBox = Mp4MetaBox.createiTunesStyleMetaBox(hdlrBox.getHeader().getLength() + newIlstDataSize); udtaHeader = new Mp4BoxHeader(Mp4AtomIdentifier.UDTA.getFieldName()); udtaHeader.setLength(Mp4BoxHeader.HEADER_LENGTH + metaBox.getHeader().getLength() + existingUdtaDataLength); int increaseInSizeOfUdtaAtom = udtaHeader.getDataLength() - existingUdtaDataLength; boolean isMdatDataMoved = adjustStcosIfNoSuitableTopLevelAtom(sizeOfExistingTopLevelFreeAtom, topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, increaseInSizeOfUdtaAtom, stcos, moovHeader, mdatHeader); //Edit and rewrite the Moov header upto start of Udta moovHeader.setLength(moovHeader.getLength() + increaseInSizeOfUdtaAtom); fileWriteChannel.write(moovHeader.getHeaderData()); moovBuffer.rewind(); moovBuffer.limit(existingMoovHeaderDataLength - existingUdtaLength); fileWriteChannel.write(moovBuffer); //Write new atoms required for holding metadata in iTunes format fileWriteChannel.write(udtaHeader.getHeaderData()); //Write any atoms if they previously existed within udta atom if(moovBuffer.position() + Mp4BoxHeader.HEADER_LENGTH < moovBuffer.capacity()) { moovBuffer.limit(moovBuffer.capacity()); moovBuffer.position(moovBuffer.position() + Mp4BoxHeader.HEADER_LENGTH); fileWriteChannel.write(moovBuffer); } //Write our newly constructed meta/hdlr headers (required for ilst) fileWriteChannel.write(metaBox.getHeader().getHeaderData()); fileWriteChannel.write(metaBox.getData()); fileWriteChannel.write(hdlrBox.getHeader().getHeaderData()); fileWriteChannel.write(hdlrBox.getData()); //Now write ilst data fileWriteChannel.write(newIlstData); //Skip over the read channel existing ilst(if exists) and metadata free atom fileReadChannel.position(positionInExistingFileOfWhereNewIlstAtomShouldBeWritten + existingSizeOfIlstData + sizeOfExistingMetaLevelFreeAtom); //Write the remainder of any data in the moov buffer thats comes after existing ilst/metadata level free atoms //but we replace any neroTags atoms with free atoms as these cause problems if (neroTagsHeader != null) { writeFromEndOfIlstToNeroTagsAndMakeNeroFree(endOfMoov, fileReadChannel, fileWriteChannel, neroTagsHeader); } else { //Now write the rest of children under moov thats come after ilst/free which wont have changed long extraData = endOfMoov - fileReadChannel.position(); fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), extraData); fileWriteChannel.position(fileWriteChannel.position() + extraData); } if (!isMdatDataMoved) { adjustFreeAtom(fileReadChannel, fileWriteChannel, topLevelFreeSize, additionalMetaSizeThatWontFitWithinMetaAtom); } else { logger.config("Writing:Option 9;Top Level Free comes after Mdat or before Metadata or not large enough"); } writeDataInChunks(fileReadChannel, fileWriteChannel); }
Use when we need to write metadata, we have a {@code udta} atom but there is no existing meta atom so we have to create the complete metadata structure. @param fileWriteChannel @param newIlstData @param moovHeader @param moovBuffer @param mdatHeader @param stcos @param sizeOfExistingTopLevelFreeAtom @param topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata @throws IOException @throws CannotWriteException
Mp4TagWriter::writeNoExistingMetaAtom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeHaveExistingMetadata(Mp4BoxHeader udtaHeader, Mp4BoxHeader metaHeader, FileChannel fileReadChannel, FileChannel fileWriteChannel, int positionOfNewIlstAtomRelativeToMoovAtom, Mp4BoxHeader moovHeader, ByteBuffer moovBuffer, Mp4BoxHeader mdatHeader, List<Mp4StcoBox> stcos, int additionalMetaSizeThatWontFitWithinMetaAtom, int topLevelFreeSize, boolean topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, ByteBuffer newIlstData, Mp4BoxHeader neroTagsHeader, int sizeOfExistingMetaLevelFreeAtom, int positionInExistingFileOfWhereNewIlstAtomShouldBeWritten, int existingSizeOfIlstData) throws IOException, CannotWriteException { logger.config("Writing:Option 5.3;udta and meta atom exists"); boolean isMdatDataMoved = adjustStcosIfNoSuitableTopLevelAtom(topLevelFreeSize, topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, additionalMetaSizeThatWontFitWithinMetaAtom, stcos, moovHeader, mdatHeader); long endOfMoov = moovHeader.getFileEndPos(); //Edit and rewrite the Moov header inc udta and meta headers) adjustSizeOfMoovHeader(moovHeader, moovBuffer, additionalMetaSizeThatWontFitWithinMetaAtom, udtaHeader, metaHeader); fileWriteChannel.write(moovHeader.getHeaderData()); //Now write from this edited buffer up until location of start of ilst atom moovBuffer.rewind(); moovBuffer.limit(positionOfNewIlstAtomRelativeToMoovAtom); fileWriteChannel.write(moovBuffer); //Now write ilst data fileWriteChannel.write(newIlstData); //Write the remainder of any data in the moov buffer thats comes after existing ilst/metadata level free atoms //but we replace any neroTags atoms with free atoms as these cause problems if (neroTagsHeader != null) { //Skip over the read channel existing ilst(if exists) and metadata free atom fileReadChannel.position(positionInExistingFileOfWhereNewIlstAtomShouldBeWritten + existingSizeOfIlstData + sizeOfExistingMetaLevelFreeAtom); // TODO: Does this handle changed stco tags correctly that occur *after* ilst? writeFromEndOfIlstToNeroTagsAndMakeNeroFree(endOfMoov, fileReadChannel, fileWriteChannel, neroTagsHeader); } else { //Write the remaining children under moov that come after ilst/free //These might have changed, if they contain stco atoms moovBuffer.limit(moovBuffer.capacity()); moovBuffer.position(positionOfNewIlstAtomRelativeToMoovAtom + existingSizeOfIlstData + sizeOfExistingMetaLevelFreeAtom); fileWriteChannel.write(moovBuffer); fileReadChannel.position(moovHeader.getFileEndPos() - additionalMetaSizeThatWontFitWithinMetaAtom); } if (!isMdatDataMoved) { adjustFreeAtom(fileReadChannel, fileWriteChannel, topLevelFreeSize, additionalMetaSizeThatWontFitWithinMetaAtom); } else { logger.config("Writing:Option 9;Top Level Free comes after Mdat or before Metadata or not large enough"); } writeDataInChunks(fileReadChannel, fileWriteChannel); }
We have existing structure but we need more space. @param udtaHeader @param fileWriteChannel @param positionOfNewIlstAtomRelativeToMoovAtom @param moovHeader @param moovBuffer @param mdatHeader @param stcos @param additionalMetaSizeThatWontFitWithinMetaAtom @param topLevelFreeSize @param topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata @throws IOException @throws CannotWriteException
Mp4TagWriter::writeHaveExistingMetadata
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void writeFromEndOfIlstToNeroTagsAndMakeNeroFree(long endOfMoov, FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader neroTagsHeader) throws IOException { //Write from after ilst upto tags atom long writeBetweenIlstAndTags = neroTagsHeader.getFilePos() - fileReadChannel.position(); fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), writeBetweenIlstAndTags); fileWriteChannel.position(fileWriteChannel.position() + writeBetweenIlstAndTags); convertandWriteTagsAtomToFreeAtom(fileWriteChannel, neroTagsHeader); //Write after tags atom upto end of moov fileReadChannel.position(neroTagsHeader.getFileEndPos()); long extraData = endOfMoov - fileReadChannel.position(); fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), extraData); }
If any data between existing {@code ilst} atom and {@code tags} atom write it to new file, then convert {@code tags} atom to a {@code free} atom. @param endOfMoov @param fileReadChannel @param fileWriteChannel @param neroTagsHeader @throws IOException
Mp4TagWriter::writeFromEndOfIlstToNeroTagsAndMakeNeroFree
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private void adjustFreeAtom(FileChannel fileReadChannel, FileChannel fileWriteChannel, int topLevelFreeSize, int additionalMetaSizeThatWontFitWithinMetaAtom) throws IOException, CannotWriteException { //If the shift is less than the space available in this second free atom data size we just //shrink the free atom accordingly if (topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH >= additionalMetaSizeThatWontFitWithinMetaAtom) { logger.config("Writing:Option 6;Larger Size can use top free atom"); Mp4FreeBox freeBox = new Mp4FreeBox((topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH) - additionalMetaSizeThatWontFitWithinMetaAtom); fileWriteChannel.write(freeBox.getHeader().getHeaderData()); fileWriteChannel.write(freeBox.getData()); //Skip over the read channel old free atom fileReadChannel.position(fileReadChannel.position() + topLevelFreeSize); } //If the space required is identical to total size of the free space (inc header) //we could just remove the header else if (topLevelFreeSize == additionalMetaSizeThatWontFitWithinMetaAtom) { logger.config("Writing:Option 7;Larger Size uses top free atom including header"); //Skip over the read channel old free atom fileReadChannel.position(fileReadChannel.position() + topLevelFreeSize); } else { //MDAT comes before MOOV, nothing to do because data has already been written } }
We adjust {@code free} atom, allowing us to not need to move {@code mdat} atom. @param fileReadChannel @param fileWriteChannel @param topLevelFreeSize @param additionalMetaSizeThatWontFitWithinMetaAtom @throws IOException @throws CannotWriteException
Mp4TagWriter::adjustFreeAtom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
private boolean adjustStcosIfNoSuitableTopLevelAtom(int topLevelFreeSize, boolean topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata, int additionalSizeRequired, List<Mp4StcoBox> stcos, Mp4BoxHeader moovHeader, Mp4BoxHeader mdatHeader) { //We don't bother using the top level free atom coz not big enough anyway, we need to adjust offsets //by the amount mdat is going to be shifted as long as mdat is after moov if (mdatHeader.getFilePos() > moovHeader.getFilePos()) { //Edit stco atoms within moov header, if the free atom comes after mdat OR //(there is not enough space in the top level free atom //or special case (of not matching exactly the free atom plus header so could remove free atom completely) if ((!topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata) || ((topLevelFreeSize - Mp4BoxHeader.HEADER_LENGTH < additionalSizeRequired) && (topLevelFreeSize != additionalSizeRequired))) { for (final Mp4StcoBox stoc : stcos) { stoc.adjustOffsets(additionalSizeRequired); } return true; } } return false; }
May need to rewrite the {@code stco} offsets, if the location of {@code mdat} (audio) header is going to move. @param topLevelFreeSize @param topLevelFreeAtomComesBeforeMdatAtomAndAfterMetadata @param additionalSizeRequired @param stcos @param moovHeader @param mdatHeader @return {@code true}, if offsets were adjusted because unable to fit in new metadata without shifting {@code mdat} header further down
Mp4TagWriter::adjustStcosIfNoSuitableTopLevelAtom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagWriter.java
Apache-2.0
public Mp4Tag read(RandomAccessFile raf) throws CannotReadException, IOException { FileChannel fc = raf.getChannel(); Mp4Tag tag = new Mp4Tag(); //Get to the facts everything we are interested in is within the moov box, so just load data from file //once so no more file I/O needed Mp4BoxHeader moovHeader = Mp4BoxHeader.seekWithinLevel(fc, Mp4AtomIdentifier.MOOV.getFieldName()); if (moovHeader == null) { throw new CannotReadException(ErrorMessage.MP4_FILE_NOT_CONTAINER.getMsg()); } ByteBuffer moovBuffer = ByteBuffer.allocate(moovHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH); raf.getChannel().read(moovBuffer); moovBuffer.rewind(); //Level 2-Searching for "udta" within "moov" Mp4BoxHeader boxHeader = Mp4BoxHeader.seekWithinLevel(moovBuffer, Mp4AtomIdentifier.UDTA.getFieldName()); if (boxHeader != null) { //Level 3-Searching for "meta" within udta boxHeader = Mp4BoxHeader.seekWithinLevel(moovBuffer, Mp4AtomIdentifier.META.getFieldName()); if (boxHeader == null) { logger.warning(ErrorMessage.MP4_FILE_HAS_NO_METADATA.getMsg()); return tag; } Mp4MetaBox meta = new Mp4MetaBox(boxHeader, moovBuffer); meta.processData(); //Level 4- Search for "ilst" within meta boxHeader = Mp4BoxHeader.seekWithinLevel(moovBuffer, Mp4AtomIdentifier.ILST.getFieldName()); //This file does not actually contain a tag if (boxHeader == null) { logger.warning(ErrorMessage.MP4_FILE_HAS_NO_METADATA.getMsg()); return tag; } } else { //Level 2-Searching for "meta" not within udta boxHeader = Mp4BoxHeader.seekWithinLevel(moovBuffer, Mp4AtomIdentifier.META.getFieldName()); if (boxHeader == null) { logger.warning(ErrorMessage.MP4_FILE_HAS_NO_METADATA.getMsg()); return tag; } Mp4MetaBox meta = new Mp4MetaBox(boxHeader, moovBuffer); meta.processData(); //Level 3- Search for "ilst" within meta boxHeader = Mp4BoxHeader.seekWithinLevel(moovBuffer, Mp4AtomIdentifier.ILST.getFieldName()); //This file does not actually contain a tag if (boxHeader == null) { logger.warning(ErrorMessage.MP4_FILE_HAS_NO_METADATA.getMsg()); return tag; } } //Size of metadata (exclude the size of the ilst parentHeader), take a slice starting at //metadata children to make things safer int length = boxHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH; ByteBuffer metadataBuffer = moovBuffer.slice(); //Datalength is longer are there boxes after ilst at this level? logger.config("headerlengthsays:" + length + "datalength:" + metadataBuffer.limit()); int read = 0; logger.config("Started to read metadata fields at position is in metadata buffer:" + metadataBuffer.position()); while (read < length) { //Read the boxHeader boxHeader.update(metadataBuffer); //Create the corresponding datafield from the id, and slice the buffer so position of main buffer //wont get affected logger.config("Next position is at:" + metadataBuffer.position()); createMp4Field(tag, boxHeader, metadataBuffer.slice()); //Move position in buffer to the start of the next parentHeader metadataBuffer.position(metadataBuffer.position() + boxHeader.getDataLength()); read += boxHeader.getLength(); } return tag; }
Reads metadata from mp4, <p>The metadata tags are usually held under the ilst atom as shown below <p>Valid Exceptions to the rule: <p>Can be no udta atom with meta rooted immediately under moov instead <p>Can be no udta/meta atom at all <pre> |--- ftyp |--- moov |......| |......|----- mvdh |......|----- trak |......|----- udta |..............| |..............|-- meta |....................| |....................|-- hdlr |....................|-- ilst |.........................| |.........................|---- @nam (Optional for each metadatafield) |.........................|.......|-- data |.........................|....... ecetera |.........................|---- ---- (Optional for reverse dns field) |.................................|-- mean |.................................|-- name |.................................|-- data |.................................... ecetere | |--- mdat </pre public class Mp4TagReader { // Logger Object public static Logger logger = Logger.getLogger("org.jaudiotagger.tag.mp4"); /* The metadata is stored in the box under the hierachy moov.udta.meta.ilst There are gaps between these boxes
Mp4TagReader::read
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagReader.java
Apache-2.0
private void createMp4Field(Mp4Tag tag, Mp4BoxHeader header, ByteBuffer raw) throws UnsupportedEncodingException { //Header with no data #JAUDIOTAGGER-463 if(header.getDataLength()==0) { //Just Ignore } //Reverse Dns Atom else if (header.getId().equals(Mp4TagReverseDnsField.IDENTIFIER)) { // try { TagField field = new Mp4TagReverseDnsField(header, raw); tag.addField(field); } catch (Exception e) { logger.warning(ErrorMessage.MP4_UNABLE_READ_REVERSE_DNS_FIELD.getMsg(e.getMessage())); TagField field = new Mp4TagRawBinaryField(header, raw); tag.addField(field); } } //Normal Parent with Data atom else { int currentPos = raw.position(); boolean isDataIdentifier = Utils.getString(raw, Mp4BoxHeader.IDENTIFIER_POS, Mp4BoxHeader.IDENTIFIER_LENGTH, StandardCharsets.ISO_8859_1).equals(Mp4DataBox.IDENTIFIER); raw.position(currentPos); if (isDataIdentifier) { //Need this to decide what type of Field to create int type = Utils.getIntBE(raw, Mp4DataBox.TYPE_POS_INCLUDING_HEADER, Mp4DataBox.TYPE_POS_INCLUDING_HEADER + Mp4DataBox.TYPE_LENGTH - 1); Mp4FieldType fieldType = Mp4FieldType.getFieldType(type); logger.config("Box Type id:" + header.getId() + ":type:" + fieldType); //Special handling for some specific identifiers otherwise just base on class id if (header.getId().equals(Mp4FieldKey.TRACK.getFieldName())) { TagField field = new Mp4TrackField(header.getId(), raw); tag.addField(field); } else if (header.getId().equals(Mp4FieldKey.DISCNUMBER.getFieldName())) { TagField field = new Mp4DiscNoField(header.getId(), raw); tag.addField(field); } else if (header.getId().equals(Mp4FieldKey.GENRE.getFieldName())) { TagField field = new Mp4GenreField(header.getId(), raw); tag.addField(field); } else if (header.getId().equals(Mp4FieldKey.ARTWORK.getFieldName()) || Mp4FieldType.isCoverArtType(fieldType)) { int processedDataSize = 0; int imageCount = 0; //The loop should run for each image (each data atom) while (processedDataSize < header.getDataLength()) { //There maybe a mixture of PNG and JPEG images so have to check type //for each subimage (if there are more than one image) if (imageCount > 0) { type = Utils.getIntBE(raw, processedDataSize + Mp4DataBox.TYPE_POS_INCLUDING_HEADER, processedDataSize + Mp4DataBox.TYPE_POS_INCLUDING_HEADER + Mp4DataBox.TYPE_LENGTH - 1); fieldType = Mp4FieldType.getFieldType(type); } Mp4TagCoverField field = new Mp4TagCoverField(raw,fieldType); tag.addField(field); processedDataSize += field.getDataAndHeaderSize(); imageCount++; } } else if (fieldType == Mp4FieldType.TEXT) { TagField field = new Mp4TagTextField(header.getId(), raw); tag.addField(field); } else if (fieldType == Mp4FieldType.IMPLICIT) { TagField field = new Mp4TagTextNumberField(header.getId(), raw); tag.addField(field); } else if (fieldType == Mp4FieldType.INTEGER) { TagField field = new Mp4TagByteField(header.getId(), raw); tag.addField(field); } else { boolean existingId = false; for (Mp4FieldKey key : Mp4FieldKey.values()) { if (key.getFieldName().equals(header.getId())) { //The parentHeader is a known id but its field type is not one of the expected types so //this field is invalid. i.e I received a file with the TMPO set to 15 (Oxf) when it should //be 21 (ox15) so looks like somebody got their decimal and hex numbering confused //So in this case best to ignore this field and just write a warning existingId = true; logger.warning("Known Field:" + header.getId() + " with invalid field type of:" + type + " is ignored"); break; } } //Unknown field id with unknown type so just create as binary if (!existingId) { logger.warning("UnKnown Field:" + header.getId() + " with invalid field type of:" + type + " created as binary"); TagField field = new Mp4TagBinaryField(header.getId(), raw); tag.addField(field); } } } //Special Cases else { //MediaMonkey 3 CoverArt Attributes field, does not have data items so just //copy parent and child as is without modification if (header.getId().equals(Mp4NonStandardFieldKey.AAPR.getFieldName())) { TagField field = new Mp4TagRawBinaryField(header, raw); tag.addField(field); } //Default case else { TagField field = new Mp4TagRawBinaryField(header, raw); tag.addField(field); } } } }
Process the field and add to the tag Note:In the case of coverart MP4 holds all the coverart within individual dataitems all within a single covr atom, we will add separate mp4field for each image. @param tag @param header @param raw @return @throws UnsupportedEncodingException
Mp4TagReader::createMp4Field
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4TagReader.java
Apache-2.0
public Mp4EsdsBox.Kind getKind() { return kind; }
@return kind
Mp4AudioHeader::getKind
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java
Apache-2.0
public void setProfile(Mp4EsdsBox.AudioProfile profile) { this.profile=profile; }
The key for the profile @param profile
Mp4AudioHeader::setProfile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java
Apache-2.0
public Mp4EsdsBox.AudioProfile getProfile() { return profile; }
@return audio profile
Mp4AudioHeader::getProfile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java
Apache-2.0