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 int getCommentHeaderSize() { return commentHeaderSize; }
@return the size of the raw packet data for the vorbis comment header (includes vorbis header)
OggVorbisHeaderSizes::getCommentHeaderSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
Apache-2.0
public int getSetupHeaderSize() { return setupHeaderSize; }
@return he size of the raw packet data for the vorbis setup header (includes vorbis header)
OggVorbisHeaderSizes::getSetupHeaderSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
Apache-2.0
public int getExtraPacketDataSize() { int extraPacketSize = 0; for (OggPageHeader.PacketStartAndLength packet : packetList) { extraPacketSize += packet.getLength(); } return extraPacketSize; }
Return the size required by all the extra packets on same page as setup header, usually there are no packets immediately after the setup packet. @return extra data size required for additional packets on same page
OggVorbisHeaderSizes::getExtraPacketDataSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
Apache-2.0
public long getCommentHeaderStartPosition() { return commentHeaderStartPosition; }
@return the start position in the file of the ogg header which contains the start of the Vorbis Comment
OggVorbisHeaderSizes::getCommentHeaderStartPosition
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
Apache-2.0
public long getSetupHeaderStartPosition() { return setupHeaderStartPosition; }
@return the start position in the file of the ogg header which contains the start of the Setup Header
OggVorbisHeaderSizes::getSetupHeaderStartPosition
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagReader.java
Apache-2.0
private void calculateChecksumOverPage(ByteBuffer page) { //CRC should be zero before calculating it page.putInt(OggPageHeader.FIELD_PAGE_CHECKSUM_POS, 0); //Compute CRC over the page //TODO shouldnt really use array(); byte[] crc = OggCRCFactory.computeCRC(page.array()); for (int i = 0; i < crc.length; i++) { page.put(OggPageHeader.FIELD_PAGE_CHECKSUM_POS + i, crc[i]); } //Rewind to start of Page page.rewind(); }
Calculate checkSum over the Page @param page
OggVorbisTagWriter::calculateChecksumOverPage
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
private ByteBuffer startCreateBasicSecondPage( OggVorbisTagReader.OggVorbisHeaderSizes vorbisHeaderSizes, int newCommentLength, int newSecondPageLength, OggPageHeader secondPageHeader, ByteBuffer newComment) throws IOException { logger.fine("WriteOgg Type 1"); byte[] segmentTable = createSegmentTable(newCommentLength, vorbisHeaderSizes.getSetupHeaderSize(), vorbisHeaderSizes.getExtraPacketList()); int newSecondPageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length; logger.fine("New second page header length:" + newSecondPageHeaderLength); logger.fine("No of segments:" + segmentTable.length); ByteBuffer secondPageBuffer = ByteBuffer.allocate(newSecondPageLength + newSecondPageHeaderLength); secondPageBuffer.order(ByteOrder.LITTLE_ENDIAN); //Build the new 2nd page header, can mostly be taken from the original upto the segment length OggS capture secondPageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1); //Number of Page Segments secondPageBuffer.put((byte) segmentTable.length); //Page segment table for (byte aSegmentTable : segmentTable) { secondPageBuffer.put(aSegmentTable); } //Add New VorbisComment secondPageBuffer.put(newComment); return secondPageBuffer; }
Create a second Page, and add comment header to it, but page is incomplete may want to add addition header and need to calculate CRC @param vorbisHeaderSizes @param newCommentLength @param newSecondPageLength @param secondPageHeader @param newComment @return @throws IOException
OggVorbisTagWriter::startCreateBasicSecondPage
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
private void replaceSecondPageOnly( OggVorbisTagReader.OggVorbisHeaderSizes vorbisHeaderSizes, int newCommentLength, int newSecondPageLength, OggPageHeader secondPageHeader, ByteBuffer newComment, long secondPageHeaderEndPos, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException { logger.fine("WriteOgg Type 1"); ByteBuffer secondPageBuffer = startCreateBasicSecondPage(vorbisHeaderSizes, newCommentLength, newSecondPageLength, secondPageHeader, newComment); raf.seek(secondPageHeaderEndPos); //Skip comment header raf.skipBytes(vorbisHeaderSizes.getCommentHeaderSize()); //Read in setup header and extra packets raf.getChannel().read(secondPageBuffer); calculateChecksumOverPage(secondPageBuffer); rafTemp.getChannel().write(secondPageBuffer); rafTemp.getChannel().transferFrom(raf.getChannel(), rafTemp.getFilePointer(), raf.length() - raf.getFilePointer()); }
Usually can use this method, previously comment and setup header all fit on page 2 and they still do, so just replace this page. And copy further pages as is. @param vorbisHeaderSizes @param newCommentLength @param newSecondPageLength @param secondPageHeader @param newComment @param secondPageHeaderEndPos @param raf @param rafTemp @throws IOException
OggVorbisTagWriter::replaceSecondPageOnly
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
private void replaceSecondPageAndRenumberPageSeqs(OggVorbisTagReader.OggVorbisHeaderSizes originalHeaderSizes, int newCommentLength, int newSecondPageLength, OggPageHeader secondPageHeader, ByteBuffer newComment, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException, CannotReadException, CannotWriteException { logger.fine("WriteOgg Type 2"); ByteBuffer secondPageBuffer = startCreateBasicSecondPage(originalHeaderSizes, newCommentLength, newSecondPageLength, secondPageHeader, newComment); //Add setup header and packets int pageSequence = secondPageHeader.getPageSequence(); byte[] setupHeaderData = reader.convertToVorbisSetupHeaderPacketAndAdditionalPackets(originalHeaderSizes.getSetupHeaderStartPosition(), raf); logger.finest(setupHeaderData.length + ":" + secondPageBuffer.position() + ":" + secondPageBuffer.capacity()); secondPageBuffer.put(setupHeaderData); calculateChecksumOverPage(secondPageBuffer); rafTemp.getChannel().write(secondPageBuffer); writeRemainingPages(pageSequence, raf, rafTemp); }
Previously comment and/or setup header was on a number of pages now can just replace this page fitting all on 2nd page, and renumber subsequent sequence pages @param originalHeaderSizes @param newCommentLength @param newSecondPageLength @param secondPageHeader @param newComment @param raf @param rafTemp @throws IOException @throws org.jaudiotagger.audio.exceptions.CannotReadException @throws org.jaudiotagger.audio.exceptions.CannotWriteException
OggVorbisTagWriter::replaceSecondPageAndRenumberPageSeqs
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
private void replacePagesAndRenumberPageSeqs(OggVorbisTagReader.OggVorbisHeaderSizes originalHeaderSizes, int newCommentLength, OggPageHeader secondPageHeader, ByteBuffer newComment, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException, CannotReadException, CannotWriteException { int pageSequence = secondPageHeader.getPageSequence(); //We need to work out how to split the newcommentlength over the pages int noOfCompletePagesNeededForComment = newCommentLength / OggPageHeader.MAXIMUM_PAGE_DATA_SIZE; logger.config("Comment requires:" + noOfCompletePagesNeededForComment + " complete pages"); //Create the Pages int newCommentOffset = 0; if (noOfCompletePagesNeededForComment > 0) { for (int i = 0; i < noOfCompletePagesNeededForComment; i++) { //Create ByteBuffer for the New page byte[] segmentTable = this.createSegments(OggPageHeader.MAXIMUM_PAGE_DATA_SIZE, false); int pageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length; ByteBuffer pageBuffer = ByteBuffer.allocate(pageHeaderLength + OggPageHeader.MAXIMUM_PAGE_DATA_SIZE); pageBuffer.order(ByteOrder.LITTLE_ENDIAN); //Now create the page basing it on the existing 2ndpageheader pageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1); //Number of Page Segments pageBuffer.put((byte) segmentTable.length); //Page segment table for (byte aSegmentTable : segmentTable) { pageBuffer.put(aSegmentTable); } //Get next bit of Comment ByteBuffer nextPartOfComment = newComment.slice(); nextPartOfComment.limit(OggPageHeader.MAXIMUM_PAGE_DATA_SIZE); pageBuffer.put(nextPartOfComment); //Recalculate Page Sequence Number pageBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence); pageSequence++; //Set Header Flag to indicate continuous (except for first flag) if (i != 0) { pageBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue()); } calculateChecksumOverPage(pageBuffer); rafTemp.getChannel().write(pageBuffer); newCommentOffset += OggPageHeader.MAXIMUM_PAGE_DATA_SIZE; newComment.position(newCommentOffset); } } int lastPageCommentPacketSize = newCommentLength % OggPageHeader.MAXIMUM_PAGE_DATA_SIZE; logger.fine("Last comment packet size:" + lastPageCommentPacketSize); //End of comment and setup header cannot fit on the last page if (!isCommentAndSetupHeaderFitsOnASinglePage(lastPageCommentPacketSize, originalHeaderSizes.getSetupHeaderSize(), originalHeaderSizes.getExtraPacketList())) { logger.fine("WriteOgg Type 3"); //Write the last part of comment only (its possible it might be the only comment) { byte[] segmentTable = createSegments(lastPageCommentPacketSize, true); int pageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length; ByteBuffer pageBuffer = ByteBuffer.allocate(lastPageCommentPacketSize + pageHeaderLength); pageBuffer.order(ByteOrder.LITTLE_ENDIAN); pageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1); pageBuffer.put((byte) segmentTable.length); for (byte aSegmentTable : segmentTable) { pageBuffer.put(aSegmentTable); } newComment.position(newCommentOffset); pageBuffer.put(newComment.slice()); pageBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence); if(noOfCompletePagesNeededForComment>0) { pageBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue()); } logger.fine("Writing Last Comment Page "+pageSequence +" to file"); pageSequence++; calculateChecksumOverPage(pageBuffer); rafTemp.getChannel().write(pageBuffer); } //Now write header and extra packets onto next page { byte[] segmentTable = this.createSegmentTable(originalHeaderSizes.getSetupHeaderSize(),originalHeaderSizes.getExtraPacketList()); int pageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length; byte[] setupHeaderData = reader.convertToVorbisSetupHeaderPacketAndAdditionalPackets(originalHeaderSizes.getSetupHeaderStartPosition(), raf); ByteBuffer pageBuffer = ByteBuffer.allocate(setupHeaderData.length + pageHeaderLength); pageBuffer.order(ByteOrder.LITTLE_ENDIAN); pageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1); pageBuffer.put((byte) segmentTable.length); for (byte aSegmentTable : segmentTable) { pageBuffer.put(aSegmentTable); } pageBuffer.put(setupHeaderData); pageBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence); //pageBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue()); logger.fine("Writing Setup Header and packets Page "+pageSequence +" to file"); calculateChecksumOverPage(pageBuffer); rafTemp.getChannel().write(pageBuffer); } } else { //End of Comment and SetupHeader and extra packets can fit on one page logger.fine("WriteOgg Type 4"); //Create last header page int newSecondPageDataLength = originalHeaderSizes.getSetupHeaderSize() + lastPageCommentPacketSize + originalHeaderSizes.getExtraPacketDataSize(); newComment.position(newCommentOffset); ByteBuffer lastComment = newComment.slice(); ByteBuffer lastHeaderBuffer = startCreateBasicSecondPage( originalHeaderSizes, lastPageCommentPacketSize, newSecondPageDataLength, secondPageHeader, lastComment); //Now find the setupheader which is on a different page raf.seek(originalHeaderSizes.getSetupHeaderStartPosition()); //Add setup Header and Extra Packets (although it will fit in this page, it may be over multiple pages in its original form //so need to use this function to convert to raw data byte[] setupHeaderData = reader.convertToVorbisSetupHeaderPacketAndAdditionalPackets(originalHeaderSizes.getSetupHeaderStartPosition(), raf); lastHeaderBuffer.put(setupHeaderData); //Page Sequence No lastHeaderBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, pageSequence); //Set Header Flag to indicate continuous (contains end of comment) lastHeaderBuffer.put(OggPageHeader.FIELD_HEADER_TYPE_FLAG_POS, OggPageHeader.HeaderTypeFlag.CONTINUED_PACKET.getFileValue()); calculateChecksumOverPage(lastHeaderBuffer); rafTemp.getChannel().write(lastHeaderBuffer); } //Write the rest of the original file writeRemainingPages(pageSequence, raf, rafTemp); }
CommentHeader extends over multiple pages OR Comment Header doesnt but it's got larger causing some extra packets to be shifted onto another page. @param originalHeaderSizes @param newCommentLength @param secondPageHeader @param newComment @param raf @param rafTemp @throws IOException @throws CannotReadException @throws CannotWriteException
OggVorbisTagWriter::replacePagesAndRenumberPageSeqs
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
public void writeRemainingPages(int pageSequence, RandomAccessFile raf, RandomAccessFile rafTemp) throws IOException, CannotReadException, CannotWriteException { long startAudio = raf.getFilePointer(); long startAudioWritten = rafTemp.getFilePointer(); //TODO there is a risk we wont have enough memory to create these buffers ByteBuffer bb = ByteBuffer.allocate((int) (raf.length() - raf.getFilePointer())); ByteBuffer bbTemp = ByteBuffer.allocate((int)(raf.length() - raf.getFilePointer())); //Read in the rest of the data into bytebuffer and rewind it to start raf.getChannel().read(bb); bb.rewind(); long bytesToDiscard = 0; while(bb.hasRemaining()) { OggPageHeader nextPage=null; try { nextPage = OggPageHeader.read(bb); } catch(CannotReadException cre) { //Go back to where were bb.position(bb.position() - OggPageHeader.CAPTURE_PATTERN.length); //#117:Ogg file with invalid ID3v1 tag at end remove and save if(Utils.readThreeBytesAsChars(bb).equals(AbstractID3v1Tag.TAG)) { bytesToDiscard = bb.remaining() + AbstractID3v1Tag.TAG.length(); break; } else { throw cre; } } //Create buffer large enough for next page (header and data) and set byte order to LE so we can use //putInt method ByteBuffer nextPageHeaderBuffer = ByteBuffer.allocate(nextPage.getRawHeaderData().length + nextPage.getPageLength()); nextPageHeaderBuffer.order(ByteOrder.LITTLE_ENDIAN); nextPageHeaderBuffer.put(nextPage.getRawHeaderData()); ByteBuffer data = bb.slice(); data.limit(nextPage.getPageLength()); nextPageHeaderBuffer.put(data); nextPageHeaderBuffer.putInt(OggPageHeader.FIELD_PAGE_SEQUENCE_NO_POS, ++pageSequence); calculateChecksumOverPage(nextPageHeaderBuffer); bb.position(bb.position() + nextPage.getPageLength()); nextPageHeaderBuffer.rewind(); bbTemp.put(nextPageHeaderBuffer); } //Now just write as a single IO operation bbTemp.flip(); rafTemp.getChannel().write(bbTemp); //Check we have written all the data (minus any invalid Tag at end) if ((raf.length() - startAudio) != ((rafTemp.length() + bytesToDiscard) - startAudioWritten)) { throw new CannotWriteException("File written counts don't match, file not written:" +"origAudioLength:"+(raf.length() - startAudio) +":newAudioLength:"+((rafTemp.length() + bytesToDiscard) - startAudioWritten) +":bytesDiscarded:"+bytesToDiscard); } }
Write all the remaining pages as they are except that the page sequence needs to be modified. @param pageSequence @param raf @param rafTemp @throws IOException @throws CannotReadException @throws CannotWriteException
OggVorbisTagWriter::writeRemainingPages
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
private byte[] createSegmentTable(int newCommentLength, int setupHeaderLength, List<OggPageHeader.PacketStartAndLength> extraPackets) { logger.finest("Create SegmentTable CommentLength:" + newCommentLength + ":SetupHeaderLength:" + setupHeaderLength); ByteArrayOutputStream resultBaos = new ByteArrayOutputStream(); byte[] newStart; byte[] restShouldBe; byte[] nextPacket; //Vorbis Comment if (setupHeaderLength == 0) { //Comment Stream continues onto next page so last lacing value can be 255 newStart = createSegments(newCommentLength, false); return newStart; } else { //Comment Stream finishes on this page so if is a multiple of 255 //have to add an extra entry. newStart = createSegments(newCommentLength, true); } //Setup Header, should be closed if (extraPackets.size() > 0) { restShouldBe = createSegments(setupHeaderLength, true); } //.. continue sonto next page else { restShouldBe = createSegments(setupHeaderLength, false); } logger.finest("Created " + newStart.length + " segments for header"); logger.finest("Created " + restShouldBe.length + " segments for setup"); try { resultBaos.write(newStart); resultBaos.write(restShouldBe); if (extraPackets.size() > 0) { //Packets are being copied literally not converted from a length, so always pass //false parameter, TODO is this statement correct logger.finer("Creating segments for " + extraPackets.size() + " packets"); for (OggPageHeader.PacketStartAndLength packet : extraPackets) { nextPacket = createSegments(packet.getLength(), false); resultBaos.write(nextPacket); } } } catch (IOException ioe) { throw new RuntimeException("Unable to create segment table:" + ioe.getMessage()); } return resultBaos.toByteArray(); }
This method creates a new segment table for the second page (header). @param newCommentLength The length of the Vorbis Comment @param setupHeaderLength The length of Setup Header, zero if comment String extends over multiple pages and this is not the last page. @param extraPackets If there are packets immediately after setup header in same page, they need including in the segment table @return new segment table.
OggVorbisTagWriter::createSegmentTable
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
private byte[] createSegmentTable(int setupHeaderLength, List<OggPageHeader.PacketStartAndLength> extraPackets) { ByteArrayOutputStream resultBaos = new ByteArrayOutputStream(); byte[] restShouldBe; byte[] nextPacket; //Setup Header restShouldBe = createSegments(setupHeaderLength, true); try { resultBaos.write(restShouldBe); if (extraPackets.size() > 0) { //Packets are being copied literally not converted from a length, so always pass //false parameter, TODO is this statement correct for (OggPageHeader.PacketStartAndLength packet : extraPackets) { nextPacket = createSegments(packet.getLength(), false); resultBaos.write(nextPacket); } } } catch (IOException ioe) { throw new RuntimeException("Unable to create segment table:" + ioe.getMessage()); } return resultBaos.toByteArray(); }
This method creates a new segment table for the second half of setup header @param setupHeaderLength The length of Setup Header, zero if comment String extends over multiple pages and this is not the last page. @param extraPackets If there are packets immediately after setup header in same page, they need including in the segment table @return new segment table.
OggVorbisTagWriter::createSegmentTable
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
private boolean isCommentAndSetupHeaderFitsOnASinglePage(int commentLength, int setupHeaderLength, List<OggPageHeader.PacketStartAndLength> extraPacketList) { int totalDataSize = 0; if (commentLength == 0) { totalDataSize++; } else { totalDataSize = (commentLength / OggPageHeader.MAXIMUM_SEGMENT_SIZE) + 1; if (commentLength % OggPageHeader.MAXIMUM_SEGMENT_SIZE == 0) { totalDataSize++; } } logger.finest("Require:" + totalDataSize + " segments for comment"); if (setupHeaderLength == 0) { totalDataSize++; } else { totalDataSize += (setupHeaderLength / OggPageHeader.MAXIMUM_SEGMENT_SIZE) + 1; if (setupHeaderLength % OggPageHeader.MAXIMUM_SEGMENT_SIZE == 0) { totalDataSize++; } } logger.finest("Require:" + totalDataSize + " segments for comment plus setup"); for (OggPageHeader.PacketStartAndLength extraPacket : extraPacketList) { if (extraPacket.getLength() == 0) { totalDataSize++; } else { totalDataSize += (extraPacket.getLength() / OggPageHeader.MAXIMUM_SEGMENT_SIZE) + 1; if (extraPacket.getLength() % OggPageHeader.MAXIMUM_SEGMENT_SIZE == 0) { totalDataSize++; } } } logger.finest("Total No Of Segment If New Comment And Header Put On One Page:" + totalDataSize); return totalDataSize <= OggPageHeader.MAXIMUM_NO_OF_SEGMENT_SIZE; }
@param commentLength @param setupHeaderLength @param extraPacketList @return true if there is enough room to fit the comment and the setup headers on one page taking into account the maximum no of segments allowed per page and zero lacing values.
OggVorbisTagWriter::isCommentAndSetupHeaderFitsOnASinglePage
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/OggVorbisTagWriter.java
Apache-2.0
public static OggPageHeader read(ByteBuffer byteBuffer) throws IOException, CannotReadException { //byteBuffer int start = byteBuffer.position(); logger.fine("Trying to read OggPage at:" + start); byte[] b = new byte[OggPageHeader.CAPTURE_PATTERN.length]; byteBuffer.get(b); if (!(Arrays.equals(b, OggPageHeader.CAPTURE_PATTERN))) { throw new CannotReadException(ErrorMessage.OGG_HEADER_CANNOT_BE_FOUND.getMsg(new String(b))); } byteBuffer.position(start + OggPageHeader.FIELD_PAGE_SEGMENTS_POS); int pageSegments = byteBuffer.get() & 0xFF; //unsigned byteBuffer.position(start); b = new byte[OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageSegments]; byteBuffer.get(b); OggPageHeader pageHeader = new OggPageHeader(b); //Now just after PageHeader, ready for Packet Data return pageHeader; }
Read next PageHeader from Buffer @param byteBuffer @return @throws IOException @throws CannotReadException
OggPageHeader::read
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
Apache-2.0
public static OggPageHeader read(RandomAccessFile raf) throws IOException, CannotReadException { long start = raf.getFilePointer(); logger.fine("Trying to read OggPage at:" + start); byte[] b = new byte[OggPageHeader.CAPTURE_PATTERN.length]; raf.read(b); if (!(Arrays.equals(b, OggPageHeader.CAPTURE_PATTERN))) { raf.seek(start); if(AbstractID3v2Tag.isId3Tag(raf)) { logger.warning(ErrorMessage.OGG_CONTAINS_ID3TAG.getMsg(raf.getFilePointer() - start)); raf.read(b); if ((Arrays.equals(b, OggPageHeader.CAPTURE_PATTERN))) { //Go to the end of the ID3 header start=raf.getFilePointer() - OggPageHeader.CAPTURE_PATTERN.length; } } else { throw new CannotReadException(ErrorMessage.OGG_HEADER_CANNOT_BE_FOUND.getMsg(new String(b))); } } raf.seek(start + OggPageHeader.FIELD_PAGE_SEGMENTS_POS); int pageSegments = raf.readByte() & 0xFF; //unsigned raf.seek(start); b = new byte[OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageSegments]; raf.read(b); OggPageHeader pageHeader = new OggPageHeader(b); pageHeader.setStartByte(start); //Now just after PageHeader, ready for Packet Data return pageHeader; }
Read next PageHeader from file @param raf @return @throws IOException @throws CannotReadException
OggPageHeader::read
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
Apache-2.0
public boolean isLastPacketIncomplete() { return lastPacketIncomplete; }
@return true if the last packet on this page extends to the next page
OggPageHeader::isLastPacketIncomplete
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
Apache-2.0
public List<PacketStartAndLength> getPacketList() { return packetList; }
@return a list of packet start position and size within this page.
OggPageHeader::getPacketList
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
Apache-2.0
public byte[] getRawHeaderData() { return rawHeaderData; }
@return the raw header data that this pageheader is derived from
OggPageHeader::getRawHeaderData
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
Apache-2.0
public long getStartByte() { return startByte; }
Startbyte of this pageHeader in the file This is useful for Ogg files that contain unsupported additional data at the start of the file such as ID3 data
OggPageHeader::getStartByte
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
Apache-2.0
public byte getFileValue() { return fileValue; }
@return the value that should be written to file to enable this flag
HeaderTypeFlag::getFileValue
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/ogg/util/OggPageHeader.java
Apache-2.0
public ExtDouble(byte[] rawData) { _rawData = rawData; }
Constructor. @param rawData A 10-byte array representing the number in the sequence in which it was stored.
ExtDouble::ExtDouble
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/ExtDouble.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/ExtDouble.java
Apache-2.0
public double toDouble() { int sign; int exponent; long mantissa = 0; // Extract the sign bit. sign = _rawData[0] >> 7; // Extract the exponent. It's stored with a // bias of 16383, so subtract that off. // Also, the mantissa is between 1 and 2 (i.e., // all but 1 digits are to the right of the binary point, so // we take 62 (not 63: see below) off the exponent for that. exponent = (_rawData[0] << 8) | _rawData[1]; exponent &= 0X7FFF; // strip off sign bit exponent -= (16383 + 62); // 1 is added to the "real" exponent // Extract the mantissa. It's 64 bits of unsigned // data, but a long is a signed number, so we have to // discard the LSB. We'll lose more than that converting // to double anyway. This division by 2 is the reason for // adding an extra 1 to the exponent above. int shifter = 55; for (int i = 2; i < 9; i++) { mantissa |= ((long) _rawData[i] & 0XFFL) << shifter; shifter -= 8; } mantissa |= _rawData[9] >>> 1; // Now put it together in a floating point number. double val = Math.pow(2, exponent); val *= mantissa; if (sign != 0) { val = -val; } return val; }
Convert the value to a Java double. This results in loss of precision. If the number is out of range, results aren't guaranteed.
ExtDouble::toDouble
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/ExtDouble.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/ExtDouble.java
Apache-2.0
public AiffTag read(Path file) throws CannotReadException, IOException { try(FileChannel fc = FileChannel.open(file)) { AiffAudioHeader aiffAudioHeader = new AiffAudioHeader(); AiffTag aiffTag = new AiffTag(); final AiffFileHeader fileHeader = new AiffFileHeader(); fileHeader.readHeader(fc, aiffAudioHeader, file.toString()); while (fc.position() < fc.size()) { if (!readChunk(fc, aiffTag, file.toString())) { logger.severe(file + " UnableToReadProcessChunk"); break; } } if (aiffTag.getID3Tag() == null) { aiffTag.setID3Tag(AiffTag.createDefaultID3Tag()); } return aiffTag; } }
Read editable Metadata @param file @return @throws CannotReadException @throws IOException
AiffTagReader::read
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagReader.java
Apache-2.0
private boolean readChunk(FileChannel fc, AiffTag aiffTag, String fileName) throws IOException { logger.config(fileName + " Reading Tag Chunk"); ChunkHeader chunkHeader = new ChunkHeader(ByteOrder.BIG_ENDIAN); if (!chunkHeader.readHeader(fc)) { return false; } logger.config(fileName + " Reading Chunk:" + chunkHeader.getID() + ":starting at:" + Hex.asDecAndHex(chunkHeader.getStartLocationInFile()) + ":sizeIncHeader:" + (chunkHeader.getSize() + ChunkHeader.CHUNK_HEADER_SIZE)); long startLocationOfId3TagInFile = fc.position(); AiffChunkType chunkType = AiffChunkType.get(chunkHeader.getID()); if (chunkType!=null && chunkType== AiffChunkType.TAG && chunkHeader.getSize() > 0) { ByteBuffer chunkData = readChunkDataIntoBuffer(fc, chunkHeader); aiffTag.addChunkSummary(new ChunkSummary(chunkHeader.getID(), chunkHeader.getStartLocationInFile(), chunkHeader.getSize())); //If we havent already for an ID3 Tag if(aiffTag.getID3Tag()==null) { Chunk chunk = new ID3Chunk(chunkHeader,chunkData, aiffTag); chunk.readChunk(); aiffTag.setExistingId3Tag(true); aiffTag.getID3Tag().setStartLocationInFile(startLocationOfId3TagInFile); aiffTag.getID3Tag().setEndLocationInFile(fc.position()); } //else otherwise we discard because the first one found is the one that will be used by other apps { logger.warning(fileName + " Ignoring ID3Tag because already have one:" + chunkHeader.getID() + ":" + chunkHeader.getStartLocationInFile() + Hex.asDecAndHex(chunkHeader.getStartLocationInFile() - 1) + ":sizeIncHeader:" + (chunkHeader.getSize() + ChunkHeader.CHUNK_HEADER_SIZE)); } } //Special handling to recognise ID3Tags written on odd boundary because original preceding chunk odd length but //didn't write padding byte else if(chunkType!=null && chunkType== AiffChunkType.CORRUPT_TAG_LATE) { logger.warning(fileName + "Found Corrupt ID3 Chunk, starting at Odd Location:" + chunkHeader.getID() + ":" + Hex.asDecAndHex(chunkHeader.getStartLocationInFile() - 1) + ":sizeIncHeader:"+ (chunkHeader.getSize() + ChunkHeader.CHUNK_HEADER_SIZE)); //We only want to know if first metadata tag is misaligned if(aiffTag.getID3Tag()==null) { aiffTag.setIncorrectlyAlignedTag(true); } fc.position(fc.position() - (ChunkHeader.CHUNK_HEADER_SIZE + 1)); return true; } //Other Special handling for ID3Tags else if(chunkType!=null && chunkType== AiffChunkType.CORRUPT_TAG_EARLY) { logger.warning(fileName + " Found Corrupt ID3 Chunk, starting at Odd Location:" + chunkHeader.getID() + ":" + Hex.asDecAndHex(chunkHeader.getStartLocationInFile()) + ":sizeIncHeader:"+ (chunkHeader.getSize() + ChunkHeader.CHUNK_HEADER_SIZE)); //We only want to know if first metadata tag is misaligned if(aiffTag.getID3Tag()==null) { aiffTag.setIncorrectlyAlignedTag(true); } fc.position(fc.position() - (ChunkHeader.CHUNK_HEADER_SIZE - 1)); return true; } else { logger.config(fileName + "Skipping Chunk:" + chunkHeader.getID() + ":" + chunkHeader.getSize()); aiffTag.addChunkSummary(new ChunkSummary(chunkHeader.getID(), chunkHeader.getStartLocationInFile(), chunkHeader.getSize())); fc.position(fc.position() + chunkHeader.getSize()); } IffHeaderChunk.ensureOnEqualBoundary(fc, chunkHeader); return true; }
Reads an AIFF ID3 Chunk. @return {@code false}, if we were not able to read a valid chunk id
AiffTagReader::readChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagReader.java
Apache-2.0
private AiffTag getExistingMetadata(Path file) throws IOException, CannotWriteException { try { //Find AiffTag (if any) AiffTagReader im = new AiffTagReader(); return im.read(file); } catch (CannotReadException ex) { throw new CannotWriteException(file + " Failed to read file"); } }
Read existing metadata @param file @return tags within Tag wrapper @throws IOException @throws CannotWriteException
AiffTagWriter::getExistingMetadata
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private ChunkHeader seekToStartOfMetadata(FileChannel fc, AiffTag existingTag, String fileName) throws IOException, CannotWriteException { fc.position(existingTag.getStartLocationInFileOfId3Chunk()); final ChunkHeader chunkHeader = new ChunkHeader(ByteOrder.BIG_ENDIAN); chunkHeader.readHeader(fc); fc.position(fc.position() - ChunkHeader.CHUNK_HEADER_SIZE); if(!AiffChunkType.TAG.getCode().equals(chunkHeader.getID())) { throw new CannotWriteException(fileName + " Unable to find ID3 chunk at expected location:"+existingTag.getStartLocationInFileOfId3Chunk()); } return chunkHeader; }
Seek in file to start of LIST Metadata chunk @param fc @param existingTag @throws IOException @throws CannotWriteException
AiffTagWriter::seekToStartOfMetadata
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private boolean isAtEndOfFileAllowingForPaddingByte(AiffTag existingTag, FileChannel fc) throws IOException { return ( ( existingTag.getID3Tag().getEndLocationInFile() == fc.size() ) || ( Utils.isOddLength(existingTag.getID3Tag().getEndLocationInFile()) && existingTag.getID3Tag().getEndLocationInFile() + 1 == fc.size() ) ); }
@param existingTag @param fc @return true if at end of file (also take into account padding byte) @throws IOException
AiffTagWriter::isAtEndOfFileAllowingForPaddingByte
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
public void delete(final Tag tag, Path file) throws CannotWriteException { try(FileChannel fc = FileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.READ)) { logger.severe(file +" Deleting tag from file"); final AiffTag existingTag = getExistingMetadata(file); if (existingTag.isExistingId3Tag() && existingTag.getID3Tag().getStartLocationInFile() != null) { ChunkHeader chunkHeader = seekToStartOfMetadata(fc, existingTag, file.toString()); if (isAtEndOfFileAllowingForPaddingByte(existingTag, fc)) { logger.severe(file + " Setting new length to:" + (existingTag.getStartLocationInFileOfId3Chunk())); fc.truncate(existingTag.getStartLocationInFileOfId3Chunk()); } else { logger.severe(file + " Deleting tag chunk"); deleteTagChunk(fc, existingTag, chunkHeader,file.toString()); } rewriteRiffHeaderSize(fc); } logger.severe(file + " Deleted tag from file"); } catch(IOException ioe) { throw new CannotWriteException(file + ":" + ioe.getMessage()); } }
Delete given {@link Tag} from file. @param tag tag, must be instance of {@link AiffTag} @param file @throws java.io.IOException @throws org.jaudiotagger.audio.exceptions.CannotWriteException
AiffTagWriter::delete
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private void deleteTagChunk(FileChannel fc, final AiffTag existingTag, final ChunkHeader tagChunkHeader, String fileName) throws IOException { int lengthTagChunk = (int) tagChunkHeader.getSize() + ChunkHeader.CHUNK_HEADER_SIZE; if(Utils.isOddLength(lengthTagChunk)) { if(existingTag.getStartLocationInFileOfId3Chunk() + lengthTagChunk <fc.size()) { lengthTagChunk++; } } final long newLength = fc.size() - lengthTagChunk; logger.severe(fileName + " Size of id3 chunk to delete is:"+lengthTagChunk+":Location:"+existingTag.getStartLocationInFileOfId3Chunk()); // position for reading after the id3 tag fc.position(existingTag.getStartLocationInFileOfId3Chunk() + lengthTagChunk); deleteTagChunkUsingSmallByteBufferSegments(existingTag, fc, newLength, lengthTagChunk); // truncate the file after the last chunk logger.severe(fileName + " Setting new length to:" + newLength); fc.truncate(newLength); }
<p>Deletes the given ID3-{@link Tag}/{@link Chunk} from the file by moving all following chunks up.</p> <pre> [chunk][-id3-][chunk][chunk] [chunk] &lt;&lt;--- [chunk][chunk] [chunk][chunk][chunk] </pre> @param fc, filechannel @param existingTag existing tag @param tagChunkHeader existing chunk header for the tag @throws IOException if something goes wrong
AiffTagWriter::deleteTagChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private void deleteRemainderOfFile(FileChannel fc, final AiffTag existingTag, String fileName) throws IOException { ChunkSummary precedingChunk = AiffChunkSummary.getChunkBeforeStartingMetadataTag(existingTag); if(!Utils.isOddLength(precedingChunk.getEndLocation())) { logger.severe(fileName + " Truncating corrupted ID3 tags from:" + (existingTag.getStartLocationInFileOfId3Chunk() - 1)); fc.truncate(existingTag.getStartLocationInFileOfId3Chunk() - 1); } else { logger.severe(fileName + " Truncating corrupted ID3 tags from:" + (existingTag.getStartLocationInFileOfId3Chunk())); fc.truncate(existingTag.getStartLocationInFileOfId3Chunk()); } }
If Metadata tags are corrupted and no other tags later in the file then just truncate ID3 tags and start again @param fc @param existingTag @throws IOException
AiffTagWriter::deleteRemainderOfFile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private void deleteTagChunkUsingChannelTransfer(final AiffTag existingTag, final FileChannel channel, final long newLength) throws IOException { long read; //Read from just after the ID3Chunk into the channel at where the ID3 chunk started, should usually only require one transfer //but put into loop in case multiple calls are required for (long position = existingTag.getStartLocationInFileOfId3Chunk(); (read = channel.transferFrom(channel, position, newLength - position)) < newLength-position; position += read);//is this problem if loop called more than once do we need to update position of channel to modify //where write to ? }
The following seems to work on Windows but hangs on OSX! Bug is filed <a href="https://bugs.openjdk.java.net/browse/JDK-8140241">here</a>. @param existingTag existing tag @param channel channel @param newLength new length @throws IOException if something goes wrong
AiffTagWriter::deleteTagChunkUsingChannelTransfer
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
public void write(final Tag tag, Path file) throws CannotWriteException { logger.severe(file + " Writing Aiff tag to file"); AiffTag existingTag = null; try { existingTag = getExistingMetadata(file); } catch(IOException ioe) { throw new CannotWriteException(file + ":" + ioe.getMessage()); } try(FileChannel fc = FileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.READ)) { long existingFileLength = fc.size(); final AiffTag aiffTag = (AiffTag) tag; final ByteBuffer bb = convert(aiffTag, existingTag); //Replacing ID3 tag if (existingTag.isExistingId3Tag() && existingTag.getID3Tag().getStartLocationInFile() != null) { //Usual case if (!existingTag.isIncorrectlyAlignedTag()) { final ChunkHeader chunkHeader = seekToStartOfMetadata(fc, existingTag, file.toString()); logger.info(file + "Current Space allocated:" + existingTag.getSizeOfID3TagOnly() + ":NewTagRequires:" + bb.limit()); //Usual case ID3 is last chunk if (isAtEndOfFileAllowingForPaddingByte(existingTag, fc)) { writeDataToFile(fc, bb); } //Unusual Case where ID3 is not last chunk else { deleteTagChunk(fc, existingTag, chunkHeader, file.toString()); fc.position(fc.size()); writeExtraByteIfChunkOddSize(fc, fc.size()); writeDataToFile(fc, bb); } } //Existing ID3 tag is incorrectly aligned so if we can lets delete it and any subsequentially added //ID3 tags as we only want one ID3 tag. else if (AiffChunkSummary.isOnlyMetadataTagsAfterStartingMetadataTag(existingTag)) { deleteRemainderOfFile(fc, existingTag, file.toString()); fc.position(fc.size()); writeExtraByteIfChunkOddSize(fc, fc.size()); writeDataToFile(fc, bb); } else { throw new CannotWriteException(file + " Metadata tags are corrupted and not at end of file so cannot be fixed"); } } //New Tag else { fc.position(fc.size()); if (Utils.isOddLength(fc.size())) { fc.write(ByteBuffer.allocateDirect(1)); } writeDataToFile(fc, bb); } if (existingFileLength != fc.size()) { rewriteRiffHeaderSize(fc); } } catch(AccessDeniedException ade) { throw new NoWritePermissionsException(file + ":" + ade.getMessage()); } catch(IOException ioe) { throw new CannotWriteException(file + ":" + ioe.getMessage()); } }
@param tag @param file @throws CannotWriteException @throws IOException
AiffTagWriter::write
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private void rewriteRiffHeaderSize(FileChannel fc) throws IOException { fc.position(IffHeaderChunk.SIGNATURE_LENGTH); ByteBuffer bb = ByteBuffer.allocateDirect(IffHeaderChunk.SIZE_LENGTH); bb.order(ByteOrder.BIG_ENDIAN); int size = ((int) fc.size()) - SIGNATURE_LENGTH - SIZE_LENGTH; bb.putInt(size); bb.flip(); fc.write(bb); }
Rewrite RAF header to reflect new file length @param fc @throws IOException
AiffTagWriter::rewriteRiffHeaderSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private void writeDataToFile(FileChannel fc, final ByteBuffer bb) throws IOException { final ChunkHeader ch = new ChunkHeader(ByteOrder.BIG_ENDIAN); ch.setID(AiffChunkType.TAG.getCode()); ch.setSize(bb.limit()); fc.write(ch.writeHeader()); fc.write(bb); writeExtraByteIfChunkOddSize(fc, bb.limit() ); }
Writes data as a {@link org.jaudiotagger.audio.aiff.chunk.AiffChunkType#TAG} chunk to the file. @param fc filechannel @param bb data to write @throws IOException
AiffTagWriter::writeDataToFile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
private void writeExtraByteIfChunkOddSize(FileChannel fc, long size ) throws IOException { if(Utils.isOddLength(size)) { fc.write(ByteBuffer.allocateDirect(1)); } }
Chunk must also start on an even byte so if our chunksize is odd we need to write another byte. This should never happen as ID3Tag is now amended to ensure always write padding byte if needed to stop it being odd sized but we keep check in just incase. @param fc @param size @throws IOException
AiffTagWriter::writeExtraByteIfChunkOddSize
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
public ByteBuffer convert(final AiffTag tag, AiffTag existingTag) throws UnsupportedEncodingException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); long existingTagSize = existingTag.getSizeOfID3TagOnly(); //If existingTag is uneven size lets make it even if( existingTagSize > 0) { if((existingTagSize & 1)!=0) { existingTagSize++; } } //Write Tag to buffer tag.getID3Tag().write(baos, (int)existingTagSize); //If the tag is now odd because we needed to increase size and the data made it odd sized //we redo adding a padding byte to make it even if((baos.toByteArray().length & 1)!=0) { int newSize = baos.toByteArray().length + 1; baos = new ByteArrayOutputStream(); tag.getID3Tag().write(baos, newSize); } final ByteBuffer buf = ByteBuffer.wrap(baos.toByteArray()); buf.rewind(); return buf; } catch (IOException ioe) { //Should never happen as not writing to file at this point throw new RuntimeException(ioe); } }
Converts tag to {@link ByteBuffer}. @param tag tag @param existingTag @return byte buffer containing the tag data @throws UnsupportedEncodingException
AiffTagWriter::convert
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffTagWriter.java
Apache-2.0
public void setTimestamp(Date d) { timestamp = d; }
Set the timestamp.
Endian::setTimestamp
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public AiffType getFileType() { return fileType; }
Return the file type (AIFF or AIFC)
Endian::getFileType
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void setFileType(AiffType typ) { fileType = typ; }
Set the file type (AIFF or AIFC)
Endian::setFileType
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public String getAuthor() { return author; }
Return the author
Endian::getAuthor
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void setAuthor(String a) { author = a; }
Set the author
Endian::setAuthor
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void setName(String n) { name = n; }
Set the name
Endian::setName
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public String getCopyright() { return copyright; }
Return the copyright. May be null.
Endian::getCopyright
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void setCopyright(String c) { copyright = c; }
Set the copyright
Endian::setCopyright
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public Endian getEndian() { return endian; }
Return endian status (big or little)
Endian::getEndian
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void setEndian(Endian e) { endian = e; }
Set endian status (big or little)
Endian::setEndian
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public List<String> getApplicationIdentifiers() { return applicationIdentifiers; }
Return list of all application identifiers
Endian::getApplicationIdentifiers
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void addApplicationIdentifier(String id) { applicationIdentifiers.add(id); }
Add an application identifier. There can be any number of these.
Endian::addApplicationIdentifier
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public List<String> getAnnotations() { return annotations; }
Return list of all annotations
Endian::getAnnotations
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void addAnnotation(String a) { annotations.add(a); }
Add an annotation. There can be any number of these.
Endian::addAnnotation
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public List<String> getComments() { return comments; }
Return list of all comments
Endian::getComments
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public void addComment(String c) { comments.add(c); }
Add a comment. There can be any number of these.
Endian::addComment
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffAudioHeader.java
Apache-2.0
public long readHeader(FileChannel fc, final AiffAudioHeader aiffAudioHeader, String fileName) throws IOException, CannotReadException { final ByteBuffer headerData = ByteBuffer.allocateDirect(HEADER_LENGTH); headerData.order(BIG_ENDIAN); final int bytesRead = fc.read(headerData); headerData.position(0); if (bytesRead < HEADER_LENGTH) { throw new IOException(fileName + " AIFF:Unable to read required number of databytes read:" + bytesRead + ":required:" + HEADER_LENGTH); } final String signature = Utils.readFourBytesAsChars(headerData); if(FORM.equals(signature)) { // read chunk size final long chunkSize = headerData.getInt(); logger.severe(fileName + " Reading AIFF header size:" + Hex.asDecAndHex(chunkSize)); readFileType(headerData, aiffAudioHeader); // subtract the file type length from the chunk size to get remaining number of bytes return chunkSize - TYPE_LENGTH; } else { throw new CannotReadException(fileName + "Not an AIFF file: incorrect signature " + signature); } }
Reads the file header and registers the data (file type) with the given header. @param fc random access file @param aiffAudioHeader the {@link org.jaudiotagger.audio.AudioHeader} we set the read data to @param fileName @return the number of bytes in the FORM chunk, i.e. the size of the payload @throws IOException @throws CannotReadException if the file is not a valid AIFF file
AiffFileHeader::readHeader
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffFileHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffFileHeader.java
Apache-2.0
private void readFileType(final ByteBuffer bytes, final AiffAudioHeader aiffAudioHeader) throws IOException, CannotReadException { final String type = Utils.readFourBytesAsChars(bytes); if (AIFF.getCode().equals(type)) { aiffAudioHeader.setFileType(AIFF); } else if (AIFC.getCode().equals(type)) { aiffAudioHeader.setFileType(AIFC); } else { throw new CannotReadException("Invalid AIFF file: Incorrect file type info " + type); } }
Reads the file type ({@link AiffType}). @throws CannotReadException if the file type is not supported
AiffFileHeader::readFileType
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffFileHeader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffFileHeader.java
Apache-2.0
public static Date timestampToDate(long timestamp) { Calendar cal = Calendar.getInstance(); cal.set(1904, 0, 1, 0, 0, 0); // If we add the seconds directly, we'll truncate the long // value when converting to int. So convert to hours plus // residual seconds. int hours = (int) (timestamp / 3600); int seconds = (int) (timestamp - (long) hours * 3600L); cal.add(Calendar.HOUR_OF_DAY, hours); cal.add(Calendar.SECOND, seconds); Date dat = cal.getTime(); return dat; }
Converts a Macintosh-style timestamp (seconds since January 1, 1904) into a Java date. The timestamp is treated as a time in the default localization. Depending on that localization, there may be some variation in the exact hour of the date returned, e.g., due to daylight savings time.
AiffUtil::timestampToDate
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffUtil.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffUtil.java
Apache-2.0
public static String formatDate(Date dat) { return dateFmt.format(dat); }
Format a date as text
AiffUtil::formatDate
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffUtil.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffUtil.java
Apache-2.0
private void calculateBitRate(GenericAudioHeader info) throws CannotReadException { if(info.getAudioDataLength()!=null) { info.setBitRate((int)(Math.round(info.getAudioDataLength() * Utils.BITS_IN_BYTE_MULTIPLIER / (info.getPreciseTrackLength() * Utils.KILOBYTE_MULTIPLIER)))); } }
Calculate bitrate, done it here because requires data from multiple chunks @param info @throws CannotReadException
AiffInfoReader::calculateBitRate
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffInfoReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffInfoReader.java
Apache-2.0
private boolean readChunk(FileChannel fc, AiffAudioHeader aiffAudioHeader, String fileName) throws IOException, CannotReadException { logger.config(fileName + " Reading Info Chunk"); final Chunk chunk; final ChunkHeader chunkHeader = new ChunkHeader(ByteOrder.BIG_ENDIAN); if (!chunkHeader.readHeader(fc)) { return false; } logger.config(fileName + "Reading Next Chunk:" + chunkHeader.getID() + ":starting at:" + chunkHeader.getStartLocationInFile() + ":sizeIncHeader:" + (chunkHeader.getSize() + ChunkHeader.CHUNK_HEADER_SIZE)); chunk = createChunk(fc, chunkHeader, aiffAudioHeader); if (chunk != null) { if (!chunk.readChunk()) { logger.severe(fileName + "ChunkReadFail:" + chunkHeader.getID()); return false; } } else { if(chunkHeader.getSize() < 0) { String msg = fileName + " Not a valid header, unable to read a sensible size:Header" + chunkHeader.getID()+"Size:"+chunkHeader.getSize(); logger.severe(msg); throw new CannotReadException(msg); } fc.position(fc.position() + chunkHeader.getSize()); } IffHeaderChunk.ensureOnEqualBoundary(fc, chunkHeader); return true; }
Reads an AIFF Chunk. @return {@code false}, if we were not able to read a valid chunk id
AiffInfoReader::readChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffInfoReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffInfoReader.java
Apache-2.0
private Chunk createChunk(FileChannel fc, final ChunkHeader chunkHeader, AiffAudioHeader aiffAudioHeader) throws IOException { final AiffChunkType chunkType = AiffChunkType.get(chunkHeader.getID()); Chunk chunk; if (chunkType != null) { switch (chunkType) { case FORMAT_VERSION: chunk = new FormatVersionChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case APPLICATION: chunk = new ApplicationChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case COMMON: chunk = new CommonChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case COMMENTS: chunk = new CommentsChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case NAME: chunk = new NameChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case AUTHOR: chunk = new AuthorChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case COPYRIGHT: chunk = new CopyrightChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case ANNOTATION: chunk = new AnnotationChunk(chunkHeader, readChunkDataIntoBuffer(fc,chunkHeader), aiffAudioHeader); break; case SOUND: //Dont need to read chunk itself just need size aiffAudioHeader.setAudioDataLength(chunkHeader.getSize()); aiffAudioHeader.setAudioDataStartPosition(fc.position()); aiffAudioHeader.setAudioDataEndPosition(fc.position() + chunkHeader.getSize()); chunk = null; break; default: chunk = null; } } else { chunk = null; } return chunk; }
Create a chunk. May return {@code null}, if the chunk is not of a valid type. @param fc @param chunkHeader @param aiffAudioHeader @return @throws IOException
AiffInfoReader::createChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/AiffInfoReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/AiffInfoReader.java
Apache-2.0
public static boolean isOnlyMetadataTagsAfterStartingMetadataTag(AiffTag tag) { boolean firstId3Tag = false; for(ChunkSummary cs:tag.getChunkSummaryList()) { if(firstId3Tag) { if(!cs.getChunkId().equals(AiffChunkType.TAG.getCode())) { return false; } } else { if (cs.getFileStartLocation() == tag.getStartLocationInFileOfId3Chunk()) { //Found starting point firstId3Tag = true; } } } //Should always be true but this is to protect against something gone wrong return firstId3Tag; }
Checks that there are only id3 tags after the currently selected id3tag because this means its safe to truncate the remainder of the file. @param tag @return
AiffChunkSummary::isOnlyMetadataTagsAfterStartingMetadataTag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkSummary.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkSummary.java
Apache-2.0
public static ChunkSummary getChunkBeforeStartingMetadataTag(AiffTag tag) { for(int i=0;i < tag.getChunkSummaryList().size(); i++) { ChunkSummary cs = tag.getChunkSummaryList().get(i); if (cs.getFileStartLocation() == tag.getStartLocationInFileOfId3Chunk()) { return tag.getChunkSummaryList().get(i - 1); } } return null; }
Get chunk before starting metadata tag @param tag @return
AiffChunkSummary::getChunkBeforeStartingMetadataTag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkSummary.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkSummary.java
Apache-2.0
protected ByteBuffer readChunkDataIntoBuffer(FileChannel fc, final ChunkHeader chunkHeader) throws IOException { final ByteBuffer chunkData = ByteBuffer.allocateDirect((int)chunkHeader.getSize()); chunkData.order(ByteOrder.BIG_ENDIAN); fc.read(chunkData); chunkData.position(0); return chunkData; }
Read the next chunk into ByteBuffer as specified by ChunkHeader and moves raf file pointer to start of next chunk/end of file. @param fc @param chunkHeader @return @throws java.io.IOException
AiffChunkReader::readChunkDataIntoBuffer
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkReader.java
Apache-2.0
AiffChunkType(final String code) { this.code=code; }
@param code 4 char string
AiffChunkType::AiffChunkType
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkType.java
Apache-2.0
public synchronized static AiffChunkType get(final String code) { if (CODE_TYPE_MAP.isEmpty()) { for (final AiffChunkType type : values()) { CODE_TYPE_MAP.put(type.getCode(), type); } } return CODE_TYPE_MAP.get(code); }
Get {@link AiffChunkType} for code (e.g. "SSND"). @param code chunk id @return chunk type or {@code null} if not registered
AiffChunkType::get
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkType.java
Apache-2.0
public String getCode() { return code; }
4 char type code. @return 4 char type code, e.g. "SSND" for the sound chunk.
AiffChunkType::getCode
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/AiffChunkType.java
Apache-2.0
public FormatVersionChunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData, final AiffAudioHeader aiffAudioHeader) { super(chunkData, chunkHeader); this.aiffHeader = aiffAudioHeader; }
@param chunkHeader The header for this chunk @param chunkData The buffer from which the AIFF data are being read @param aiffAudioHeader The AiffTag into which information is stored
FormatVersionChunk::FormatVersionChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/FormatVersionChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/FormatVersionChunk.java
Apache-2.0
public boolean readChunk() throws IOException { final long rawTimestamp = chunkData.getInt(); // The timestamp is in seconds since January 1, 1904. // We must convert to Java time. final Date timestamp = AiffUtil.timestampToDate(rawTimestamp); aiffHeader.setTimestamp(timestamp); return true; }
Reads a chunk and extracts information. @return <code>false</code> if the chunk is structurally invalid, otherwise <code>true</code>
FormatVersionChunk::readChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/FormatVersionChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/FormatVersionChunk.java
Apache-2.0
public CopyrightChunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData, final AiffAudioHeader aiffAudioHeader) { super(chunkHeader, chunkData, aiffAudioHeader); }
@param chunkHeader The header for this chunk @param chunkData The buffer from which the AIFF data are being read @param aiffAudioHeader The AiffAudioHeader into which information is stored
CopyrightChunk::CopyrightChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/CopyrightChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/CopyrightChunk.java
Apache-2.0
public TextChunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData, final AiffAudioHeader aiffAudioHeader) { super(chunkData, chunkHeader); this.aiffAudioHeader = aiffAudioHeader; }
Constructor. @param chunkHeader The header for this chunk @param chunkData The buffer from which the AIFF data are being read @param aiffAudioHeader aiff header
TextChunk::TextChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/TextChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/TextChunk.java
Apache-2.0
protected String readChunkText() throws IOException { // the spec actually only defines ASCII, not ISO_8859_1, but it probably does not hurt to be lenient return Utils.getString(chunkData, 0, chunkData.remaining(), StandardCharsets.ISO_8859_1); }
Reads the chunk and transforms it to a {@link String}. @return text string @throws IOException if the read fails
TextChunk::readChunkText
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/TextChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/TextChunk.java
Apache-2.0
public ApplicationChunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData, final AiffAudioHeader aiffAudioHeader) { super(chunkData, chunkHeader); this.aiffHeader = aiffAudioHeader; }
Constructor. @param chunkHeader The header for this chunk @param chunkData The file from which the AIFF data are being read @param aiffAudioHeader audio header
ApplicationChunk::ApplicationChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ApplicationChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ApplicationChunk.java
Apache-2.0
public boolean readChunk() throws IOException { final String applicationSignature = Utils.readFourBytesAsChars(chunkData); String applicationName = null; /* If the application signature is 'pdos' or 'stoc', * then the beginning of the data area is a Pascal * string naming the application. Otherwise, we * ignore the data. ('pdos' is for Apple II * applications, 'stoc' for the entire non-Apple world.) */ if (SIGNATURE_STOC.equals(applicationSignature) || SIGNATURE_PDOS.equals(applicationSignature)) { applicationName = Utils.readPascalString(chunkData); } aiffHeader.addApplicationIdentifier(applicationSignature + ": " + applicationName); return true; }
Reads a chunk and puts an Application property into the RepInfo object. @return <code>false</code> if the chunk is structurally invalid, otherwise <code>true</code>
ApplicationChunk::readChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ApplicationChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ApplicationChunk.java
Apache-2.0
public ID3Chunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData, final AiffTag tag) { super(chunkData, chunkHeader); aiffTag = tag; }
Constructor. @param chunkHeader The header for this chunk @param chunkData The content of this chunk @param tag The AiffTag into which information is stored
ID3Chunk::ID3Chunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ID3Chunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ID3Chunk.java
Apache-2.0
private boolean isId3v2Tag(final ByteBuffer headerData) throws IOException { for (int i = 0; i < AbstractID3v2Tag.FIELD_TAGID_LENGTH; i++) { if (headerData.get() != AbstractID3v2Tag.TAG_ID[i]) { return false; } } return true; }
Reads 3 bytes to determine if the tag really looks like ID3 data.
ID3Chunk::isId3v2Tag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ID3Chunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/ID3Chunk.java
Apache-2.0
public CommonChunk(ChunkHeader hdr, ByteBuffer chunkData, AiffAudioHeader aiffAudioHeader) { super(chunkData, hdr); aiffHeader = aiffAudioHeader; }
@param hdr @param chunkData @param aiffAudioHeader
CommonChunk::CommonChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/CommonChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/CommonChunk.java
Apache-2.0
public SoundChunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData) { super(chunkData, chunkHeader); }
@param chunkHeader The header for this chunk @param chunkData The file from which the AIFF data are being read
SoundChunk::SoundChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/SoundChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/SoundChunk.java
Apache-2.0
public CommentsChunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData, final AiffAudioHeader aiffAudioHeader) { super(chunkData, chunkHeader); this.aiffHeader = aiffAudioHeader; }
@param chunkHeader The header for this chunk @param chunkData The buffer from which the AIFF data are being read @param aiffAudioHeader audio header
CommentsChunk::CommentsChunk
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/aiff/chunk/CommentsChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/aiff/chunk/CommentsChunk.java
Apache-2.0
public ByteBuffer write() { ByteBuffer buffer = ByteBuffer.allocateDirect(DSD_HEADER_LENGTH); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(DsfChunkType.DSD.getCode().getBytes(StandardCharsets.US_ASCII)); buffer.putLong(chunkSizeLength); buffer.putLong(fileLength); buffer.putLong(metadataOffset); buffer.flip(); return buffer; }
Write new DSDchunk to buffer @return
DsdChunk::write
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/dsf/DsdChunk.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/dsf/DsdChunk.java
Apache-2.0
private Tag readTag(FileChannel fc, DsdChunk dsd, String fileName) throws CannotReadException,IOException { if(dsd.getMetadataOffset() > 0) { fc.position(dsd.getMetadataOffset()); ID3Chunk id3Chunk = ID3Chunk.readChunk(Utils.readFileDataIntoBufferLE(fc, (int) (fc.size() - fc.position()))); if(id3Chunk!=null) { int version = id3Chunk.getDataBuffer().get(AbstractID3v2Tag.FIELD_TAG_MAJOR_VERSION_POS); try { switch (version) { case ID3v22Tag.MAJOR_VERSION: return new ID3v22Tag(id3Chunk.getDataBuffer(), ""); case ID3v23Tag.MAJOR_VERSION: return new ID3v23Tag(id3Chunk.getDataBuffer(), ""); case ID3v24Tag.MAJOR_VERSION: return new ID3v24Tag(id3Chunk.getDataBuffer(), ""); default: logger.log(Level.WARNING, fileName + " Unknown ID3v2 version " + version + ". Returning an empty ID3v2 Tag."); return null; } } catch (TagException e) { throw new CannotReadException(fileName + " Could not read ID3v2 tag:corruption"); } } else { logger.log(Level.WARNING, fileName + " No existing ID3 tag(1)"); return null; } } else { logger.log(Level.WARNING, fileName + " No existing ID3 tag(2)"); return null; } }
Reads the ID3v2 tag starting at the {@code tagOffset} position in the supplied file. @param fc the filechannel from which to read @param dsd the dsd chunk @param fileName @return the read tag or an empty tag if something went wrong. Never <code>null</code>. @throws IOException if cannot read file.
DsfFileReader::readTag
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/dsf/DsfFileReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/dsf/DsfFileReader.java
Apache-2.0
public ByteBuffer convert(final AbstractID3v2Tag tag) throws UnsupportedEncodingException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); long existingTagSize = tag.getSize(); //If existingTag is uneven size lets make it even if( existingTagSize > 0) { if(Utils.isOddLength(existingTagSize)) { existingTagSize++; } } //Write Tag to buffer tag.write(baos, (int) existingTagSize); //If the tag is now odd because we needed to increase size and the data made it odd sized //we redo adding a padding byte to make it even if((baos.toByteArray().length & 1)!=0) { int newSize = baos.toByteArray().length + 1; baos = new ByteArrayOutputStream(); tag.write(baos, newSize); } final ByteBuffer buf = ByteBuffer.wrap(baos.toByteArray()); buf.rewind(); return buf; } catch (IOException ioe) { //Should never happen as not writing to file at this point throw new RuntimeException(ioe); } }
Convert ID3 tag into a ByteBuffer, also ensures always even to avoid problems @param tag @return @throws UnsupportedEncodingException
DsfFileWriter::convert
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/dsf/DsfFileWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/dsf/DsfFileWriter.java
Apache-2.0
public synchronized static DsfChunkType get(final String code) { if (CODE_TYPE_MAP.isEmpty()) { for (final DsfChunkType type : values()) { CODE_TYPE_MAP.put(type.getCode(), type); } } return CODE_TYPE_MAP.get(code); }
Get {@link org.jaudiotagger.audio.dsf.DsfChunkType} for code (e.g. "SSND"). @param code chunk id @return chunk type or {@code null} if not registered
DsfChunkType::get
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/dsf/DsfChunkType.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/dsf/DsfChunkType.java
Apache-2.0
public FlacStreamReader(FileChannel fc, String loggingName) { this.fc = fc; this.loggingName =loggingName; }
Create instance for holding stream info @param fc @param loggingName
FlacStreamReader::FlacStreamReader
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacStreamReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacStreamReader.java
Apache-2.0
public void findStream() throws IOException, CannotReadException { //Begins tag parsing if (fc.size() == 0) { //Empty File throw new CannotReadException("Error: File empty"+ " " + loggingName); } fc.position(0); //FLAC Stream at start if (isFlacHeader()) { startOfFlacInFile = 0; return; } //Ok maybe there is an ID3v24tag first if (isId3v2Tag()) { startOfFlacInFile = (int) (fc.position() - FLAC_STREAM_IDENTIFIER_LENGTH); return; } throw new CannotReadException(loggingName + ErrorMessage.FLAC_NO_FLAC_HEADER_FOUND.getMsg()); }
Reads the stream block to ensure it is a flac file @throws IOException @throws CannotReadException
FlacStreamReader::findStream
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacStreamReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacStreamReader.java
Apache-2.0
public int getStartOfFlacInFile() { return startOfFlacInFile; }
Usually flac header is at start of file, but unofficially an ID3 tag is allowed at the start of the file. @return the start of the Flac within file
FlacStreamReader::getStartOfFlacInFile
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacStreamReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacStreamReader.java
Apache-2.0
public ByteBuffer convert(Tag tag, int paddingSize) throws UnsupportedEncodingException { logger.config("Convert flac tag:padding:" + paddingSize); FlacTag flacTag = (FlacTag) tag; int tagLength = 0; ByteBuffer vorbiscomment = null; if (flacTag.getVorbisCommentTag() != null) { vorbiscomment = creator.convert(flacTag.getVorbisCommentTag()); tagLength = vorbiscomment.capacity() + MetadataBlockHeader.HEADER_LENGTH; } for (MetadataBlockDataPicture image : flacTag.getImages()) { tagLength += image.getBytes().limit() + MetadataBlockHeader.HEADER_LENGTH; } logger.config("Convert flac tag:taglength:" + tagLength); ByteBuffer buf = ByteBuffer.allocate(tagLength + paddingSize); MetadataBlockHeader vorbisHeader; //If there are other metadata blocks if (flacTag.getVorbisCommentTag() != null) { if ((paddingSize > 0) || (flacTag.getImages().size() > 0)) { vorbisHeader = new MetadataBlockHeader(false, BlockType.VORBIS_COMMENT, vorbiscomment.capacity()); } else { vorbisHeader = new MetadataBlockHeader(true, BlockType.VORBIS_COMMENT, vorbiscomment.capacity()); } buf.put(vorbisHeader.getBytes()); buf.put(vorbiscomment); } //Images ListIterator<MetadataBlockDataPicture> li = flacTag.getImages().listIterator(); while (li.hasNext()) { MetadataBlockDataPicture imageField = li.next(); MetadataBlockHeader imageHeader; if (paddingSize > 0 || li.hasNext()) { imageHeader = new MetadataBlockHeader(false, BlockType.PICTURE, imageField.getLength()); } else { imageHeader = new MetadataBlockHeader(true, BlockType.PICTURE, imageField.getLength()); } buf.put(imageHeader.getBytes()); buf.put(imageField.getBytes()); } //Padding logger.config("Convert flac tag at" + buf.position()); if (paddingSize > 0) { int paddingDataSize = paddingSize - MetadataBlockHeader.HEADER_LENGTH; MetadataBlockHeader paddingHeader = new MetadataBlockHeader(true, BlockType.PADDING, paddingDataSize); MetadataBlockDataPadding padding = new MetadataBlockDataPadding(paddingDataSize); buf.put(paddingHeader.getBytes()); buf.put(padding.getBytes()); } buf.rewind(); return buf; }
@param tag @param paddingSize extra padding to be added @return @throws UnsupportedEncodingException
FlacTagCreator::convert
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagCreator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagCreator.java
Apache-2.0
public int countMetaBlocks(File f) throws CannotReadException, IOException { try(FileChannel fc = FileChannel.open(f.toPath())) { FlacStreamReader flacStream = new FlacStreamReader(fc, f.toPath() + " "); flacStream.findStream(); boolean isLastBlock = false; int count = 0; while (!isLastBlock) { MetadataBlockHeader mbh = MetadataBlockHeader.readHeader(fc); logger.config(f + ":Found block:" + mbh.getBlockType()); fc.position(fc.position() + mbh.getDataLength()); isLastBlock = mbh.isLastBlock(); count++; } return count; } }
Count the number of metadatablocks, useful for debugging @param f @return @throws CannotReadException @throws IOException
FlacInfoReader::countMetaBlocks
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacInfoReader.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacInfoReader.java
Apache-2.0
public void delete(Tag tag, Path file) throws CannotWriteException { //This will save the file without any Comment or PictureData blocks FlacTag emptyTag = new FlacTag(null, new ArrayList<MetadataBlockDataPicture>()); write(emptyTag, file); }
@param tag @param file @throws IOException @throws CannotWriteException
FlacTagWriter::delete
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
public void write(Tag tag, Path file) throws CannotWriteException { logger.config(file + " Writing tag"); try (FileChannel fc = FileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.READ)) { MetadataBlockInfo blockInfo = new MetadataBlockInfo(); //Read existing data FlacStreamReader flacStream = new FlacStreamReader(fc, file.toString() + " "); try { flacStream.findStream(); } catch (CannotReadException cre) { throw new CannotWriteException(cre.getMessage()); } boolean isLastBlock = false; while (!isLastBlock) { try { MetadataBlockHeader mbh = MetadataBlockHeader.readHeader(fc); if (mbh.getBlockType() != null) { switch (mbh.getBlockType()) { case STREAMINFO: { blockInfo.streamInfoBlock = new MetadataBlock(mbh, new MetadataBlockDataStreamInfo(mbh, fc)); break; } case VORBIS_COMMENT: case PADDING: case PICTURE: { //All these will be replaced by the new metadata so we just treat as padding in order //to determine how much space is already allocated in the file fc.position(fc.position() + mbh.getDataLength()); MetadataBlockData mbd = new MetadataBlockDataPadding(mbh.getDataLength()); blockInfo.metadataBlockPadding.add(new MetadataBlock(mbh, mbd)); break; } case APPLICATION: { MetadataBlockData mbd = new MetadataBlockDataApplication(mbh, fc); blockInfo.metadataBlockApplication.add(new MetadataBlock(mbh, mbd)); break; } case SEEKTABLE: { MetadataBlockData mbd = new MetadataBlockDataSeekTable(mbh, fc); blockInfo.metadataBlockSeekTable.add(new MetadataBlock(mbh, mbd)); break; } case CUESHEET: { MetadataBlockData mbd = new MetadataBlockDataCueSheet(mbh, fc); blockInfo.metadataBlockCueSheet.add(new MetadataBlock(mbh, mbd)); break; } default: { //What are the consequences of doing this fc.position(fc.position() + mbh.getDataLength()); break; } } } isLastBlock = mbh.isLastBlock(); } catch (CannotReadException cre) { throw new CannotWriteException(cre.getMessage()); } } //Number of bytes in the existing file available before audio data int availableRoom = computeAvailableRoom(blockInfo); //Minimum Size of the New tag data without padding int newTagSize = tc.convert(tag).limit(); //Other blocks required size int otherBlocksRequiredSize = computeNeededRoom(blockInfo); //Number of bytes required for new tagdata and other metadata blocks int neededRoom = newTagSize + otherBlocksRequiredSize; //Go to start of Flac within file fc.position(flacStream.getStartOfFlacInFile()); logger.config(file + ":Writing tag available bytes:" + availableRoom + ":needed bytes:" + neededRoom); //There is enough room to fit the tag without moving the audio just need to //adjust padding accordingly need to allow space for padding header if padding required if ((availableRoom == neededRoom) || (availableRoom > neededRoom + MetadataBlockHeader.HEADER_LENGTH)) { logger.config(file + ":Room to Rewrite"); //Jump over Id3 (if exists) and flac header fc.position(flacStream.getStartOfFlacInFile() + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH); //Write stream info and other non metadata blocks writeOtherMetadataBlocks(fc, blockInfo); //Write tag (and padding) fc.write(tc.convert(tag, availableRoom - neededRoom)); } //Need to move audio else { logger.config(file + ":Audio must be shifted "+ "NewTagSize:" + newTagSize + ":AvailableRoom:" + availableRoom + ":MinimumAdditionalRoomRequired:"+(neededRoom - availableRoom)); //As we are having to both anyway may as well put in the default padding insertUsingChunks(file, tag, fc, blockInfo, flacStream, neededRoom + FlacTagCreator.DEFAULT_PADDING, availableRoom); } } catch (AccessDeniedException ade) { logger.log(Level.SEVERE, ade.getMessage(), ade); throw new NoWritePermissionsException(file + ":" + ade.getMessage()); } catch (IOException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); throw new CannotWriteException(file + ":" + ioe.getMessage()); } }
@param tag @param file @throws CannotWriteException @throws IOException
MetadataBlockInfo::write
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
private void insertUsingDirectBuffer(Path file, Tag tag, FileChannel fc, MetadataBlockInfo blockInfo, FlacStreamReader flacStream, int availableRoom) throws IOException { //Find end of metadata blocks (start of Audio), i.e start of Flac + 4 bytes for 'fLaC', 4 bytes for streaminfo header and //34 bytes for streaminfo and then size of all the other existing blocks fc.position(flacStream.getStartOfFlacInFile() + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH + MetadataBlockHeader.HEADER_LENGTH + MetadataBlockDataStreamInfo.STREAM_INFO_DATA_LENGTH + availableRoom); //And copy into Buffer, because direct buffer doesnt use heap ByteBuffer audioData = ByteBuffer.allocateDirect((int)(fc.size() - fc.position())); fc.read(audioData); audioData.flip(); //Jump over Id3 (if exists) Flac Header fc.position(flacStream.getStartOfFlacInFile() + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH); writeOtherMetadataBlocks(fc, blockInfo); //Write tag (and add some default padding) fc.write(tc.convert(tag, FlacTagCreator.DEFAULT_PADDING)); //Write Audio fc.write(audioData); }
Insert metadata into space that is not large enough, so have to shift existing audio data by copying into buffer and the reinserting after adding the metadata However this method requires a contiguous amount of memory equal to the size of the audio to be available and this can cause a failure on low memory systems, so no longer used. @param tag @param fc @param blockInfo @param flacStream @param availableRoom @throws IOException @throws UnsupportedEncodingException
MetadataBlockInfo::insertUsingDirectBuffer
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
private void insertUsingChunks(Path file, Tag tag, FileChannel fc, MetadataBlockInfo blockInfo, FlacStreamReader flacStream, int neededRoom, int availableRoom) throws IOException, UnsupportedEncodingException { long originalFileSize = fc.size(); //Find end of metadata blocks (start of Audio), i.e start of Flac + 4 bytes for 'fLaC', 4 bytes for streaminfo header and //34 bytes for streaminfo and then size of all the other existing blocks long audioStart =flacStream.getStartOfFlacInFile() + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH + MetadataBlockHeader.HEADER_LENGTH + MetadataBlockDataStreamInfo.STREAM_INFO_DATA_LENGTH + availableRoom; //Extra Space Required for larger metadata block int extraSpaceRequired = neededRoom - availableRoom; logger.config(file + " Audio needs shifting:"+extraSpaceRequired); //ChunkSize must be at least as large as the extra space required to write the metadata int chunkSize = (int)TagOptionSingleton.getInstance().getWriteChunkSize(); if(chunkSize < extraSpaceRequired) { chunkSize = extraSpaceRequired; } Queue<ByteBuffer> queue = new LinkedBlockingQueue<>(); //Read first chunk of audio fc.position(audioStart); { ByteBuffer audioBuffer = ByteBuffer.allocateDirect(chunkSize); fc.read(audioBuffer); audioBuffer.flip(); queue.add(audioBuffer); } long readPosition = fc.position(); //Jump over Id3 (if exists) and Flac Header fc.position(flacStream.getStartOfFlacInFile() + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH); writeOtherMetadataBlocks(fc, blockInfo); fc.write(tc.convert(tag, FlacTagCreator.DEFAULT_PADDING)); long writePosition = fc.position(); fc.position(readPosition); while (fc.position() < originalFileSize) { //Read next chunk ByteBuffer audioBuffer = ByteBuffer.allocateDirect(chunkSize); fc.read(audioBuffer); readPosition=fc.position(); audioBuffer.flip(); queue.add(audioBuffer); //Write previous chunk fc.position(writePosition); fc.write(queue.remove()); writePosition=fc.position(); fc.position(readPosition); } fc.position(writePosition); fc.write(queue.remove()); }
Insert metadata into space that is not large enough We do this by reading/writing chunks of data allowing it to work on low memory systems Chunk size defined by TagOptionSingleton.getInstance().getWriteChunkSize() @param tag @param fc @param blockInfo @param flacStream @param neededRoom @param availableRoom @throws IOException @throws UnsupportedEncodingException
MetadataBlockInfo::insertUsingChunks
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
private void insertTagAndShift(Path file, Tag tag, FileChannel fc, MetadataBlockInfo blockInfo, FlacStreamReader flacStream, int neededRoom, int availableRoom) throws IOException, UnsupportedEncodingException { int headerLength = flacStream.getStartOfFlacInFile() + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH + MetadataBlockHeader.HEADER_LENGTH // this should be the length of the block header for the stream info + MetadataBlockDataStreamInfo.STREAM_INFO_DATA_LENGTH; long targetSizeBeforeAudioData = headerLength + neededRoom + FlacTagCreator.DEFAULT_PADDING; long remainderTargetSize = fc.size() - (headerLength + availableRoom); long totalTargetSize = targetSizeBeforeAudioData + remainderTargetSize; MappedByteBuffer mappedFile =null; try { //Use ByteBuffer mappedFile = fc.map(MapMode.READ_WRITE, 0, totalTargetSize); insertTagAndShiftViaMappedByteBuffer(tag, mappedFile, fc, targetSizeBeforeAudioData, totalTargetSize, blockInfo, flacStream, neededRoom, availableRoom); } catch(IOException ioe) { //#175: Flac Map error on write if(mappedFile==null) { insertUsingChunks(file, tag, fc, blockInfo, flacStream, neededRoom + FlacTagCreator.DEFAULT_PADDING, availableRoom); } else { logger.log(Level.SEVERE, ioe.getMessage(), ioe); throw ioe; } } }
Insert new metadata into file by using memory mapped file, and if fails write in chunks But this is problematic on 32bit systems for large flac files may not be able to map a contiguous address space large enough for a large audio size , so no longer used since better to go straight to using chunks @param tag @param fc @param blockInfo @param flacStream @param neededRoom @param availableRoom @throws IOException @throws UnsupportedEncodingException
MetadataBlockInfo::insertTagAndShift
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
private void insertTagAndShiftViaMappedByteBuffer(Tag tag, MappedByteBuffer mappedFile, FileChannel fc, long targetSizeBeforeAudioData, long totalTargetSize, MetadataBlockInfo blockInfo, FlacStreamReader flacStream, int neededRoom, int availableRoom) throws IOException, UnsupportedEncodingException { //Find end of metadata blacks (start of Audio) int currentEndOfFilePosition = safeLongToInt(fc.size()); /* * First shift data to the 'right' of the tag to the end of the file, whose position is currentEndOfTagsPosition */ int currentEndOfTagsPosition = safeLongToInt((targetSizeBeforeAudioData - FlacTagCreator.DEFAULT_PADDING) - neededRoom + availableRoom); int lengthDiff = safeLongToInt(totalTargetSize - currentEndOfFilePosition); final int BLOCK_SIZE = safeLongToInt(TagOptionSingleton.getInstance().getWriteChunkSize()); int currentPos = currentEndOfFilePosition - BLOCK_SIZE; byte[] buffer = new byte[BLOCK_SIZE]; for (; currentPos >= currentEndOfTagsPosition; currentPos -= BLOCK_SIZE) { mappedFile.position(currentPos); mappedFile.get(buffer, 0, BLOCK_SIZE); mappedFile.position(currentPos + lengthDiff); mappedFile.put(buffer, 0, BLOCK_SIZE); } /* * Final movement of start bytes. This also covers cases where BLOCK_SIZE is larger than the audio data */ int remainder = (currentPos + BLOCK_SIZE) - currentEndOfTagsPosition; if (remainder > 0) { mappedFile.position(currentEndOfTagsPosition); mappedFile.get(buffer, 0, remainder); mappedFile.position(currentEndOfTagsPosition + lengthDiff); mappedFile.put(buffer, 0, remainder); } DirectByteBufferUtils.release(mappedFile); /* Now overwrite the tag */ writeTags(tag, fc, blockInfo, flacStream); }
Insert new metadata into file by using memory mapped file But this is problematic on 32bit systems for large flac files may not be able to map a contiguous address space large enough for a large audio size , so no longer used @param tag @param mappedFile @param fc @param targetSizeBeforeAudioData @param totalTargetSize @param blockInfo @param flacStream @param neededRoom @param availableRoom @throws IOException @throws UnsupportedEncodingException
MetadataBlockInfo::insertTagAndShiftViaMappedByteBuffer
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
private void writeOtherMetadataBlocks(FileChannel fc, MetadataBlockInfo blockInfo) throws IOException { //Write StreamInfo, we always write this first even if wasn't first in original spec fc.write(ByteBuffer.wrap(blockInfo.streamInfoBlock.getHeader().getBytesWithoutIsLastBlockFlag())); fc.write(blockInfo.streamInfoBlock.getData().getBytes()); //Write Application Blocks for (MetadataBlock aMetadataBlockApplication : blockInfo.metadataBlockApplication) { fc.write(ByteBuffer.wrap(aMetadataBlockApplication.getHeader().getBytesWithoutIsLastBlockFlag())); fc.write(aMetadataBlockApplication.getData().getBytes()); } //Write Seek Table Blocks for (MetadataBlock aMetadataBlockSeekTable : blockInfo.metadataBlockSeekTable) { fc.write(ByteBuffer.wrap(aMetadataBlockSeekTable.getHeader().getBytesWithoutIsLastBlockFlag())); fc.write(aMetadataBlockSeekTable.getData().getBytes()); } //Write Cue sheet Blocks for (MetadataBlock aMetadataBlockCueSheet : blockInfo.metadataBlockCueSheet) { fc.write(ByteBuffer.wrap(aMetadataBlockCueSheet.getHeader().getBytesWithoutIsLastBlockFlag())); fc.write(aMetadataBlockCueSheet.getData().getBytes()); } }
Write all metadata blocks except for the the actual tag metadata <p/> We always write blocks in this order @param fc @param blockInfo @throws IOException
MetadataBlockInfo::writeOtherMetadataBlocks
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
private int computeAvailableRoom(MetadataBlockInfo blockInfo) { int length = 0; for (MetadataBlock aMetadataBlockApplication : blockInfo.metadataBlockApplication) { length += aMetadataBlockApplication.getLength(); } for (MetadataBlock aMetadataBlockSeekTable : blockInfo.metadataBlockSeekTable) { length += aMetadataBlockSeekTable.getLength(); } for (MetadataBlock aMetadataBlockCueSheet : blockInfo.metadataBlockCueSheet) { length += aMetadataBlockCueSheet.getLength(); } //Note when reading metadata has been put into padding as well for purposes of write for (MetadataBlock aMetadataBlockPadding : blockInfo.metadataBlockPadding) { length += aMetadataBlockPadding.getLength(); } return length; }
@param blockInfo @return space currently available for writing all Flac metadatablocks except for StreamInfo which is fixed size
MetadataBlockInfo::computeAvailableRoom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
private int computeNeededRoom(MetadataBlockInfo blockInfo) { int length = 0; for (MetadataBlock aMetadataBlockApplication : blockInfo.metadataBlockApplication) { length += aMetadataBlockApplication.getLength(); } for (MetadataBlock aMetadataBlockSeekTable : blockInfo.metadataBlockSeekTable) { length += aMetadataBlockSeekTable.getLength(); } for (MetadataBlock aMetadataBlockCueSheet : blockInfo.metadataBlockCueSheet) { length += aMetadataBlockCueSheet.getLength(); } return length; }
@param blockInfo @return space required to write the metadata blocks that are part of Flac but are not part of tagdata in the normal sense.
MetadataBlockInfo::computeNeededRoom
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/FlacTagWriter.java
Apache-2.0
public ByteBuffer getBytes() { return rawdata; }
@return the rawdata as it will be written to file
MetadataBlockDataStreamInfo::getBytes
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
Apache-2.0
private int readThreeByteInteger(byte b1, byte b2, byte b3) { int rate = (Utils.u(b1) << 16) + (Utils.u(b2) << 8) + (Utils.u(b3)); return rate; }
SOme values are stored as 3 byte integrals (instead of the more usual 2 or 4) @param b1 @param b2 @param b3 @return
MetadataBlockDataStreamInfo::readThreeByteInteger
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
Apache-2.0
private int readSamplingRate() { int rate = (Utils.u(rawdata.get(10)) << 12) + (Utils.u(rawdata.get(11)) << 4) + ((Utils.u(rawdata.get(12)) & 0xF0) >>> 4); return rate; }
Sampling rate is stored over 20 bits bytes 10 and 11 and half of bytes 12 so have to mask third one @return
MetadataBlockDataStreamInfo::readSamplingRate
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
Apache-2.0
private int readNoOfChannels() { return ((Utils.u(rawdata.get(12)) & 0x0E) >>> 1) + 1; }
Stored in 5th to 7th bits of byte 12
MetadataBlockDataStreamInfo::readNoOfChannels
java
ZTFtrue/MonsterMusic
app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/org/jaudiotagger/audio/flac/metadatablock/MetadataBlockDataStreamInfo.java
Apache-2.0