a52.pas 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. {
  2. Translation of the A52 headers for FreePascal
  3. Copyright (C) 2006 by Ivo Steinmann
  4. }
  5. (*
  6. * a52.h
  7. * Copyright (C) 2000-2002 Michel Lespinasse <[email protected]>
  8. * Copyright (C) 1999-2000 Aaron Holtzman <[email protected]>
  9. *
  10. * This file is part of a52dec, a free ATSC A-52 stream decoder.
  11. * See http://liba52.sourceforge.net/ for updates.
  12. *
  13. * a52dec is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 2 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * a52dec is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program; if not, write to the Free Software
  25. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  26. *)
  27. {
  28. Using the liba52 API
  29. --------------------
  30. liba52 provides a low-level interface to decoding audio frames encoded
  31. using ATSC standard A/52 aka AC-3. liba52 provides downmixing and
  32. dynamic range compression for the following output configurations:
  33. A52_CHANNEL : Dual mono. Two independant mono channels.
  34. A52_CHANNEL1 : First of the two mono channels above.
  35. A52_CHANNEL2 : Second of the two mono channels above.
  36. A52_MONO : Mono.
  37. A52_STEREO : Stereo.
  38. A52_DOLBY : Dolby surround compatible stereo.
  39. A52_3F : 3 front channels (left, center, right)
  40. A52_2F1R : 2 front, 1 rear surround channel (L, R, S)
  41. A52_3F1R : 3 front, 1 rear surround channel (L, C, R, S)
  42. A52_2F2R : 2 front, 2 rear surround channels (L, R, LS, RS)
  43. A52_3F2R : 3 front, 2 rear surround channels (L, C, R, LS, RS)
  44. A52_LFE : Low frequency effects channel. Normally used to connect a
  45. subwoofer. Can be combined with any of the above channels.
  46. For example: A52_3F2R | A52_LFE -> 3 front, 2 rear, 1 LFE (5.1)
  47. Initialization
  48. --------------
  49. sample_t * a52_init (uint32_t mm_accel);
  50. Initializes the A/52 library. Takes as a parameter the acceptable
  51. optimizations which may be used, such as MMX. These are found in the
  52. included header file 'mm_accel', along with an autodetection function
  53. (mm_accel()). Currently, the only accelleration implemented is
  54. MM_ACCEL_MLIB, which uses the 'mlib' library if installed. mlib is
  55. only available on some Sun Microsystems platforms.
  56. The return value is a pointer to a properly-aligned sample buffer used
  57. for output samples.
  58. Probing the bitstream
  59. ---------------------
  60. int a52_syncinfo (uint8_t * buf, int * flags,
  61. int * sample_rate, int * bit_rate);
  62. The A/52 bitstream is composed of several a52 frames concatenated one
  63. after each other. An a52 frame is the smallest independantly decodable
  64. unit in the stream.
  65. buf must contain at least 7 bytes from the input stream. If these look
  66. like the start of a valid a52 frame, a52_syncinfo() returns the size
  67. of the coded frame in bytes, and fills flags, sample_rate and bit_rate
  68. with the information encoded in the stream. The returned size is
  69. guaranteed to be an even number between 128 and 3840. sample_rate will
  70. be the sampling frequency in Hz, bit_rate is for the compressed stream
  71. and is in bits per second, and flags is a description of the coded
  72. channels: the A52_LFE bit is set if there is an LFE channel coded in
  73. this stream, and by masking flags with A52_CHANNEL_MASK you will get a
  74. value that describes the full-bandwidth channels, as one of the
  75. A52_CHANNEL...A52_3F2R flags.
  76. If this can not possibly be a valid frame, then the function returns
  77. 0. You should then try to re-synchronize with the a52 stream - one way
  78. to try this would be to advance buf by one byte until its contents
  79. looks like a valid frame, but there might be better
  80. application-specific ways to synchronize.
  81. It is recommended to call this function for each frame, for several
  82. reasons: this function detects errors that the other functions will
  83. not double-check, consecutive frames might have different lengths, and
  84. it helps you re-sync with the stream if you get de-synchronized.
  85. Starting to decode a frame
  86. --------------------------
  87. int a52_frame (a52_state_t * state, uint8_t * buf, int * flags,
  88. sample_t * level, sample_t bias);
  89. This starts the work of decoding the A/52 frame (to be completed using
  90. a52_block()). buf should point to the beginning of the complete frame
  91. of the full size returned by a52_syncinfo().
  92. You should pass in the flags the speaker configuration that you
  93. support, and liba52 will return the speaker configuration it will use
  94. for its output, based on what is coded in the stream and what you
  95. asked for. For example, if the stream contains 2+2 channels
  96. (a52_syncinfo() returned A52_2F2R in the flags), and you have 3+1
  97. speakers (you passed A52_3F1R), then liba52 will choose do downmix to
  98. 2+1 speakers, since there is no center channel to send to your center
  99. speaker. So in that case the left and right channels will be
  100. essentially unmodified by the downmix, and the two surround channels
  101. will be added together and sent to your surround speaker. liba52 will
  102. return A52_2F1R to indicate this.
  103. The good news is that when you downmix to stereo you dont have to
  104. worry about this, you will ALWAYS get a stereo output no matter what
  105. was coded in the stream. For more complex output configurations you
  106. will have to handle the case where liba52 couldnt give you what you
  107. wanted because some of the channels were not encoded in the stream
  108. though.
  109. Level, bias, and A52_ADJUST_LEVEL:
  110. Before downmixing, samples are floating point values with a range of
  111. [-1,1]. Most types of downmixing will combine channels together, which
  112. will potentially result in a larger range for the output
  113. samples. liba52 provides two methods of controlling the range of the
  114. output, either before or after the downmix stage.
  115. If you do not set A52_ADJUST_LEVEL, liba52 will multiply the samples
  116. by your level value, so that they fit in the [-level,level]
  117. range. Then it will apply the standardized downmix equations,
  118. potentially making the samples go out of that interval again. The
  119. level parameter is not modified.
  120. Setting the A52_ADJUST_LEVEL flag will instruct liba52 to treat your
  121. level value as the intended range interval after downmixing. It will
  122. then figure out what level to use before the downmix (what you should
  123. have passed if you hadnt used the A52_ADJUST_LEVEL flag), and
  124. overwrite the level value you gave it with that new level value.
  125. The bias represents a value which should be added to the result
  126. regardless:
  127. output_sample = (input_sample * level) + bias;
  128. For example, a bias of 384 and a level of 1 tells liba52 you want
  129. samples between 383 and 385 instead of -1 and 1. This is what the
  130. sample program a52dec does, as it makes it faster to convert the
  131. samples to integer format, using a trick based on the IEEE
  132. floating-point format.
  133. This function also initialises the state for that frame, which will be
  134. reused next when decoding blocks.
  135. Dynamic range compression
  136. -------------------------
  137. void a52_dynrng (a52_state_t * state,
  138. sample_t (* call) (sample_t, void *), void * data);
  139. This function is purely optional. If you dont call it, liba52 will
  140. provide the default behaviour, which is to apply the full dynamic
  141. range compression as specified in the A/52 stream. This basically
  142. makes the loud sounds softer, and the soft sounds louder, so you can
  143. more easily listen to the stream in a noisy environment without
  144. disturbing anyone.
  145. If you do call this function and set a NULL callback, this will
  146. totally disable the dynamic range compression and provide a playback
  147. more adapted to a movie theater or a listening room.
  148. If you call this function and specify a callback function, this
  149. callback might be called up to once for each block, with two
  150. arguments: the compression factor 'c' recommended by the bitstream,
  151. and the private data pointer you specified in a52_dynrng(). The
  152. callback will then return the amount of compression to actually use -
  153. typically pow(c,x) where x is somewhere between 0 and 1. More
  154. elaborate compression functions might want to use a different value
  155. for 'x' depending wether c>1 or c<1 - or even something more complex
  156. if this is what you want.
  157. Decoding blocks
  158. ---------------
  159. int a52_block (a52_state_t * state, sample_t * samples);
  160. Every A/52 frame is composed of 6 blocks, each with an output of 256
  161. samples for each channel. The a52_block() function decodes the next
  162. block in the frame, and should be called 6 times to decode all of the
  163. audio in the frame. After each call, you should extract the audio data
  164. from the sample buffer.
  165. The sample pointer given should be the one a52_init() returned.
  166. After this function returns, the samples buuffer will contain 256
  167. samples for the first channel, followed by 256 samples for the second
  168. channel, etc... the channel order is LFE, left, center, right, left
  169. surround, right surround. If one of the channels is not present in the
  170. liba52 output, as indicated by the flags returned by a52_frame(), then
  171. this channel is skipped and the following channels are shifted so
  172. liba52 does not leave an empty space between channels.
  173. Pseudocode example
  174. ------------------
  175. sample_t * samples = a52_init (mm_accel());
  176. loop on input bytes:
  177. if at least 7 bytes in the buffer:
  178. bytes_to_get = a52_syncinfo (...)
  179. if bytes_to_get == 0:
  180. goto loop to keep looking for sync point
  181. else
  182. get rest of bytes
  183. a52_frame (state, buf, ...)
  184. [a52_dynrng (state, ...); this is only optional]
  185. for i = 1 ... 6:
  186. a52_block (state, samples)
  187. convert samples to integer and queue to soundcard
  188. }
  189. unit a52;
  190. {$mode objfpc}
  191. {$MINENUMSIZE 4}
  192. interface
  193. uses
  194. ctypes;
  195. {$UNDEF LIBA52_DOUBLE}
  196. {$IFDEF WINDOWS}
  197. {$DEFINE DYNLINK}
  198. {$ENDIF}
  199. {$IFDEF DYNLINK}
  200. const
  201. {$IF Defined(WINDOWS)}
  202. a52lib = 'a52.dll';
  203. {$ELSEIF Defined(UNIX)}
  204. a52lib = 'liba52.so';
  205. {$ELSE}
  206. {$MESSAGE ERROR 'DYNLINK not supported'}
  207. {$IFEND}
  208. {$ELSE}
  209. {$LINKLIB a52}
  210. {$ENDIF}
  211. const
  212. (* generic accelerations *)
  213. MM_ACCEL_DJBFFT = $00000001;
  214. (* x86 accelerations *)
  215. MM_ACCEL_X86_MMX = $80000000;
  216. MM_ACCEL_X86_3DNOW = $40000000;
  217. MM_ACCEL_X86_MMXEXT = $20000000;
  218. function mm_accel: cuint32; cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  219. // include a52.h
  220. // to avoid type problems with dts.pas, I renamed a52_sample_t to a52_a52_sample_t
  221. type
  222. pa52_sample_t = ^a52_sample_t;
  223. {$IFDEF LIBA52_DOUBLE}
  224. a52_sample_t = cdouble;
  225. {$ELSE}
  226. a52_sample_t = cfloat;
  227. {$ENDIF}
  228. pa52_state_t = ^a52_state_t;
  229. a52_state_t = record
  230. end;
  231. a52_dynrng_call = function(s: a52_sample_t; data: pointer): a52_sample_t; cdecl;
  232. const
  233. A52_CHANNEL = 0;
  234. A52_MONO = 1;
  235. A52_STEREO = 2;
  236. A52_3F = 3;
  237. A52_2F1R = 4;
  238. A52_3F1R = 5;
  239. A52_2F2R = 6;
  240. A52_3F2R = 7;
  241. A52_CHANNEL1 = 8;
  242. A52_CHANNEL2 = 9;
  243. A52_DOLBY = 10;
  244. A52_CHANNEL_MASK = 15;
  245. A52_LFE = 16;
  246. A52_ADJUST_LEVEL = 32;
  247. function a52_init(mm_accel: cuint32): pa52_state_t; cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  248. function a52_samples(state: pa52_state_t): pa52_sample_t; cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  249. function a52_syncinfo(buf: pcuint8; var flags: cint; var sample_rate: cint; var bit_rate: cint): cint; cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  250. function a52_frame(state: pa52_state_t; buf: pcuint8; var flags: cint; var level: a52_sample_t; bias: a52_sample_t): cint; cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  251. procedure a52_dynrng(state: pa52_state_t; call: a52_dynrng_call; data: pointer); cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  252. function a52_block(state: pa52_state_t): cint; cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  253. procedure a52_free(state: pa52_state_t); cdecl; external {$IFDEF DYNLINK}a52lib{$ENDIF};
  254. {
  255. Developer of the A52 helpers for FreePascal
  256. Copyright (C) 2006 by Ivo Steinmann
  257. }
  258. type
  259. a52_read_func = function(user: pointer; ptr: pointer; size: cuint): cuint; cdecl;
  260. a52_seek_func = function(user: pointer; offset: clong; whence: cint): clong; cdecl;
  261. a52_close_func = function(user: pointer): cint; cdecl;
  262. a52_tell_func = function(user: pointer): clong; cdecl;
  263. pa52_decoder = ^a52_decoder;
  264. a52_decoder = record
  265. inbuf : array[0..4096-1] of cuint8;
  266. inbuf_ptr : pcuint8;
  267. frame_size : cint;
  268. state : pa52_state_t;
  269. fsamples : pa52_sample_t; // internal samples buffer of a52 (returned by a52_samples)
  270. samples : array[0..1,0..6*256-1] of cint16;
  271. samplecnt : cint;
  272. sampleofs : cint;
  273. user : pointer;
  274. read : a52_read_func;
  275. seek : a52_seek_func;
  276. close : a52_close_func;
  277. tell : a52_tell_func;
  278. // Userinfo
  279. flags : cint;
  280. channels : cint;
  281. sample_rate : cint;
  282. bit_rate : cint;
  283. end;
  284. function a52_decoder_init(mm_accel: cuint32; user: pointer; read: a52_read_func; seek: a52_seek_func; close: a52_close_func; tell: a52_tell_func): pa52_decoder;
  285. function a52_decoder_read(decoder: pa52_decoder; buffer: pointer; length: cint): cint;
  286. procedure a52_decoder_free(decoder: pa52_decoder);
  287. implementation
  288. function a52_decoder_init(mm_accel: cuint32; user: pointer; read: a52_read_func; seek: a52_seek_func; close: a52_close_func; tell: a52_tell_func): pa52_decoder;
  289. begin
  290. GetMem(Result, Sizeof(a52_decoder));
  291. FillChar(Result^, Sizeof(a52_decoder), 0);
  292. Result^.state := a52_init(mm_accel);
  293. Result^.fsamples := a52_samples(Result^.state);
  294. Result^.inbuf_ptr := @Result^.inbuf[0];
  295. Result^.user := user;
  296. Result^.read := read;
  297. Result^.seek := seek;
  298. Result^.close := close;
  299. Result^.tell := tell;
  300. end;
  301. procedure a52_decoder_free(decoder: pa52_decoder);
  302. begin
  303. if not Assigned(decoder) then
  304. Exit;
  305. a52_free(decoder^.state);
  306. decoder^.close(decoder^.user);
  307. FreeMem(decoder);
  308. end;
  309. function a52_decoder_read(decoder: pa52_decoder; buffer: pointer; length: cint): cint;
  310. const
  311. HEADER_SIZE = 7;
  312. ac3_channels: array[0..7] of cint = (2,1,2,3,3,4,4,5);
  313. var
  314. num, ofs: cint;
  315. flags, len, i, j: cint;
  316. sample_rate, bit_rate: cint;
  317. level: a52_sample_t;
  318. begin
  319. // check blocksize here!
  320. ofs := 0;
  321. num := length;
  322. while num > 0 do
  323. begin
  324. if decoder^.samplecnt = 0 then
  325. begin
  326. len := ptrint(decoder^.inbuf_ptr) - ptrint(@decoder^.inbuf);
  327. if (len < HEADER_SIZE) or (len < decoder^.frame_size) then
  328. begin
  329. (* inbuf too small : enlarge *)
  330. len := Sizeof(a52_decoder.inbuf) - len;
  331. len := decoder^.read(decoder^.user, decoder^.inbuf_ptr, len);
  332. if len <= 0 then
  333. Exit(ofs);
  334. Inc(decoder^.inbuf_ptr, len);
  335. end;
  336. if decoder^.frame_size = 0 then
  337. begin
  338. (* no header seen : find one. We need at least 7 bytes to parse it *)
  339. //WriteLn('no header seen (', len, ')');
  340. len := a52_syncinfo(@decoder^.inbuf[0], decoder^.flags, sample_rate, bit_rate);
  341. if len = 0 then
  342. begin
  343. (* no sync found : move by one byte (inefficient, but simple!) *)
  344. Move(decoder^.inbuf[1], decoder^.inbuf[0], ptrint(decoder^.inbuf_ptr) - ptrint(@decoder^.inbuf) - 1);
  345. Dec(decoder^.inbuf_ptr, 1);
  346. end else begin
  347. decoder^.frame_size := len;
  348. (* update codec info *)
  349. decoder^.sample_rate := sample_rate;
  350. decoder^.bit_rate := bit_rate;
  351. decoder^.channels := ac3_channels[decoder^.flags and $7];
  352. if decoder^.flags and A52_LFE <> 0 then
  353. Inc(decoder^.channels);
  354. {WriteLn(' frame_size : ', decoder^.frame_size);
  355. WriteLn(' sample_rate : ', sample_rate);
  356. WriteLn(' bit_rate : ', bit_rate);
  357. WriteLn(' channels : ', decoder^.channels);}
  358. end;
  359. Continue;
  360. end;
  361. (* decode the frame *)
  362. flags := A52_STEREO;//decoder^.flags;
  363. level := High(Smallint)-30;
  364. if a52_frame(decoder^.state, @decoder^.inbuf[0], flags, level, 0) <> 0 then
  365. begin
  366. decoder^.inbuf_ptr := @decoder^.inbuf[0];
  367. decoder^.frame_size := 0;
  368. Continue;
  369. end;
  370. for i := 0 to 5 do
  371. begin
  372. if a52_block(decoder^.state) <> 0 then
  373. begin
  374. decoder^.inbuf_ptr := @decoder^.inbuf[0];
  375. decoder^.frame_size := 0;
  376. Exit(-1);
  377. end;
  378. for j := 0 to 255 do
  379. begin
  380. decoder^.samples[0, i*256+j] := Round(decoder^.fsamples[j + 000]);
  381. decoder^.samples[1, i*256+j] := Round(decoder^.fsamples[j + 256]);
  382. end;
  383. end;
  384. (* skip decoded frame *)
  385. Move(decoder^.inbuf[decoder^.frame_size], decoder^.inbuf[0], ptrint(decoder^.inbuf_ptr) - ptrint(@decoder^.inbuf) - decoder^.frame_size);
  386. Dec(decoder^.inbuf_ptr, decoder^.frame_size);
  387. decoder^.frame_size := 0;
  388. decoder^.sampleofs := 0;
  389. decoder^.samplecnt := 6*256;
  390. end;
  391. len := num div 4;
  392. if len > decoder^.samplecnt then
  393. len := decoder^.samplecnt;
  394. for i := 0 to len - 1 do
  395. begin
  396. pcint16(ptrint(buffer) + ofs + 0)^ := decoder^.samples[0][decoder^.sampleofs];
  397. pcint16(ptrint(buffer) + ofs + 2)^ := decoder^.samples[1][decoder^.sampleofs];
  398. Inc(decoder^.sampleofs);
  399. Dec(decoder^.samplecnt);
  400. ofs := ofs + 4;
  401. num := num - 4;
  402. end;
  403. end;
  404. Result := ofs;
  405. end;
  406. end.