VbrTag.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /*
  2. * Xing VBR tagging for LAME.
  3. *
  4. * Copyright (c) 1999 A.L. Faber
  5. * Copyright (c) 2001 Jonathan Dee
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Library General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Library General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Library General Public
  18. * License along with this library; if not, write to the
  19. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  20. * Boston, MA 02111-1307, USA.
  21. */
  22. /* $Id$ */
  23. #ifdef HAVE_CONFIG_H
  24. # include <config.h>
  25. #endif
  26. #include "lame.h"
  27. #include "machine.h"
  28. #include "encoder.h"
  29. #include "util.h"
  30. #include "bitstream.h"
  31. #include "VbrTag.h"
  32. #include "lame_global_flags.h"
  33. #include "tables.h"
  34. #ifdef __sun__
  35. /* woraround for SunOS 4.x, it has SEEK_* defined here */
  36. #include <unistd.h>
  37. #endif
  38. #ifdef _DEBUG
  39. /* #define DEBUG_VBRTAG */
  40. #endif
  41. /*
  42. * 4 bytes for Header Tag
  43. * 4 bytes for Header Flags
  44. * 100 bytes for entry (NUMTOCENTRIES)
  45. * 4 bytes for FRAME SIZE
  46. * 4 bytes for STREAM_SIZE
  47. * 4 bytes for VBR SCALE. a VBR quality indicator: 0=best 100=worst
  48. * 20 bytes for LAME tag. for example, "LAME3.12 (beta 6)"
  49. * ___________
  50. * 140 bytes
  51. */
  52. #define VBRHEADERSIZE (NUMTOCENTRIES+4+4+4+4+4)
  53. #define LAMEHEADERSIZE (VBRHEADERSIZE + 9 + 1 + 1 + 8 + 1 + 1 + 3 + 1 + 1 + 2 + 4 + 2 + 2)
  54. /* the size of the Xing header (MPEG1 and MPEG2) in kbps */
  55. #define XING_BITRATE1 128
  56. #define XING_BITRATE2 64
  57. #define XING_BITRATE25 32
  58. extern const char* get_lame_tag_encoder_short_version(void);
  59. static const char VBRTag0[] = { "Xing" };
  60. static const char VBRTag1[] = { "Info" };
  61. /* Lookup table for fast CRC computation
  62. * See 'CRC_update_lookup'
  63. * Uses the polynomial x^16+x^15+x^2+1 */
  64. static const unsigned int crc16_lookup[256] = {
  65. 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
  66. 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
  67. 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
  68. 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
  69. 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
  70. 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
  71. 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
  72. 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
  73. 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
  74. 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
  75. 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
  76. 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
  77. 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
  78. 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
  79. 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
  80. 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
  81. 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
  82. 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
  83. 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
  84. 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
  85. 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
  86. 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
  87. 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
  88. 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
  89. 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
  90. 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
  91. 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
  92. 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
  93. 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
  94. 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
  95. 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
  96. 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
  97. };
  98. /***********************************************************************
  99. * Robert Hegemann 2001-01-17
  100. ***********************************************************************/
  101. static void
  102. addVbr(VBR_seek_info_t * v, int bitrate)
  103. {
  104. int i;
  105. v->nVbrNumFrames++;
  106. v->sum += bitrate;
  107. v->seen++;
  108. if (v->seen < v->want) {
  109. return;
  110. }
  111. if (v->pos < v->size) {
  112. v->bag[v->pos] = v->sum;
  113. v->pos++;
  114. v->seen = 0;
  115. }
  116. if (v->pos == v->size) {
  117. for (i = 1; i < v->size; i += 2) {
  118. v->bag[i / 2] = v->bag[i];
  119. }
  120. v->want *= 2;
  121. v->pos /= 2;
  122. }
  123. }
  124. static void
  125. Xing_seek_table(VBR_seek_info_t const* v, unsigned char *t)
  126. {
  127. int i, indx;
  128. int seek_point;
  129. if (v->pos <= 0)
  130. return;
  131. for (i = 1; i < NUMTOCENTRIES; ++i) {
  132. float j = i / (float) NUMTOCENTRIES, act, sum;
  133. indx = (int) (floor(j * v->pos));
  134. if (indx > v->pos - 1)
  135. indx = v->pos - 1;
  136. act = v->bag[indx];
  137. sum = v->sum;
  138. seek_point = (int) (256. * act / sum);
  139. if (seek_point > 255)
  140. seek_point = 255;
  141. t[i] = seek_point;
  142. }
  143. }
  144. #ifdef DEBUG_VBR_SEEKING_TABLE
  145. static void
  146. print_seeking(unsigned char *t)
  147. {
  148. int i;
  149. printf("seeking table ");
  150. for (i = 0; i < NUMTOCENTRIES; ++i) {
  151. printf(" %d ", t[i]);
  152. }
  153. printf("\n");
  154. }
  155. #endif
  156. /****************************************************************************
  157. * AddVbrFrame: Add VBR entry, used to fill the VBR the TOC entries
  158. * Paramters:
  159. * nStreamPos: how many bytes did we write to the bitstream so far
  160. * (in Bytes NOT Bits)
  161. ****************************************************************************
  162. */
  163. void
  164. AddVbrFrame(lame_internal_flags * gfc)
  165. {
  166. int kbps = bitrate_table[gfc->cfg.version][gfc->ov_enc.bitrate_index];
  167. assert(gfc->VBR_seek_table.bag);
  168. addVbr(&gfc->VBR_seek_table, kbps);
  169. }
  170. /*-------------------------------------------------------------*/
  171. static int
  172. ExtractI4(const unsigned char *buf)
  173. {
  174. int x;
  175. /* big endian extract */
  176. x = buf[0];
  177. x <<= 8;
  178. x |= buf[1];
  179. x <<= 8;
  180. x |= buf[2];
  181. x <<= 8;
  182. x |= buf[3];
  183. return x;
  184. }
  185. static void
  186. CreateI4(unsigned char *buf, uint32_t nValue)
  187. {
  188. /* big endian create */
  189. buf[0] = (nValue >> 24) & 0xff;
  190. buf[1] = (nValue >> 16) & 0xff;
  191. buf[2] = (nValue >> 8) & 0xff;
  192. buf[3] = (nValue) & 0xff;
  193. }
  194. static void
  195. CreateI2(unsigned char *buf, int nValue)
  196. {
  197. /* big endian create */
  198. buf[0] = (nValue >> 8) & 0xff;
  199. buf[1] = (nValue) & 0xff;
  200. }
  201. /* check for magic strings*/
  202. static int
  203. IsVbrTag(const unsigned char *buf)
  204. {
  205. int isTag0, isTag1;
  206. isTag0 = ((buf[0] == VBRTag0[0]) && (buf[1] == VBRTag0[1]) && (buf[2] == VBRTag0[2])
  207. && (buf[3] == VBRTag0[3]));
  208. isTag1 = ((buf[0] == VBRTag1[0]) && (buf[1] == VBRTag1[1]) && (buf[2] == VBRTag1[2])
  209. && (buf[3] == VBRTag1[3]));
  210. return (isTag0 || isTag1);
  211. }
  212. #define SHIFT_IN_BITS_VALUE(x,n,v) ( x = (x << (n)) | ( (v) & ~(-1 << (n)) ) )
  213. static void
  214. setLameTagFrameHeader(lame_internal_flags const *gfc, unsigned char *buffer)
  215. {
  216. SessionConfig_t const *const cfg = &gfc->cfg;
  217. EncResult_t const *const eov = &gfc->ov_enc;
  218. char abyte, bbyte;
  219. SHIFT_IN_BITS_VALUE(buffer[0], 8u, 0xffu);
  220. SHIFT_IN_BITS_VALUE(buffer[1], 3u, 7);
  221. SHIFT_IN_BITS_VALUE(buffer[1], 1u, (cfg->samplerate_out < 16000) ? 0 : 1);
  222. SHIFT_IN_BITS_VALUE(buffer[1], 1u, cfg->version);
  223. SHIFT_IN_BITS_VALUE(buffer[1], 2u, 4 - 3);
  224. SHIFT_IN_BITS_VALUE(buffer[1], 1u, (!cfg->error_protection) ? 1 : 0);
  225. SHIFT_IN_BITS_VALUE(buffer[2], 4u, eov->bitrate_index);
  226. SHIFT_IN_BITS_VALUE(buffer[2], 2u, cfg->samplerate_index);
  227. SHIFT_IN_BITS_VALUE(buffer[2], 1u, 0);
  228. SHIFT_IN_BITS_VALUE(buffer[2], 1u, cfg->extension);
  229. SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->mode);
  230. SHIFT_IN_BITS_VALUE(buffer[3], 2u, eov->mode_ext);
  231. SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->copyright);
  232. SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->original);
  233. SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->emphasis);
  234. /* the default VBR header. 48 kbps layer III, no padding, no crc */
  235. /* but sampling freq, mode andy copyright/copy protection taken */
  236. /* from first valid frame */
  237. buffer[0] = (uint8_t) 0xff;
  238. abyte = (buffer[1] & (unsigned char) 0xf1);
  239. {
  240. int bitrate;
  241. if (1 == cfg->version) {
  242. bitrate = XING_BITRATE1;
  243. }
  244. else {
  245. if (cfg->samplerate_out < 16000)
  246. bitrate = XING_BITRATE25;
  247. else
  248. bitrate = XING_BITRATE2;
  249. }
  250. if (cfg->vbr == vbr_off)
  251. bitrate = cfg->avg_bitrate;
  252. if (cfg->free_format)
  253. bbyte = 0x00;
  254. else
  255. bbyte = 16 * BitrateIndex(bitrate, cfg->version, cfg->samplerate_out);
  256. }
  257. /* Use as much of the info from the real frames in the
  258. * Xing header: samplerate, channels, crc, etc...
  259. */
  260. if (cfg->version == 1) {
  261. /* MPEG1 */
  262. buffer[1] = abyte | (char) 0x0a; /* was 0x0b; */
  263. abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
  264. buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG1 frame */
  265. }
  266. else {
  267. /* MPEG2 */
  268. buffer[1] = abyte | (char) 0x02; /* was 0x03; */
  269. abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
  270. buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG2 frame */
  271. }
  272. }
  273. #if 0
  274. static int CheckVbrTag(unsigned char *buf);
  275. /*-------------------------------------------------------------*/
  276. /* Same as GetVbrTag below, but only checks for the Xing tag.
  277. requires buf to contain only 40 bytes */
  278. /*-------------------------------------------------------------*/
  279. int
  280. CheckVbrTag(unsigned char *buf)
  281. {
  282. int h_id, h_mode;
  283. /* get selected MPEG header data */
  284. h_id = (buf[1] >> 3) & 1;
  285. h_mode = (buf[3] >> 6) & 3;
  286. /* determine offset of header */
  287. if (h_id) {
  288. /* mpeg1 */
  289. if (h_mode != 3)
  290. buf += (32 + 4);
  291. else
  292. buf += (17 + 4);
  293. }
  294. else {
  295. /* mpeg2 */
  296. if (h_mode != 3)
  297. buf += (17 + 4);
  298. else
  299. buf += (9 + 4);
  300. }
  301. return IsVbrTag(buf);
  302. }
  303. #endif
  304. int
  305. GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf)
  306. {
  307. int i, head_flags;
  308. int h_bitrate, h_id, h_mode, h_sr_index, h_layer;
  309. int enc_delay, enc_padding;
  310. /* get Vbr header data */
  311. pTagData->flags = 0;
  312. /* get selected MPEG header data */
  313. h_layer = (buf[1] >> 1) & 3;
  314. if ( h_layer != 0x01 ) {
  315. /* the following code assumes Layer-3, so give up here */
  316. return 0;
  317. }
  318. h_id = (buf[1] >> 3) & 1;
  319. h_sr_index = (buf[2] >> 2) & 3;
  320. h_mode = (buf[3] >> 6) & 3;
  321. h_bitrate = ((buf[2] >> 4) & 0xf);
  322. h_bitrate = bitrate_table[h_id][h_bitrate];
  323. /* check for FFE syncword */
  324. if ((buf[1] >> 4) == 0xE)
  325. pTagData->samprate = samplerate_table[2][h_sr_index];
  326. else
  327. pTagData->samprate = samplerate_table[h_id][h_sr_index];
  328. /* if( h_id == 0 ) */
  329. /* pTagData->samprate >>= 1; */
  330. /* determine offset of header */
  331. if (h_id) {
  332. /* mpeg1 */
  333. if (h_mode != 3)
  334. buf += (32 + 4);
  335. else
  336. buf += (17 + 4);
  337. }
  338. else {
  339. /* mpeg2 */
  340. if (h_mode != 3)
  341. buf += (17 + 4);
  342. else
  343. buf += (9 + 4);
  344. }
  345. if (!IsVbrTag(buf))
  346. return 0;
  347. buf += 4;
  348. pTagData->h_id = h_id;
  349. head_flags = pTagData->flags = ExtractI4(buf);
  350. buf += 4; /* get flags */
  351. if (head_flags & FRAMES_FLAG) {
  352. pTagData->frames = ExtractI4(buf);
  353. buf += 4;
  354. }
  355. if (head_flags & BYTES_FLAG) {
  356. pTagData->bytes = ExtractI4(buf);
  357. buf += 4;
  358. }
  359. if (head_flags & TOC_FLAG) {
  360. if (pTagData->toc != NULL) {
  361. for (i = 0; i < NUMTOCENTRIES; i++)
  362. pTagData->toc[i] = buf[i];
  363. }
  364. buf += NUMTOCENTRIES;
  365. }
  366. pTagData->vbr_scale = -1;
  367. if (head_flags & VBR_SCALE_FLAG) {
  368. pTagData->vbr_scale = ExtractI4(buf);
  369. buf += 4;
  370. }
  371. pTagData->headersize = ((h_id + 1) * 72000 * h_bitrate) / pTagData->samprate;
  372. buf += 21;
  373. enc_delay = buf[0] << 4;
  374. enc_delay += buf[1] >> 4;
  375. enc_padding = (buf[1] & 0x0F) << 8;
  376. enc_padding += buf[2];
  377. /* check for reasonable values (this may be an old Xing header, */
  378. /* not a INFO tag) */
  379. if (enc_delay < 0 || enc_delay > 3000)
  380. enc_delay = -1;
  381. if (enc_padding < 0 || enc_padding > 3000)
  382. enc_padding = -1;
  383. pTagData->enc_delay = enc_delay;
  384. pTagData->enc_padding = enc_padding;
  385. #ifdef DEBUG_VBRTAG
  386. fprintf(stderr, "\n\n********************* VBR TAG INFO *****************\n");
  387. fprintf(stderr, "tag :%s\n", VBRTag);
  388. fprintf(stderr, "head_flags :%d\n", head_flags);
  389. fprintf(stderr, "bytes :%d\n", pTagData->bytes);
  390. fprintf(stderr, "frames :%d\n", pTagData->frames);
  391. fprintf(stderr, "VBR Scale :%d\n", pTagData->vbr_scale);
  392. fprintf(stderr, "enc_delay = %i \n", enc_delay);
  393. fprintf(stderr, "enc_padding= %i \n", enc_padding);
  394. fprintf(stderr, "toc:\n");
  395. if (pTagData->toc != NULL) {
  396. for (i = 0; i < NUMTOCENTRIES; i++) {
  397. if ((i % 10) == 0)
  398. fprintf(stderr, "\n");
  399. fprintf(stderr, " %3d", (int) (pTagData->toc[i]));
  400. }
  401. }
  402. fprintf(stderr, "\n***************** END OF VBR TAG INFO ***************\n");
  403. #endif
  404. return 1; /* success */
  405. }
  406. /****************************************************************************
  407. * InitVbrTag: Initializes the header, and write empty frame to stream
  408. * Paramters:
  409. * fpStream: pointer to output file stream
  410. * nMode : Channel Mode: 0=STEREO 1=JS 2=DS 3=MONO
  411. ****************************************************************************
  412. */
  413. int
  414. InitVbrTag(lame_global_flags * gfp)
  415. {
  416. lame_internal_flags *gfc = gfp->internal_flags;
  417. SessionConfig_t const *const cfg = &gfc->cfg;
  418. int kbps_header;
  419. #define MAXFRAMESIZE 2880 /* or 0xB40, the max freeformat 640 32kHz framesize */
  420. /*
  421. * Xing VBR pretends to be a 48kbs layer III frame. (at 44.1kHz).
  422. * (at 48kHz they use 56kbs since 48kbs frame not big enough for
  423. * table of contents)
  424. * let's always embed Xing header inside a 64kbs layer III frame.
  425. * this gives us enough room for a LAME version string too.
  426. * size determined by sampling frequency (MPEG1)
  427. * 32kHz: 216 bytes@48kbs 288bytes@ 64kbs
  428. * 44.1kHz: 156 bytes 208bytes@64kbs (+1 if padding = 1)
  429. * 48kHz: 144 bytes 192
  430. *
  431. * MPEG 2 values are the same since the framesize and samplerate
  432. * are each reduced by a factor of 2.
  433. */
  434. if (1 == cfg->version) {
  435. kbps_header = XING_BITRATE1;
  436. }
  437. else {
  438. if (cfg->samplerate_out < 16000)
  439. kbps_header = XING_BITRATE25;
  440. else
  441. kbps_header = XING_BITRATE2;
  442. }
  443. if (cfg->vbr == vbr_off)
  444. kbps_header = cfg->avg_bitrate;
  445. /** make sure LAME Header fits into Frame
  446. */
  447. {
  448. int total_frame_size = ((cfg->version + 1) * 72000 * kbps_header) / cfg->samplerate_out;
  449. int header_size = (cfg->sideinfo_len + LAMEHEADERSIZE);
  450. gfc->VBR_seek_table.TotalFrameSize = total_frame_size;
  451. if (total_frame_size < header_size || total_frame_size > MAXFRAMESIZE) {
  452. /* disable tag, it wont fit */
  453. gfc->cfg.write_lame_tag = 0;
  454. return 0;
  455. }
  456. }
  457. gfc->VBR_seek_table.nVbrNumFrames = 0;
  458. gfc->VBR_seek_table.nBytesWritten = 0;
  459. gfc->VBR_seek_table.sum = 0;
  460. gfc->VBR_seek_table.seen = 0;
  461. gfc->VBR_seek_table.want = 1;
  462. gfc->VBR_seek_table.pos = 0;
  463. if (gfc->VBR_seek_table.bag == NULL) {
  464. gfc->VBR_seek_table.bag = lame_calloc(int, 400);
  465. if (gfc->VBR_seek_table.bag != NULL) {
  466. gfc->VBR_seek_table.size = 400;
  467. }
  468. else {
  469. gfc->VBR_seek_table.size = 0;
  470. ERRORF(gfc, "Error: can't allocate VbrFrames buffer\n");
  471. gfc->cfg.write_lame_tag = 0;
  472. return -1;
  473. }
  474. }
  475. /* write dummy VBR tag of all 0's into bitstream */
  476. {
  477. uint8_t buffer[MAXFRAMESIZE];
  478. size_t i, n;
  479. memset(buffer, 0, sizeof(buffer));
  480. setLameTagFrameHeader(gfc, buffer);
  481. n = gfc->VBR_seek_table.TotalFrameSize;
  482. for (i = 0; i < n; ++i) {
  483. add_dummy_byte(gfc, buffer[i], 1);
  484. }
  485. }
  486. /* Success */
  487. return 0;
  488. }
  489. /* fast CRC-16 computation - uses table crc16_lookup 8*/
  490. static uint16_t
  491. CRC_update_lookup(uint16_t value, uint16_t crc)
  492. {
  493. uint16_t tmp;
  494. tmp = crc ^ value;
  495. crc = (crc >> 8) ^ crc16_lookup[tmp & 0xff];
  496. return crc;
  497. }
  498. void
  499. UpdateMusicCRC(uint16_t * crc, unsigned char const *buffer, int size)
  500. {
  501. int i;
  502. for (i = 0; i < size; ++i)
  503. *crc = CRC_update_lookup(buffer[i], *crc);
  504. }
  505. /****************************************************************************
  506. * Jonathan Dee 2001/08/31
  507. *
  508. * PutLameVBR: Write LAME info: mini version + info on various switches used
  509. * Paramters:
  510. * pbtStreamBuffer : pointer to output buffer
  511. * id3v2size : size of id3v2 tag in bytes
  512. * crc : computation of crc-16 of Lame Tag so far (starting at frame sync)
  513. *
  514. ****************************************************************************
  515. */
  516. static int
  517. PutLameVBR(lame_global_flags const *gfp, size_t nMusicLength, uint8_t * pbtStreamBuffer, uint16_t crc)
  518. {
  519. lame_internal_flags const *gfc = gfp->internal_flags;
  520. SessionConfig_t const *const cfg = &gfc->cfg;
  521. int nBytesWritten = 0;
  522. int i;
  523. int enc_delay = gfc->ov_enc.encoder_delay; /* encoder delay */
  524. int enc_padding = gfc->ov_enc.encoder_padding; /* encoder padding */
  525. /*recall: cfg->vbr_q is for example set by the switch -V */
  526. /* gfp->quality by -q, -h, -f, etc */
  527. int nQuality = (100 - 10 * gfp->VBR_q - gfp->quality);
  528. /*
  529. NOTE:
  530. Even though the specification for the LAME VBR tag
  531. did explicitly mention other encoders than LAME,
  532. many SW/HW decoder seem to be able to make use of
  533. this tag only, if the encoder version starts with LAME.
  534. To be compatible with such decoders, ANY encoder will
  535. be forced to write a fake LAME version string!
  536. As a result, the encoder version info becomes worthless.
  537. */
  538. const char *szVersion = get_lame_tag_encoder_short_version();
  539. uint8_t nVBR;
  540. uint8_t nRevision = 0x00;
  541. uint8_t nRevMethod;
  542. uint8_t vbr_type_translator[] = { 1, 5, 3, 2, 4, 0, 3 }; /*numbering different in vbr_mode vs. Lame tag */
  543. uint8_t nLowpass =
  544. (((cfg->lowpassfreq / 100.0) + .5) > 255 ? 255 : (cfg->lowpassfreq / 100.0) + .5);
  545. uint32_t nPeakSignalAmplitude = 0;
  546. uint16_t nRadioReplayGain = 0;
  547. uint16_t nAudiophileReplayGain = 0;
  548. uint8_t nNoiseShaping = cfg->noise_shaping;
  549. uint8_t nStereoMode = 0;
  550. int bNonOptimal = 0;
  551. uint8_t nSourceFreq = 0;
  552. uint8_t nMisc = 0;
  553. uint16_t nMusicCRC = 0;
  554. /*psy model type: Gpsycho or NsPsytune */
  555. unsigned char bExpNPsyTune = 1; /* only NsPsytune */
  556. unsigned char bSafeJoint = (cfg->use_safe_joint_stereo) != 0;
  557. unsigned char bNoGapMore = 0;
  558. unsigned char bNoGapPrevious = 0;
  559. int nNoGapCount = gfp->nogap_total;
  560. int nNoGapCurr = gfp->nogap_current;
  561. uint8_t nAthType = cfg->ATHtype; /*4 bits. */
  562. uint8_t nFlags = 0;
  563. /* if ABR, {store bitrate <=255} else { store "-b"} */
  564. int nABRBitrate;
  565. switch (cfg->vbr) {
  566. case vbr_abr:{
  567. nABRBitrate = cfg->vbr_avg_bitrate_kbps;
  568. break;
  569. }
  570. case vbr_off:{
  571. nABRBitrate = cfg->avg_bitrate;
  572. break;
  573. }
  574. default:{ /*vbr modes */
  575. nABRBitrate = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];;
  576. }
  577. }
  578. /*revision and vbr method */
  579. if (cfg->vbr < sizeof(vbr_type_translator))
  580. nVBR = vbr_type_translator[cfg->vbr];
  581. else
  582. nVBR = 0x00; /*unknown. */
  583. nRevMethod = 0x10 * nRevision + nVBR;
  584. /* ReplayGain */
  585. if (cfg->findReplayGain) {
  586. int RadioGain = gfc->ov_rpg.RadioGain;
  587. if (RadioGain > 0x1FE)
  588. RadioGain = 0x1FE;
  589. if (RadioGain < -0x1FE)
  590. RadioGain = -0x1FE;
  591. nRadioReplayGain = 0x2000; /* set name code */
  592. nRadioReplayGain |= 0xC00; /* set originator code to `determined automatically' */
  593. if (RadioGain >= 0)
  594. nRadioReplayGain |= RadioGain; /* set gain adjustment */
  595. else {
  596. nRadioReplayGain |= 0x200; /* set the sign bit */
  597. nRadioReplayGain |= -RadioGain; /* set gain adjustment */
  598. }
  599. }
  600. /* peak sample */
  601. if (cfg->findPeakSample)
  602. nPeakSignalAmplitude =
  603. abs((int) ((((FLOAT) gfc->ov_rpg.PeakSample) / 32767.0) * pow(2, 23) + .5));
  604. /*nogap */
  605. if (nNoGapCount != -1) {
  606. if (nNoGapCurr > 0)
  607. bNoGapPrevious = 1;
  608. if (nNoGapCurr < nNoGapCount - 1)
  609. bNoGapMore = 1;
  610. }
  611. /*flags */
  612. nFlags = nAthType + (bExpNPsyTune << 4)
  613. + (bSafeJoint << 5)
  614. + (bNoGapMore << 6)
  615. + (bNoGapPrevious << 7);
  616. if (nQuality < 0)
  617. nQuality = 0;
  618. /*stereo mode field... a bit ugly. */
  619. switch (cfg->mode) {
  620. case MONO:
  621. nStereoMode = 0;
  622. break;
  623. case STEREO:
  624. nStereoMode = 1;
  625. break;
  626. case DUAL_CHANNEL:
  627. nStereoMode = 2;
  628. break;
  629. case JOINT_STEREO:
  630. if (cfg->force_ms)
  631. nStereoMode = 4;
  632. else
  633. nStereoMode = 3;
  634. break;
  635. case NOT_SET:
  636. /* FALLTHROUGH */
  637. default:
  638. nStereoMode = 7;
  639. break;
  640. }
  641. /*Intensity stereo : nStereoMode = 6. IS is not implemented */
  642. if (cfg->samplerate_in <= 32000)
  643. nSourceFreq = 0x00;
  644. else if (cfg->samplerate_in == 48000)
  645. nSourceFreq = 0x02;
  646. else if (cfg->samplerate_in > 48000)
  647. nSourceFreq = 0x03;
  648. else
  649. nSourceFreq = 0x01; /*default is 44100Hz. */
  650. /*Check if the user overrided the default LAME behaviour with some nasty options */
  651. if (cfg->short_blocks == short_block_forced || cfg->short_blocks == short_block_dispensed || ((cfg->lowpassfreq == -1) && (cfg->highpassfreq == -1)) || /* "-k" */
  652. (cfg->disable_reservoir && cfg->avg_bitrate < 320) ||
  653. cfg->noATH || cfg->ATHonly || (nAthType == 0) || cfg->samplerate_in <= 32000)
  654. bNonOptimal = 1;
  655. nMisc = nNoiseShaping + (nStereoMode << 2)
  656. + (bNonOptimal << 5)
  657. + (nSourceFreq << 6);
  658. nMusicCRC = gfc->nMusicCRC;
  659. /*Write all this information into the stream */
  660. CreateI4(&pbtStreamBuffer[nBytesWritten], nQuality);
  661. nBytesWritten += 4;
  662. strncpy((char *) &pbtStreamBuffer[nBytesWritten], szVersion, 9);
  663. nBytesWritten += 9;
  664. pbtStreamBuffer[nBytesWritten] = nRevMethod;
  665. nBytesWritten++;
  666. pbtStreamBuffer[nBytesWritten] = nLowpass;
  667. nBytesWritten++;
  668. CreateI4(&pbtStreamBuffer[nBytesWritten], nPeakSignalAmplitude);
  669. nBytesWritten += 4;
  670. CreateI2(&pbtStreamBuffer[nBytesWritten], nRadioReplayGain);
  671. nBytesWritten += 2;
  672. CreateI2(&pbtStreamBuffer[nBytesWritten], nAudiophileReplayGain);
  673. nBytesWritten += 2;
  674. pbtStreamBuffer[nBytesWritten] = nFlags;
  675. nBytesWritten++;
  676. if (nABRBitrate >= 255)
  677. pbtStreamBuffer[nBytesWritten] = 0xFF;
  678. else
  679. pbtStreamBuffer[nBytesWritten] = nABRBitrate;
  680. nBytesWritten++;
  681. pbtStreamBuffer[nBytesWritten] = enc_delay >> 4; /* works for win32, does it for unix? */
  682. pbtStreamBuffer[nBytesWritten + 1] = (enc_delay << 4) + (enc_padding >> 8);
  683. pbtStreamBuffer[nBytesWritten + 2] = enc_padding;
  684. nBytesWritten += 3;
  685. pbtStreamBuffer[nBytesWritten] = nMisc;
  686. nBytesWritten++;
  687. pbtStreamBuffer[nBytesWritten++] = 0; /*unused in rev0 */
  688. CreateI2(&pbtStreamBuffer[nBytesWritten], cfg->preset);
  689. nBytesWritten += 2;
  690. CreateI4(&pbtStreamBuffer[nBytesWritten], (int) nMusicLength);
  691. nBytesWritten += 4;
  692. CreateI2(&pbtStreamBuffer[nBytesWritten], nMusicCRC);
  693. nBytesWritten += 2;
  694. /*Calculate tag CRC.... must be done here, since it includes
  695. *previous information*/
  696. for (i = 0; i < nBytesWritten; i++)
  697. crc = CRC_update_lookup(pbtStreamBuffer[i], crc);
  698. CreateI2(&pbtStreamBuffer[nBytesWritten], crc);
  699. nBytesWritten += 2;
  700. return nBytesWritten;
  701. }
  702. static long
  703. skipId3v2(FILE * fpStream)
  704. {
  705. size_t nbytes;
  706. long id3v2TagSize;
  707. unsigned char id3v2Header[10];
  708. /* seek to the beginning of the stream */
  709. if (fseek(fpStream, 0, SEEK_SET) != 0) {
  710. return -2; /* not seekable, abort */
  711. }
  712. /* read 10 bytes in case there's an ID3 version 2 header here */
  713. nbytes = fread(id3v2Header, 1, sizeof(id3v2Header), fpStream);
  714. if (nbytes != sizeof(id3v2Header)) {
  715. return -3; /* not readable, maybe opened Write-Only */
  716. }
  717. /* does the stream begin with the ID3 version 2 file identifier? */
  718. if (!strncmp((char *) id3v2Header, "ID3", 3)) {
  719. /* the tag size (minus the 10-byte header) is encoded into four
  720. * bytes where the most significant bit is clear in each byte */
  721. id3v2TagSize = (((id3v2Header[6] & 0x7f) << 21)
  722. | ((id3v2Header[7] & 0x7f) << 14)
  723. | ((id3v2Header[8] & 0x7f) << 7)
  724. | (id3v2Header[9] & 0x7f))
  725. + sizeof id3v2Header;
  726. }
  727. else {
  728. /* no ID3 version 2 tag in this stream */
  729. id3v2TagSize = 0;
  730. }
  731. return id3v2TagSize;
  732. }
  733. size_t
  734. lame_get_lametag_frame(lame_global_flags const *gfp, unsigned char *buffer, size_t size)
  735. {
  736. lame_internal_flags *gfc;
  737. SessionConfig_t const *cfg;
  738. unsigned long stream_size;
  739. unsigned int nStreamIndex;
  740. uint8_t btToc[NUMTOCENTRIES];
  741. if (gfp == 0) {
  742. return 0;
  743. }
  744. gfc = gfp->internal_flags;
  745. if (gfc == 0) {
  746. return 0;
  747. }
  748. if (!is_lame_internal_flags_valid(gfc)) {
  749. return 0;
  750. }
  751. cfg = &gfc->cfg;
  752. if (cfg->write_lame_tag == 0) {
  753. return 0;
  754. }
  755. if (gfc->VBR_seek_table.pos <= 0) {
  756. return 0;
  757. }
  758. if (size < gfc->VBR_seek_table.TotalFrameSize) {
  759. return gfc->VBR_seek_table.TotalFrameSize;
  760. }
  761. if (buffer == 0) {
  762. return 0;
  763. }
  764. memset(buffer, 0, gfc->VBR_seek_table.TotalFrameSize);
  765. /* 4 bytes frame header */
  766. setLameTagFrameHeader(gfc, buffer);
  767. /* Clear all TOC entries */
  768. memset(btToc, 0, sizeof(btToc));
  769. if (cfg->free_format) {
  770. int i;
  771. for (i = 1; i < NUMTOCENTRIES; ++i)
  772. btToc[i] = 255 * i / 100;
  773. }
  774. else {
  775. Xing_seek_table(&gfc->VBR_seek_table, btToc);
  776. }
  777. #ifdef DEBUG_VBR_SEEKING_TABLE
  778. print_seeking(btToc);
  779. #endif
  780. /* Start writing the tag after the zero frame */
  781. nStreamIndex = cfg->sideinfo_len;
  782. /* note! Xing header specifies that Xing data goes in the
  783. * ancillary data with NO ERROR PROTECTION. If error protecton
  784. * in enabled, the Xing data still starts at the same offset,
  785. * and now it is in sideinfo data block, and thus will not
  786. * decode correctly by non-Xing tag aware players */
  787. if (cfg->error_protection)
  788. nStreamIndex -= 2;
  789. /* Put Vbr tag */
  790. if (cfg->vbr == vbr_off) {
  791. buffer[nStreamIndex++] = VBRTag1[0];
  792. buffer[nStreamIndex++] = VBRTag1[1];
  793. buffer[nStreamIndex++] = VBRTag1[2];
  794. buffer[nStreamIndex++] = VBRTag1[3];
  795. }
  796. else {
  797. buffer[nStreamIndex++] = VBRTag0[0];
  798. buffer[nStreamIndex++] = VBRTag0[1];
  799. buffer[nStreamIndex++] = VBRTag0[2];
  800. buffer[nStreamIndex++] = VBRTag0[3];
  801. }
  802. /* Put header flags */
  803. CreateI4(&buffer[nStreamIndex], FRAMES_FLAG + BYTES_FLAG + TOC_FLAG + VBR_SCALE_FLAG);
  804. nStreamIndex += 4;
  805. /* Put Total Number of frames */
  806. CreateI4(&buffer[nStreamIndex], gfc->VBR_seek_table.nVbrNumFrames);
  807. nStreamIndex += 4;
  808. /* Put total audio stream size, including Xing/LAME Header */
  809. stream_size = gfc->VBR_seek_table.nBytesWritten + gfc->VBR_seek_table.TotalFrameSize;
  810. CreateI4(&buffer[nStreamIndex], stream_size);
  811. nStreamIndex += 4;
  812. /* Put TOC */
  813. memcpy(&buffer[nStreamIndex], btToc, sizeof(btToc));
  814. nStreamIndex += sizeof(btToc);
  815. if (cfg->error_protection) {
  816. /* (jo) error_protection: add crc16 information to header */
  817. CRC_writeheader(gfc, (char *) buffer);
  818. }
  819. {
  820. /*work out CRC so far: initially crc = 0 */
  821. uint16_t crc = 0x00;
  822. unsigned int i;
  823. for (i = 0; i < nStreamIndex; i++)
  824. crc = CRC_update_lookup(buffer[i], crc);
  825. /*Put LAME VBR info */
  826. nStreamIndex += PutLameVBR(gfp, stream_size, buffer + nStreamIndex, crc);
  827. }
  828. #ifdef DEBUG_VBRTAG
  829. {
  830. VBRTAGDATA TestHeader;
  831. GetVbrTag(&TestHeader, buffer);
  832. }
  833. #endif
  834. return gfc->VBR_seek_table.TotalFrameSize;
  835. }
  836. /***********************************************************************
  837. *
  838. * PutVbrTag: Write final VBR tag to the file
  839. * Paramters:
  840. * lpszFileName: filename of MP3 bit stream
  841. * nVbrScale : encoder quality indicator (0..100)
  842. ****************************************************************************
  843. */
  844. int
  845. PutVbrTag(lame_global_flags const *gfp, FILE * fpStream)
  846. {
  847. lame_internal_flags *gfc = gfp->internal_flags;
  848. long lFileSize;
  849. long id3v2TagSize;
  850. size_t nbytes;
  851. uint8_t buffer[MAXFRAMESIZE];
  852. if (gfc->VBR_seek_table.pos <= 0)
  853. return -1;
  854. /* Seek to end of file */
  855. fseek(fpStream, 0, SEEK_END);
  856. /* Get file size */
  857. lFileSize = ftell(fpStream);
  858. /* Abort if file has zero length. Yes, it can happen :) */
  859. if (lFileSize == 0)
  860. return -1;
  861. /*
  862. * The VBR tag may NOT be located at the beginning of the stream.
  863. * If an ID3 version 2 tag was added, then it must be skipped to write
  864. * the VBR tag data.
  865. */
  866. id3v2TagSize = skipId3v2(fpStream);
  867. if (id3v2TagSize < 0) {
  868. return id3v2TagSize;
  869. }
  870. /*Seek to the beginning of the stream */
  871. fseek(fpStream, id3v2TagSize, SEEK_SET);
  872. nbytes = lame_get_lametag_frame(gfp, buffer, sizeof(buffer));
  873. if (nbytes > sizeof(buffer)) {
  874. return -1;
  875. }
  876. if (nbytes < 1) {
  877. return 0;
  878. }
  879. /* Put it all to disk again */
  880. if (fwrite(buffer, nbytes, 1, fpStream) != 1) {
  881. return -1;
  882. }
  883. return 0; /* success */
  884. }