| 1 | /* BoCA - BonkEnc Component Architecture |
| 2 | * Copyright (C) 2007-2026 Robert Kausch <[email protected]> |
| 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 as |
| 6 | * published by the Free Software Foundation, either version 2 of |
| 7 | * the License, or (at your option) any later version. |
| 8 | * |
| 9 | * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR |
| 10 | * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED |
| 11 | * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ |
| 12 | |
| 13 | #include <smooth.h> |
| 14 | #include <smooth/dll.h> |
| 15 | |
| 16 | #include <smooth/io/drivers/driver_ansi.h> |
| 17 | |
| 18 | #include "mad.h" |
| 19 | #include "config.h" |
| 20 | |
| 21 | #include "../../shared/mp3frame.h" |
| 22 | #include "../../shared/vbrtag.h" |
| 23 | |
| 24 | using namespace smooth::IO; |
| 25 | using namespace smooth::Threads; |
| 26 | |
| 27 | const String &BoCA::DecoderMAD::GetComponentSpecs() |
| 28 | { |
| 29 | static String componentSpecs; |
| 30 | |
| 31 | if (maddll != NIL) |
| 32 | { |
| 33 | componentSpecs = " \ |
| 34 | \ |
| 35 | <?xml version=\"1.0\" encoding=\"UTF-8\"?> \ |
| 36 | <component> \ |
| 37 | <name>MAD MP3 Decoder</name> \ |
| 38 | <version>1.0</version> \ |
| 39 | <id>mad-dec</id> \ |
| 40 | <type>decoder</type> \ |
| 41 | <replace>lame-dec</replace> \ |
| 42 | <format> \ |
| 43 | <name>MPEG Audio Files</name> \ |
| 44 | <extension>mp1</extension> \ |
| 45 | <extension>mp2</extension> \ |
| 46 | <extension>mp3</extension> \ |
| 47 | <tag id=\"id3v1-tag\" mode=\"append\">ID3v1</tag> \ |
| 48 | <tag id=\"id3v2-tag\" mode=\"prepend\">ID3v2</tag> \ |
| 49 | </format> \ |
| 50 | </component> \ |
| 51 | \ |
| 52 | "; |
| 53 | } |
| 54 | |
| 55 | return componentSpecs; |
| 56 | } |
| 57 | |
| 58 | Void smooth::AttachDLL(Void *instance) |
| 59 | { |
| 60 | LoadMADDLL(); |
| 61 | } |
| 62 | |
| 63 | Void smooth::DetachDLL() |
| 64 | { |
| 65 | FreeMADDLL(); |
| 66 | } |
| 67 | |
| 68 | namespace BoCA |
| 69 | { |
| 70 | mad_flow MADInputCallback(void *, mad_stream *); |
| 71 | mad_flow MADOutputCallback(void *, const mad_header *, mad_pcm *); |
| 72 | mad_flow MADHeaderCallback(void *, const mad_header *, mad_pcm *); |
| 73 | mad_flow MADErrorCallback(void *, mad_stream *, mad_frame *); |
| 74 | |
| 75 | /* FIXME: This is the scaling function included in the MAD |
| 76 | * package. It should be replaced by a more decent one. |
| 77 | */ |
| 78 | static inline signed int scale(mad_fixed_t sample, int scale) |
| 79 | { |
| 80 | /* Round |
| 81 | */ |
| 82 | sample += (1L << (MAD_F_FRACBITS - scale)); |
| 83 | |
| 84 | /* Clip |
| 85 | */ |
| 86 | if (sample >= MAD_F_ONE) sample = MAD_F_ONE - 1; |
| 87 | else if (sample < -MAD_F_ONE) sample = -MAD_F_ONE; |
| 88 | |
| 89 | /* Quantize |
| 90 | */ |
| 91 | return sample >> (MAD_F_FRACBITS + 1 - scale); |
| 92 | } |
| 93 | }; |
| 94 | |
| 95 | Bool BoCA::DecoderMAD::CanOpenStream(const String &streamURI) |
| 96 | { |
| 97 | String lcURI = streamURI.ToLower(); |
| 98 | |
| 99 | return lcURI.EndsWith(".mp1") || |
| 100 | lcURI.EndsWith(".mp2") || |
| 101 | lcURI.EndsWith(".mp3"); |
| 102 | } |
| 103 | |
| 104 | Error BoCA::DecoderMAD::GetStreamInfo(const String &streamURI, Track &track) |
| 105 | { |
| 106 | DriverANSI ioDriver(File(streamURI), IS_READ); |
| 107 | InStream in(STREAM_DRIVER, &ioDriver); |
| 108 | |
| 109 | SkipID3v2Tag(in); |
| 110 | ParseVBRHeaders(in); |
| 111 | |
| 112 | track.fileSize = in.Size(); |
| 113 | track.length = -1; |
| 114 | |
| 115 | infoTrack = &track; |
| 116 | stop = False; |
| 117 | finishing = False; |
| 118 | finished = False; |
| 119 | |
| 120 | offset = in.GetPos(); |
| 121 | driver = &ioDriver; |
| 122 | driver->Seek(offset); |
| 123 | |
| 124 | ReadMAD(False); |
| 125 | |
| 126 | if (track.GetFormat() == Format()) { errorState = True; errorString = "Invalid file format"; } |
| 127 | |
| 128 | in.Close(); |
| 129 | ioDriver.Close(); |
| 130 | |
| 131 | if (!errorState) |
| 132 | { |
| 133 | Bool foundTag = False; |
| 134 | |
| 135 | AS::Registry &boca = AS::Registry::Get(); |
| 136 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag"); |
| 137 | |
| 138 | if (tagger != NIL) |
| 139 | { |
| 140 | tagger->SetConfiguration(GetConfiguration()); |
| 141 | |
| 142 | if (tagger->ParseStreamInfo(streamURI, track) == Success()) foundTag = True; |
| 143 | |
| 144 | boca.DeleteComponent(tagger); |
| 145 | } |
| 146 | |
| 147 | if (!foundTag) |
| 148 | { |
| 149 | tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v1-tag"); |
| 150 | |
| 151 | if (tagger != NIL) |
| 152 | { |
| 153 | tagger->SetConfiguration(GetConfiguration()); |
| 154 | tagger->ParseStreamInfo(streamURI, track); |
| 155 | |
| 156 | boca.DeleteComponent(tagger); |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | if (errorState) return Error(); |
| 162 | else return Success(); |
| 163 | } |
| 164 | |
| 165 | BoCA::DecoderMAD::DecoderMAD() : samplesRequestedSignal(1), samplesAvailableSignal(1) |
| 166 | { |
| 167 | configLayer = NIL; |
| 168 | |
| 169 | infoTrack = NIL; |
| 170 | decoderThread = NIL; |
| 171 | |
| 172 | stop = False; |
| 173 | finishing = False; |
| 174 | finished = False; |
| 175 | |
| 176 | offset = 0; |
| 177 | |
| 178 | numBytes = 0; |
| 179 | numFrames = 0; |
| 180 | |
| 181 | delaySamples = 0; |
| 182 | padSamples = 0; |
| 183 | |
| 184 | /* Initialize to decoder delay. |
| 185 | */ |
| 186 | delaySamplesLeft = 529; |
| 187 | } |
| 188 | |
| 189 | BoCA::DecoderMAD::~DecoderMAD() |
| 190 | { |
| 191 | if (configLayer != NIL) Object::DeleteObject(configLayer); |
| 192 | } |
| 193 | |
| 194 | Bool BoCA::DecoderMAD::Activate() |
| 195 | { |
| 196 | /* Skip headers. |
| 197 | */ |
| 198 | InStream in(STREAM_DRIVER, driver); |
| 199 | |
| 200 | SkipID3v2Tag(in); |
| 201 | ParseVBRHeaders(in); |
| 202 | |
| 203 | driver->Seek(in.GetPos()); |
| 204 | |
| 205 | /* Prepare decoder. |
| 206 | */ |
| 207 | infoTrack = new Track(); |
| 208 | decoderThread = NIL; |
| 209 | |
| 210 | stop = False; |
| 211 | finishing = False; |
| 212 | finished = False; |
| 213 | |
| 214 | samplesAvailableSignal.Wait(); |
| 215 | |
| 216 | return True; |
| 217 | } |
| 218 | |
| 219 | Bool BoCA::DecoderMAD::Deactivate() |
| 220 | { |
| 221 | if (decoderThread != NIL) |
| 222 | { |
| 223 | stop = True; |
| 224 | |
| 225 | samplesRequestedSignal.Release(); |
| 226 | |
| 227 | decoderThread->Wait(); |
| 228 | } |
| 229 | |
| 230 | delete infoTrack; |
| 231 | |
| 232 | return True; |
| 233 | } |
| 234 | |
| 235 | Int BoCA::DecoderMAD::ReadData(Buffer<UnsignedByte> &data) |
| 236 | { |
| 237 | static Endianness endianness = CPU().GetEndianness(); |
| 238 | |
| 239 | if (decoderThread == NIL) decoderThread = NonBlocking1<Bool>(&DecoderMAD::ReadMAD, this).Call(True); |
| 240 | |
| 241 | if (finished && samplesBuffer.Size() <= 0) return -1; |
| 242 | |
| 243 | samplesAvailableSignal.Wait(); |
| 244 | |
| 245 | /* Convert samples to target format. |
| 246 | */ |
| 247 | const Format &format = track.GetFormat(); |
| 248 | |
| 249 | data.Resize(samplesBuffer.Size() * (format.bits / 8)); |
| 250 | |
| 251 | for (Int i = 0; i < samplesBuffer.Size(); i++) |
| 252 | { |
| 253 | int sample = scale(samplesBuffer[i], format.bits); |
| 254 | |
| 255 | if (format.bits == 16 ) ((Short *) (unsigned char *) data)[i] = sample; |
| 256 | |
| 257 | else if (format.bits == 24 && endianness == EndianLittle) { data[i * 3 + 2] = (sample >> 16) & 0xFF; data[i * 3 + 1] = (sample >> 8) & 0xFF; data[i * 3 ] = sample & 0xFF; } |
| 258 | else if (format.bits == 24 && endianness == EndianBig ) { data[i * 3 ] = (sample >> 16) & 0xFF; data[i * 3 + 1] = (sample >> 8) & 0xFF; data[i * 3 + 2] = sample & 0xFF; } |
| 259 | } |
| 260 | |
| 261 | samplesBuffer.Resize(0); |
| 262 | |
| 263 | samplesRequestedSignal.Release(); |
| 264 | |
| 265 | return data.Size(); |
| 266 | } |
| 267 | |
| 268 | Bool BoCA::DecoderMAD::SkipID3v2Tag(InStream &in) |
| 269 | { |
| 270 | /* Check for an ID3v2 tag at the beginning of the |
| 271 | * file and skip it if it exists as it might cause |
| 272 | * problems if the tag is unsynchronized. |
| 273 | */ |
| 274 | if (in.InputString(3) == "ID3") |
| 275 | { |
| 276 | in.InputNumber(2); // ID3 version |
| 277 | in.InputNumber(1); // Flags |
| 278 | |
| 279 | /* Read tag size as a 4 byte unsynchronized integer. |
| 280 | */ |
| 281 | Int tagSize = (in.InputNumber(1) << 21) + |
| 282 | (in.InputNumber(1) << 14) + |
| 283 | (in.InputNumber(1) << 7) + |
| 284 | (in.InputNumber(1) ); |
| 285 | |
| 286 | in.RelSeek(tagSize); |
| 287 | |
| 288 | inBytes += (tagSize + 10); |
| 289 | } |
| 290 | else |
| 291 | { |
| 292 | in.Seek(0); |
| 293 | } |
| 294 | |
| 295 | return True; |
| 296 | } |
| 297 | |
| 298 | Bool BoCA::DecoderMAD::ParseVBRHeaders(InStream &in) |
| 299 | { |
| 300 | /* Read MPEG header and get frame size. |
| 301 | */ |
| 302 | Buffer<UnsignedByte> header(3); |
| 303 | |
| 304 | in.InputData(header, 3); |
| 305 | in.RelSeek(-3); |
| 306 | |
| 307 | Int frameSize = MP3Frame::GetMPEGFrameSize(header); |
| 308 | |
| 309 | if (frameSize < 156) return False; |
| 310 | |
| 311 | /* Read frame. |
| 312 | */ |
| 313 | Buffer<UnsignedByte> buffer(frameSize); |
| 314 | |
| 315 | in.InputData(buffer, frameSize); |
| 316 | |
| 317 | /* Check for a Xing or VBRI header and extract the number of frames. |
| 318 | */ |
| 319 | VbrTag vbrTag; |
| 320 | |
| 321 | if (vbrTag.Parse(buffer)) |
| 322 | { |
| 323 | if (vbrTag.flags & VbrTag::FLAG_BYTES) numBytes = vbrTag.bytes - frameSize; |
| 324 | if (vbrTag.flags & VbrTag::FLAG_FRAMES) numFrames = vbrTag.frames; |
| 325 | |
| 326 | if (vbrTag.flags & VbrTag::FLAG_GAPLESS) |
| 327 | { |
| 328 | delaySamples = vbrTag.delay; |
| 329 | padSamples = vbrTag.padding; |
| 330 | |
| 331 | delaySamplesLeft += delaySamples; |
| 332 | } |
| 333 | } |
| 334 | else |
| 335 | { |
| 336 | /* Seek back to before the frame if no Xing or VBRI header was found. |
| 337 | */ |
| 338 | in.RelSeek(-frameSize); |
| 339 | |
| 340 | return False; |
| 341 | } |
| 342 | |
| 343 | /* Sanity check for header vs. actual file size (account |
| 344 | * for possible ID3v1 and addtional 4kB of other tags). |
| 345 | */ |
| 346 | if (numBytes > 0 && in.Size() - in.GetPos() > numBytes * 1.01 + 128 + 4096) |
| 347 | { |
| 348 | numFrames = 0; |
| 349 | |
| 350 | padSamples = 0; |
| 351 | } |
| 352 | |
| 353 | return True; |
| 354 | } |
| 355 | |
| 356 | Int BoCA::DecoderMAD::ReadMAD(Bool readData) |
| 357 | { |
| 358 | /* Initialize decoder. |
| 359 | */ |
| 360 | mad_decoder decoder; |
| 361 | |
| 362 | if (readData) ex_mad_decoder_init(&decoder, this, &MADInputCallback, NIL, NIL, &MADOutputCallback, &MADErrorCallback, NIL); |
| 363 | else ex_mad_decoder_init(&decoder, this, &MADInputCallback, NIL, NIL, &MADHeaderCallback, &MADErrorCallback, NIL); |
| 364 | |
| 365 | /* Process header and audio. |
| 366 | */ |
| 367 | ex_mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC); |
| 368 | |
| 369 | /* Finish and free decoder. |
| 370 | */ |
| 371 | finished = True; |
| 372 | |
| 373 | samplesAvailableSignal.Release(); |
| 374 | |
| 375 | ex_mad_decoder_finish(&decoder); |
| 376 | |
| 377 | return Success(); |
| 378 | } |
| 379 | |
| 380 | ConfigLayer *BoCA::DecoderMAD::GetConfigurationLayer() |
| 381 | { |
| 382 | if (configLayer == NIL) configLayer = new ConfigureMAD(); |
| 383 | |
| 384 | return configLayer; |
| 385 | } |
| 386 | |
| 387 | mad_flow BoCA::MADInputCallback(void *client_data, mad_stream *stream) |
| 388 | { |
| 389 | DecoderMAD *filter = (DecoderMAD *) client_data; |
| 390 | |
| 391 | if (filter->stop || filter->finishing) return MAD_FLOW_STOP; |
| 392 | |
| 393 | /* Check if we have any more data. If not, append an empty |
| 394 | * frame to the last frame to allow the decoder to finish. |
| 395 | */ |
| 396 | if (filter->driver->GetPos() == filter->driver->GetSize()) filter->finishing = True; |
| 397 | |
| 398 | Int bytes = Math::Min((Int64) 131072, filter->finishing ? 1440 : filter->driver->GetSize() - filter->driver->GetPos()); |
| 399 | Int backup = stream->bufend - stream->next_frame; |
| 400 | |
| 401 | memmove(filter->inputBuffer, stream->next_frame, backup); |
| 402 | |
| 403 | filter->inputBuffer.Resize(bytes + backup); |
| 404 | |
| 405 | if (!filter->finishing) filter->driver->ReadData(filter->inputBuffer + backup, bytes); |
| 406 | else memset(filter->inputBuffer + backup, 0, bytes); |
| 407 | |
| 408 | ex_mad_stream_buffer(stream, filter->inputBuffer, bytes + backup); |
| 409 | |
| 410 | filter->inBytes += bytes; |
| 411 | |
| 412 | return MAD_FLOW_CONTINUE; |
| 413 | } |
| 414 | |
| 415 | mad_flow BoCA::MADOutputCallback(void *client_data, const mad_header *header, mad_pcm *pcm) |
| 416 | { |
| 417 | DecoderMAD *filter = (DecoderMAD *) client_data; |
| 418 | |
| 419 | if (filter->stop) return MAD_FLOW_STOP; |
| 420 | |
| 421 | filter->samplesRequestedSignal.Wait(); |
| 422 | |
| 423 | Int oSize = filter->samplesBuffer.Size(); |
| 424 | Int channels = header->mode == MAD_MODE_SINGLE_CHANNEL ? 1 : 2; |
| 425 | |
| 426 | if (pcm->length > filter->delaySamplesLeft) |
| 427 | { |
| 428 | filter->samplesBuffer.Resize(oSize + (pcm->length - filter->delaySamplesLeft) * channels); |
| 429 | |
| 430 | for (Int i = filter->delaySamplesLeft; i < (signed) pcm->length; i++) |
| 431 | { |
| 432 | for (Int j = 0; j < channels; j++) |
| 433 | { |
| 434 | filter->samplesBuffer[oSize + (i - filter->delaySamplesLeft) * channels + j] = pcm->samples[j][i]; |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | filter->delaySamplesLeft = Math::Max(0, filter->delaySamplesLeft - pcm->length); |
| 440 | |
| 441 | filter->samplesAvailableSignal.Release(); |
| 442 | |
| 443 | return MAD_FLOW_CONTINUE; |
| 444 | } |
| 445 | |
| 446 | mad_flow BoCA::MADHeaderCallback(void *client_data, const mad_header *header, mad_pcm *pcm) |
| 447 | { |
| 448 | DecoderMAD *filter = (DecoderMAD *) client_data; |
| 449 | const Config *config = filter->GetConfiguration(); |
| 450 | |
| 451 | Format format = filter->infoTrack->GetFormat(); |
| 452 | |
| 453 | format.bits = config->GetIntValue(ConfigureMAD::ConfigID, "Enable24Bit", False) ? 24 : 16; |
| 454 | format.channels = header->mode == MAD_MODE_SINGLE_CHANNEL ? 1 : 2; |
| 455 | format.rate = header->samplerate; |
| 456 | |
| 457 | filter->infoTrack->approxLength = (filter->infoTrack->fileSize - filter->offset) / (header->bitrate / 8) * format.rate; |
| 458 | |
| 459 | filter->infoTrack->SetFormat(format); |
| 460 | |
| 461 | /* If we previously found a Xing header, |
| 462 | * we can compute the exact duration from |
| 463 | * the number of frames in the file. |
| 464 | */ |
| 465 | if (filter->numFrames > 0) |
| 466 | { |
| 467 | filter->infoTrack->length = filter->numFrames * Math::Round((Float) header->duration.fraction / MAD_TIMER_RESOLUTION * format.rate); |
| 468 | |
| 469 | filter->infoTrack->length -= (filter->delaySamples + filter->padSamples); |
| 470 | } |
| 471 | |
| 472 | return MAD_FLOW_STOP; |
| 473 | } |
| 474 | |
| 475 | mad_flow BoCA::MADErrorCallback(void *client_data, mad_stream *stream, mad_frame *frame) |
| 476 | { |
| 477 | return MAD_FLOW_CONTINUE; |
| 478 | } |