aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/github/daneren2005/dsub/util/tags/OggFile.java
blob: 0383c68ab6a8db6cbb662997ad2d9300adb42e95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
 * Copyright (C) 2013 Adrian Ulrich <adrian@blinkenlights.ch>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>. 
 */

package github.daneren2005.dsub.util.tags;


import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;


public class OggFile extends Common implements PageInfo.PageParser {

	private static final int OGG_PAGE_SIZE           = 27;  // Static size of an OGG Page
	private static final int OGG_TYPE_IDENTIFICATION = 1;   // Identification header
	private static final int OGG_TYPE_COMMENT        = 3;   // ID of 'VorbisComment's
	
	public OggFile() {
	}
	
	public HashMap getTags(RandomAccessFile s) throws IOException {
		long offset = 0;
		int  retry  = 64;
		boolean need_tags = true;
		boolean need_id = true;

		HashMap tags = new HashMap();
		HashMap identification = new HashMap();
		
		for( ; retry > 0 ; retry-- ) {
			PageInfo pi = parse_stream_page(s, offset);
			if(pi.type == OGG_TYPE_IDENTIFICATION) {
				identification = parse_ogg_vorbis_identification(s, offset+pi.header_len, pi.payload_len);
				need_id = false;
			} else if(pi.type == OGG_TYPE_COMMENT) {
				tags = parse_ogg_vorbis_comment(s, offset+pi.header_len, pi.payload_len);
				need_tags = false;
			}
			offset += pi.header_len + pi.payload_len;
			if (need_tags == false && need_id == false) {
				break;
			}
		}

		// Calculate duration in seconds
		// Note that this calculation is WRONG: We would have to get the last
		// packet to calculate the real length - but this is goot enough.
		if (identification.containsKey("bitrate_nominal")) {
			int br_nom = (Integer)identification.get("bitrate_nominal") / 8;
			long file_length = s.length();
			if (file_length > 0 && br_nom > 0) {
				tags.put("duration", (int)(file_length/br_nom));
			}
		}

		return tags;
	}
	
	
	/**
	 * Parses the ogg page at offset 'offset'
	 */
	public PageInfo parse_stream_page(RandomAccessFile s, long offset) throws IOException {
		long[] result   = new long[3];               // [header_size, payload_size]
		byte[] p_header = new byte[OGG_PAGE_SIZE];   // buffer for the page header 
		byte[] scratch;
		int bread       = 0;                         // number of bytes read
		int psize       = 0;                         // payload-size
		int nsegs       = 0;                         // Number of segments
		
		s.seek(offset);
		bread = s.read(p_header);
		if(bread != OGG_PAGE_SIZE)
			xdie("Unable to read() OGG_PAGE_HEADER");
		if((new String(p_header, 0, 5)).equals("OggS\0") != true)
			xdie("Invalid magic - not an ogg file?");
		
		nsegs = b2u(p_header[26]); 
		// debug("> file seg: "+nsegs);
		if(nsegs > 0) {
			scratch  = new byte[nsegs];
			bread    = s.read(scratch); 
			if(bread != nsegs)
				xdie("Failed to read segtable");
			
			for(int i=0; i<nsegs; i++) {
				psize += b2u(scratch[i]); 
			}
		}

		PageInfo pi    = new PageInfo();
		pi.header_len  = (s.getFilePointer() - offset);
		pi.payload_len = psize;
		pi.type        = -1;

		/* next byte is most likely the type -> pre-read */
		if(psize >= 1 && s.read(p_header, 0, 1) == 1) {
			pi.type = b2u(p_header[0]);
		}

		return pi;
	}
	
	/* In 'vorbiscomment' field is prefixed with \3vorbis in OGG files
	** we check that this marker is present and call the generic comment
	** parset with the correct offset (+7) */
	private HashMap parse_ogg_vorbis_comment(RandomAccessFile s, long offset, long pl_len) throws IOException {
		final int pfx_len = 7;
		byte[] pfx        = new byte[pfx_len];
		
		if(pl_len < pfx_len)
			xdie("ogg vorbis comment field is too short!");
		
		s.seek(offset);
		s.read(pfx);
		
		if( (new String(pfx, 0, pfx_len)).equals("\3vorbis") == false )
			xdie("Damaged packet found!");
		
		return parse_vorbis_comment(s, this, offset+pfx_len, pl_len-pfx_len);
	}

	/*
	 ** Returns a hashma with parsed vorbis identification header data
	 **/
	private HashMap parse_ogg_vorbis_identification(RandomAccessFile s, long offset, long pl_len) throws IOException {
		/* Structure:
		 * 7 bytes of \1vorbis
		 * 4 bytes version
		 * 1 byte channels
		 * 4 bytes sampling rate
		 * 4 bytes bitrate max
		 * 4 bytes bitrate nominal
		 * 4 bytes bitrate min
		 **/
		HashMap id_hash = new HashMap();
		byte[] buff = new byte[28];

		if(pl_len >= buff.length) {
			s.seek(offset);
			s.read(buff);
			id_hash.put("version"         , b2le32(buff, 7));
			id_hash.put("channels"        , b2u(buff[11]));
			id_hash.put("sampling_rate"   , b2le32(buff, 12));
			id_hash.put("bitrate_minimal" , b2le32(buff, 16));
			id_hash.put("bitrate_nominal" , b2le32(buff, 20));
			id_hash.put("bitrate_maximal" , b2le32(buff, 24));
		}

		return id_hash;
	}

};