2 * Sonitus - MetadataBlock.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sonitus.io.flac;
20 import static com.google.common.io.ByteStreams.readFully;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.Arrays;
25 import java.util.List;
27 import com.google.common.base.Optional;
28 import com.google.common.base.Predicate;
29 import com.google.common.collect.FluentIterable;
30 import com.google.common.collect.Lists;
33 * Parser and container for information about a FLAC stream.
35 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39 /** The metadata blocks of the stream. */
40 private final List<MetadataBlock> metadataBlocks = Lists.newArrayList();
43 * Creates a new FLAC stream containing the given metadata blocks.
45 * @param metadataBlocks
46 * The metadata blocks in order of appearance
48 private Stream(List<MetadataBlock> metadataBlocks) {
49 this.metadataBlocks.addAll(metadataBlocks);
57 * Returns all metadata blocks of the given block type, in the order they
58 * appear in this stream.
61 * The block type to get all metadata blocks for
62 * @return The metadata blocks of the given block type
64 public List<MetadataBlock> metadataBlocks(final BlockType blockType) {
65 return FluentIterable.from(metadataBlocks).filter(new Predicate<MetadataBlock>() {
68 public boolean apply(MetadataBlock metadataBlock) {
69 return metadataBlock.header().blockType() == blockType;
79 * Parses the given input stream and returns information about the stream if it
80 * can be successfully parsed as a FLAC stream.
83 * The input stream containing the FLAC stream
84 * @return The parsed FLAC stream, or {@link Optional#absent()} if no FLAC
85 * stream could be found at the stream’s current position
87 * if an I/O error occurs
89 public static Optional<Stream> parse(InputStream inputStream) throws IOException {
90 byte[] streamTag = new byte[4];
91 readFully(inputStream, streamTag);
92 if (!Arrays.equals(streamTag, new byte[] { 'f', 'L', 'a', 'C' })) {
93 return Optional.absent();
95 List<MetadataBlock> metadataBlocks = Lists.newArrayList();
97 MetadataBlock metadataBlock = MetadataBlock.parse(inputStream);
98 metadataBlocks.add(metadataBlock);
99 if (metadataBlock.header().isLastMetadataBlock()) {
103 return Optional.of(new Stream(metadataBlocks));