1/* metaflac - Command-line FLAC metadata editor
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
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.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18
19#if HAVE_CONFIG_H
20#  include <config.h>
21#endif
22
23#include "utils.h"
24#include "FLAC/assert.h"
25#include "FLAC/stream_decoder.h"
26#include "FLAC/metadata.h"
27#include "share/grabbag.h"
28#include "operations_shorthand.h"
29
30static FLAC__bool populate_seekpoint_values(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write);
31
32FLAC__bool do_shorthand_operation__add_seekpoints(const char *filename, FLAC__Metadata_Chain *chain, const char *specification, FLAC__bool *needs_write)
33{
34	FLAC__bool ok = true, found_seektable_block = false;
35	FLAC__StreamMetadata *block = 0;
36	FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
37	FLAC__uint64 total_samples = 0;
38	unsigned sample_rate = 0;
39
40	if(0 == iterator)
41		die("out of memory allocating iterator");
42
43	FLAC__metadata_iterator_init(iterator, chain);
44
45	do {
46		block = FLAC__metadata_iterator_get_block(iterator);
47		if(block->type == FLAC__METADATA_TYPE_STREAMINFO) {
48			sample_rate = block->data.stream_info.sample_rate;
49			total_samples = block->data.stream_info.total_samples;
50		}
51		else if(block->type == FLAC__METADATA_TYPE_SEEKTABLE)
52			found_seektable_block = true;
53	} while(!found_seektable_block && FLAC__metadata_iterator_next(iterator));
54
55	if(total_samples == 0) {
56		fprintf(stderr, "%s: ERROR: cannot add seekpoints because STREAMINFO block does not specify total_samples\n", filename);
57		return false;
58	}
59
60	if(!found_seektable_block) {
61		/* create a new block */
62		block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
63		if(0 == block)
64			die("out of memory allocating SEEKTABLE block");
65		while(FLAC__metadata_iterator_prev(iterator))
66			;
67		if(!FLAC__metadata_iterator_insert_block_after(iterator, block)) {
68			print_error_with_chain_status(chain, "%s: ERROR: adding new SEEKTABLE block to metadata", filename);
69			FLAC__metadata_object_delete(block);
70			return false;
71		}
72		/* iterator is left pointing to new block */
73		FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == block);
74	}
75
76	FLAC__metadata_iterator_delete(iterator);
77
78	FLAC__ASSERT(0 != block);
79	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_SEEKTABLE);
80
81	if(!grabbag__seektable_convert_specification_to_template(specification, /*only_explicit_placeholders=*/false, total_samples, sample_rate, block, /*spec_has_real_points=*/0)) {
82		fprintf(stderr, "%s: ERROR (internal) preparing seektable with seekpoints\n", filename);
83		return false;
84	}
85
86	ok = populate_seekpoint_values(filename, block, needs_write);
87
88	if(ok)
89		(void) FLAC__format_seektable_sort(&block->data.seek_table);
90
91	return ok;
92}
93
94/*
95 * local routines
96 */
97
98typedef struct {
99	FLAC__StreamMetadata_SeekTable *seektable_template;
100	FLAC__uint64 samples_written;
101	FLAC__uint64 audio_offset, last_offset;
102	unsigned first_seekpoint_to_check;
103	FLAC__bool error_occurred;
104	FLAC__StreamDecoderErrorStatus error_status;
105} ClientData;
106
107static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
108{
109	ClientData *cd = (ClientData*)client_data;
110
111	(void)buffer;
112	FLAC__ASSERT(0 != cd);
113
114	if(!cd->error_occurred) {
115		const unsigned blocksize = frame->header.blocksize;
116		const FLAC__uint64 frame_first_sample = cd->samples_written;
117		const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
118		FLAC__uint64 test_sample;
119		unsigned i;
120		for(i = cd->first_seekpoint_to_check; i < cd->seektable_template->num_points; i++) {
121			test_sample = cd->seektable_template->points[i].sample_number;
122			if(test_sample > frame_last_sample) {
123				break;
124			}
125			else if(test_sample >= frame_first_sample) {
126				cd->seektable_template->points[i].sample_number = frame_first_sample;
127				cd->seektable_template->points[i].stream_offset = cd->last_offset - cd->audio_offset;
128				cd->seektable_template->points[i].frame_samples = blocksize;
129				cd->first_seekpoint_to_check++;
130				/* DO NOT: "break;" and here's why:
131				 * The seektable template may contain more than one target
132				 * sample for any given frame; we will keep looping, generating
133				 * duplicate seekpoints for them, and we'll clean it up later,
134				 * just before writing the seektable back to the metadata.
135				 */
136			}
137			else {
138				cd->first_seekpoint_to_check++;
139			}
140		}
141		cd->samples_written += blocksize;
142		if(!FLAC__stream_decoder_get_decode_position(decoder, &cd->last_offset))
143			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
144		return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
145	}
146	else
147		return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
148}
149
150static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
151{
152	ClientData *cd = (ClientData*)client_data;
153
154	(void)decoder;
155	FLAC__ASSERT(0 != cd);
156
157	if(!cd->error_occurred) { /* don't let multiple errors overwrite the first one */
158		cd->error_occurred = true;
159		cd->error_status = status;
160	}
161}
162
163FLAC__bool populate_seekpoint_values(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write)
164{
165	FLAC__StreamDecoder *decoder;
166	ClientData client_data;
167	FLAC__bool ok = true;
168
169	FLAC__ASSERT(0 != block);
170	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_SEEKTABLE);
171
172	client_data.seektable_template = &block->data.seek_table;
173	client_data.samples_written = 0;
174	/* client_data.audio_offset must be determined later */
175	client_data.first_seekpoint_to_check = 0;
176	client_data.error_occurred = false;
177
178	decoder = FLAC__stream_decoder_new();
179
180	if(0 == decoder) {
181		fprintf(stderr, "%s: ERROR (--add-seekpoint) creating the decoder instance\n", filename);
182		return false;
183	}
184
185	FLAC__stream_decoder_set_md5_checking(decoder, false);
186	FLAC__stream_decoder_set_metadata_ignore_all(decoder);
187
188	if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, /*metadata_callback=*/0, error_callback_, &client_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
189		fprintf(stderr, "%s: ERROR (--add-seekpoint) initializing the decoder instance (%s)\n", filename, FLAC__stream_decoder_get_resolved_state_string(decoder));
190		ok = false;
191	}
192
193	if(ok && !FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
194		fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file (%s)\n", filename, FLAC__stream_decoder_get_resolved_state_string(decoder));
195		ok = false;
196	}
197
198	if(ok && !FLAC__stream_decoder_get_decode_position(decoder, &client_data.audio_offset)) {
199		fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file\n", filename);
200		ok = false;
201	}
202	client_data.last_offset = client_data.audio_offset;
203
204	if(ok && !FLAC__stream_decoder_process_until_end_of_stream(decoder)) {
205		fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file (%s)\n", filename, FLAC__stream_decoder_get_resolved_state_string(decoder));
206		ok = false;
207	}
208
209	if(ok && client_data.error_occurred) {
210		fprintf(stderr, "%s: ERROR (--add-seekpoint) decoding file (%u:%s)\n", filename, (unsigned)client_data.error_status, FLAC__StreamDecoderErrorStatusString[client_data.error_status]);
211		ok = false;
212	}
213
214	*needs_write = true;
215	FLAC__stream_decoder_delete(decoder);
216	return ok;
217}
218