pax_global_header00006660000000000000000000000064137373467160014533gustar00rootroot0000000000000052 comment=7c6caf962b6dd94762ed1aec99df85e9cf75b815 ocaml-mad-0.5.0/000077500000000000000000000000001373734671600133675ustar00rootroot00000000000000ocaml-mad-0.5.0/.github/000077500000000000000000000000001373734671600147275ustar00rootroot00000000000000ocaml-mad-0.5.0/.github/workflows/000077500000000000000000000000001373734671600167645ustar00rootroot00000000000000ocaml-mad-0.5.0/.github/workflows/main.yml000066400000000000000000000006571373734671600204430ustar00rootroot00000000000000name: Build on: [push] jobs: build: runs-on: ${{ matrix.operating-system }} strategy: matrix: operating-system: [ubuntu-latest, macos-latest] ocaml-version: ['4.09.0'] steps: - uses: actions/checkout@v1 - uses: avsm/setup-ocaml@master with: ocaml-version: ${{ matrix.ocaml-version }} - run: opam pin add -n . - run: opam depext -yt mad - run: opam install -t . ocaml-mad-0.5.0/.gitignore000066400000000000000000000000631373734671600153560ustar00rootroot00000000000000*~ _build *.byte *.native _tests .merlin *.install ocaml-mad-0.5.0/.ocamlformat000066400000000000000000000003201373734671600156670ustar00rootroot00000000000000profile = conventional break-separators = after space-around-lists = false doc-comments = before match-indent = 2 match-indent-nested = always parens-ite exp-grouping = preserve module-item-spacing = compact ocaml-mad-0.5.0/CHANGES000066400000000000000000000062351373734671600143700ustar00rootroot000000000000000.5.0 (07-10-2020) ===== * Switch to dune * Switch to read callbacks with bytes. * Use conversion functions provided by OCaml for filename. * Cleanup decoding logic around EOF. * Add decode_frame_float_ba. * Remove unecessary global root. 0.4.6 (17-09-2018) ===== * Minor fixes around GC when using the stream API. * Fix filename encoding in openfile on windows platforms. 0.4.5 (03-08-2015) ===== * Dummy github release. 0.4.4 (04-10-2011) ===== * Report more info about frames: private, copyright and original bits. * New decode_msg example that uses the above feature. 0.4.3 (24-08-2011) ===== * Added more general frame format reporting, including mpeg layer, channel mode and emphasis information. 0.4.2 (02-07-2011) ===== * Changed implementation to make it possible to process an mp3 frame without decoding it. This helps for seeking in mp3 files and computing duration. Functions added: - [get_current_time] - [skip_frame] 0.4.1 (12-05-2011) ===== * Added [skip_id3tags] to skip id3 tags on mad streams (e.g. handlers opened with [openstream]). 0.4.0 (19-08-2010) ===== * Changed decode_frame to return only mono data when there is only one channel. * Removed confusing wav_* and samplefreq API * Fixed duration to use decode_float * Fixed compilation using MinGW for win32 * Forced opening files in binary mode. 0.3.6 (12-10-2009) ===== * Added support for --enable-debugging configure option * Fixed mad compilation variables when compiling without pkg-config. * Added prefix to main compilation variables if passed to configure. * Makefile now honnors LIBDIRS variable for linking against libraries located in other places than then standard ones. * Added NO_CUSTOM to build in standard mode. 0.3.5 (05-01-2009) ===== * Skip ID3 tags when decoding mp3 files. Fixes #162 0.3.4 (27-05-2008) ===== * Close file descriptor after duration computation Fixes #141 0.3.3 (16-04-2008) ===== * More portable make invokation * Install .cmx file * Fixed crash in decoding routine due to recursive stack overflow 0.3.2 (17-10-2007) ===== * Improved configure support 0.3.1 (22-05-2007) ===== * Added decode_frame_float to decode directly to float arrays. * Added get_output_format to get the format of outputed PCM. 0.3.0 (02-03-2007) ===== * Minor memory fixes * Changed interface for getting the real output sample frequency 0.2.1 (11-11-2006) ===== * Minor bugfix in decoding error's handling, got rid of audio glitches. * More portable configure/build system. 0.2.0 (07-07-2006) ===== * Added openstream function. * Using caml_alloc_custom to create madfile values. * Corrected a GC issue in ocaml_mad_decode_frame. * Decoding (decode_frame) now releases the main OCaml mutex to let other threads run while decoding. 0.1.3 (20-04-2005) ===== * Updated OCamlMakefile and improved the build system. * Using caml namespace. * Makefile and configure cleaning. * Avoided memory leak on failure in ocaml_openfile. 0.1.2 (30-06-2004) ===== * Removed openfd, since it isn't used and fdopen(2) is not ANSI C. * Improved the mli documentation. 0.1.1 (11-02-2004) ===== * Big memory leaks removed. * get_current_position function added. 0.1.0 ===== * Initial release. ocaml-mad-0.5.0/COPYING000066400000000000000000000431311373734671600144240ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ocaml-mad-0.5.0/README.md000066400000000000000000000054761373734671600146620ustar00rootroot00000000000000OCaml-mad - OCaml bindings for the libmad ========================================= Authors: Samuel Mimram and Romain Beauxis Homepage: https://github.com/savonet/ocaml-mad Copyright (c) 2003-2019 the Savonet Team. Prerequisites: ============== - ocaml - lame - findlib - dune Compilation: ============ ``` $ dune build ``` This should build both the native and the byte-code version of the extension library. Installation: ============= Via `opam`: ``` $ opam install mad ``` Via `dune` (for developers): ``` $ dune install ``` License ======= 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Borrowed code ============= The libmad's stubs are based on [Madlld example](http://www.bsd-dk.dk/~elrond/audio/madlld/). Madlld is copyright 2001 by Bertrand Petit. Madlld is distributed under the following license: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ocaml-mad-0.5.0/dune-project000066400000000000000000000010071373734671600157070ustar00rootroot00000000000000(lang dune 2.0) (version 0.5.0) (name mad) (source (github savonet/ocaml-mad)) (license GPL-2.0) (authors "The Savonet Team ") (maintainers "The Savonet Team ") (generate_opam_files true) (package (name mad) (synopsis "Mad decoding library") (description "Bindings for the mad library which provides functions for encoding wave audio files into mp3") (depends (dune (> 2.0)) dune-configurator) (conflicts (liquidsoap (< 1.5.0))) ) ocaml-mad-0.5.0/examples/000077500000000000000000000000001373734671600152055ustar00rootroot00000000000000ocaml-mad-0.5.0/examples/decode_msg.ml000066400000000000000000000053701373734671600176350ustar00rootroot00000000000000(* * Copyright 2003-2006 Savonet team * * This file is part of OCaml-mad. * * Ocaml-mad 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 2 of the License, or * (at your option) any later version. * * Ocaml-mad 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 Ocaml-mad; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Decode message encoded using private bits. * * @author Romain Beauxis *) (* $Id$ *) let src = ref "" let usage = "usage: decode_msg source" let last = ref (false, true, false) let state () = let x, _, _ = !last in x let started = ref false let iob b = if b then 1 else 0 let get_bits mf char = let frame = Mad.get_frame_format mf in let cp = frame.Mad.copyright in let oi = frame.Mad.original in let pr = frame.Mad.private_bit in let lcp, _, _ = !last in last := (cp, oi, pr); if cp = not lcp then begin let char = (char lsl 1) + iob oi in (true, (char lsl 1) + iob pr) end else (false, char) let is_sync mf = let frame = Mad.get_frame_format mf in let cp = frame.Mad.copyright in let oi = frame.Mad.original in let pr = frame.Mad.private_bit in let lcp, loi, lpr = !last in last := (cp, oi, pr); if !started && loi = not oi && lpr = not pr && cp = lcp then true else begin started := true; false end let _ = Arg.parse [] (let pnum = ref (-1) in fun s -> incr pnum; match !pnum with | 0 -> src := s | _ -> Printf.eprintf "Error: too many arguments\n"; exit 1) usage; if !src = "" then ( Printf.printf "%s\n" usage; exit 1 ); let synced = ref false in let msg_char = ref 0 in let bit_pos = ref 0 in let mf = Mad.openfile !src in ( try while true do Mad.skip_frame mf; begin match !synced with | false when is_sync mf -> synced := true | false -> () | true -> let incr, char = get_bits mf !msg_char in msg_char := char; if incr then bit_pos := !bit_pos + 2 end; if !bit_pos > 7 then begin Printf.printf "%C%!" (char_of_int !msg_char); msg_char := 0; bit_pos := 0; synced := false end done; assert false with Mad.End_of_stream -> Mad.close mf ); Printf.printf "\n" ocaml-mad-0.5.0/examples/dune000066400000000000000000000004431373734671600160640ustar00rootroot00000000000000(executable (name decode_msg) (modules decode_msg) (libraries mad)) (executable (name mp32wav) (modules mp32wav) (libraries unix mad)) (executable (name mp3info) (modules mp3info) (libraries mad)) (executable (name mp3stream2wav) (modules mp3stream2wav) (libraries unix mad)) ocaml-mad-0.5.0/examples/mp32wav.ml000066400000000000000000000103311373734671600170340ustar00rootroot00000000000000(* * Copyright 2003-2006 Savonet team * * This file is part of OCaml-mad. * * Ocaml-mad 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 2 of the License, or * (at your option) any later version. * * Ocaml-mad 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 Ocaml-mad; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * An mp3 to wav converter using OCaml-Mad. * * @author Samuel Mimram *) (* $Id$ *) (* TODO: we don't need the tagging phase *) open Unix let src = ref "" let dst = ref "" let output_int chan n = output_char chan (char_of_int ((n lsr 0) land 0xff)); output_char chan (char_of_int ((n lsr 8) land 0xff)); output_char chan (char_of_int ((n lsr 16) land 0xff)); output_char chan (char_of_int ((n lsr 24) land 0xff)) let output_short chan n = output_char chan (char_of_int ((n lsr 0) land 0xff)); output_char chan (char_of_int ((n lsr 8) land 0xff)) let progress_bar = let spin = ref 0 in fun title pos tot -> let nbeq = 40 in let n = min (100. *. float_of_int pos /. float_of_int tot) 100. in let e = int_of_float (n /. 100. *. float_of_int nbeq) in Printf.printf "\r%s %6.2f%% [" title n; for _ = 1 to e do Printf.printf "=" done; if e != nbeq then Printf.printf ">"; for _ = e + 2 to nbeq do Printf.printf " " done; Printf.printf "] "; incr spin; if !spin > 4 then spin := 1; Printf.printf "%c%!" ( if n = 100. then ' ' else ( match !spin with | 1 -> '|' | 2 -> '/' | 3 -> '-' | 4 -> '\\' | _ -> failwith "this did not happen" ) ) let usage = "usage: mp32wav [options] source destination" let _ = Arg.parse [] (let pnum = ref (-1) in fun s -> incr pnum; match !pnum with | 0 -> src := s | 1 -> dst := s | _ -> Printf.eprintf "Error: too many arguments\n"; exit 1) usage; if !src = "" || !dst = "" then ( Printf.printf "%s\n" usage; exit 1 ); (* Using mad to decode the mp3. *) let tmpdst, oc = Filename.open_temp_file ~mode:[Open_binary] "mp32wav" ".raw" in let is_first = ref true in let channels = ref 2 in let samplerate = ref 44100 in let tot = (Unix.stat !src).Unix.st_size in let mf = Mad.openfile !src in ( try while true do let d = Mad.decode_frame mf in if !is_first then begin let sr, ch, _ = Mad.get_output_format mf in samplerate := sr; channels := ch; is_first := false end; output_string oc d; progress_bar "Decoding mp3:" (Mad.get_current_position mf) tot done with Mad.End_of_stream -> close_out oc; Mad.close mf ); Printf.printf "\n"; (* Do the wav stuff. *) let datalen = (stat tmpdst).st_size in let ic = open_in_bin tmpdst in let oc = open_out_bin !dst in output_string oc "RIFF"; output_int oc (4 + 24 + 8 + datalen); output_string oc "WAVE"; output_string oc "fmt "; output_int oc 16; output_short oc 1; (* WAVE_FORMAT_PCM *) output_short oc 2; (* channels *) output_int oc !samplerate; (* freq *) output_int oc (!samplerate * !channels * 2); (* bytes / s *) output_short oc (!channels * 2); (* block alignment *) output_short oc 16; (* bits per sample *) output_string oc "data"; (* TODO: uncomment the following line if you only hear noise *) (* output_char oc '\000'; *) output_int oc datalen; (let buflen = 256 * 1024 in let buf = Bytes.create buflen in let r = ref 1 in let pos = ref 0 in let tot = datalen in while !r <> 0 do r := input ic buf 0 buflen; output oc buf 0 !r; pos := !pos + !r; progress_bar "Tagging wav: " !pos tot done); close_in ic; close_out oc; Unix.unlink tmpdst; Printf.printf "\n" ocaml-mad-0.5.0/examples/mp3info.ml000066400000000000000000000004511373734671600171120ustar00rootroot00000000000000let info file = let mf = Mad.openfile file in ignore (Mad.decode_frame mf); let sample_freq, channels, _ = Mad.get_output_format mf in Mad.close mf; Printf.printf "Samplefreq:\t%dHz\nChannels\t%d\nDuration:\t%fs\n" sample_freq channels (Mad.duration file) let _ = info Sys.argv.(1) ocaml-mad-0.5.0/examples/mp3stream2wav.ml000066400000000000000000000106611373734671600202560ustar00rootroot00000000000000(* * Copyright 2003-2006 Savonet team * * This file is part of OCaml-mad. * * Ocaml-mad 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 2 of the License, or * (at your option) any later version. * * Ocaml-mad 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 Ocaml-mad; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * An mp3 to wav converter using OCaml-Mad. * * @author Samuel Mimram *) (* $Id$ *) (* TODO: we don't need the tagging phase *) open Unix let src = ref "" let dst = ref "" let output_int chan n = output_char chan (char_of_int ((n lsr 0) land 0xff)); output_char chan (char_of_int ((n lsr 8) land 0xff)); output_char chan (char_of_int ((n lsr 16) land 0xff)); output_char chan (char_of_int ((n lsr 24) land 0xff)) let output_short chan n = output_char chan (char_of_int ((n lsr 0) land 0xff)); output_char chan (char_of_int ((n lsr 8) land 0xff)) let progress_bar = let spin = ref 0 in fun title pos tot -> let nbeq = 40 in let n = min (100. *. float_of_int pos /. float_of_int tot) 100. in let e = int_of_float (n /. 100. *. float_of_int nbeq) in Printf.printf "\r%s %6.2f%% [" title n; for _ = 1 to e do Printf.printf "=" done; if e != nbeq then Printf.printf ">"; for _ = e + 2 to nbeq do Printf.printf " " done; Printf.printf "] "; incr spin; if !spin > 4 then spin := 1; Printf.printf "%c%!" ( if n = 100. then ' ' else ( match !spin with | 1 -> '|' | 2 -> '/' | 3 -> '-' | 4 -> '\\' | _ -> failwith "this did not happen" ) ) let usage = "usage: mp32wav [options] source destination" let _ = Arg.parse [] (let pnum = ref (-1) in fun s -> incr pnum; match !pnum with | 0 -> src := s | 1 -> dst := s | _ -> Printf.eprintf "Error: too many arguments\n"; exit 1) usage; if !src = "" || !dst = "" then ( Printf.printf "%s\n" usage; exit 1 ); (* Using mad to decode the mp3. *) let tmpdst, oc = Filename.open_temp_file ~mode:[Open_binary] "mp32wav" ".raw" in let is_first = ref true in let channels = ref 2 in let samplerate = ref 44100 in let tot = (Unix.stat !src).Unix.st_size in let fd = Unix.openfile !src [Unix.O_RDONLY] 0o600 in let read = Unix.read fd in let seek pos = Unix.lseek fd pos Unix.SEEK_SET in let tell () = Unix.lseek fd 0 Unix.SEEK_CUR in Mad.skip_id3tags ~read ~seek ~tell; let mf = Mad.openstream (Unix.read fd) in ( try while true do let d = Mad.decode_frame mf in if !is_first then begin let sr, ch, _ = Mad.get_output_format mf in samplerate := sr; channels := ch; is_first := false end; output_string oc d; progress_bar "Decoding mp3:" (tell ()) tot done with Mad.End_of_stream -> close_out oc; Mad.close mf ); Printf.printf "\n"; (* Do the wav stuff. *) let datalen = (stat tmpdst).st_size in let ic = open_in_bin tmpdst in let oc = open_out_bin !dst in output_string oc "RIFF"; output_int oc (4 + 24 + 8 + datalen); output_string oc "WAVE"; output_string oc "fmt "; output_int oc 16; output_short oc 1; (* WAVE_FORMAT_PCM *) output_short oc 2; (* channels *) output_int oc !samplerate; (* freq *) output_int oc (!samplerate * !channels * 2); (* bytes / s *) output_short oc (!channels * 2); (* block alignment *) output_short oc 16; (* bits per sample *) output_string oc "data"; (* TODO: uncomment the following line if you only hear noise *) (* output_char oc '\000'; *) output_int oc datalen; (let buflen = 256 * 1024 in let buf = Bytes.create buflen in let r = ref 1 in let pos = ref 0 in let tot = datalen in while !r <> 0 do r := input ic buf 0 buflen; output oc buf 0 !r; pos := !pos + !r; progress_bar "Tagging wav: " !pos tot done); close_in ic; close_out oc; Unix.unlink tmpdst; Printf.printf "\n" ocaml-mad-0.5.0/mad.opam000066400000000000000000000022671373734671600150150ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.5.0" synopsis: "Mad decoding library" description: "Bindings for the mad library which provides functions for encoding wave audio files into mp3" maintainer: ["The Savonet Team "] authors: ["The Savonet Team "] license: "GPL-2.0" homepage: "https://github.com/savonet/ocaml-mad" bug-reports: "https://github.com/savonet/ocaml-mad/issues" depends: [ "dune" {> "2.0"} "dune-configurator" ] conflicts: [ "liquidsoap" {< "1.5.0"} ] build: [ ["dune" "subst"] {pinned} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/savonet/ocaml-mad.git" depexts: [ ["libmad-dev"] {os-distribution = "alpine"} ["libmad"] {os-distribution = "archlinux"} ["libmad-devel"] {os-distribution = "centos"} ["libmad-devel"] {os-distribution = "fedora"} ["libmad-devel"] {os-family = "suse"} ["libmad0-dev"] {os-family = "debian"} ["libmad"] {os-distribution = "nixos"} ["mad"] {os = "macos" & os-distribution = "homebrew"} ] ocaml-mad-0.5.0/mad.opam.template000066400000000000000000000005721373734671600166240ustar00rootroot00000000000000depexts: [ ["libmad-dev"] {os-distribution = "alpine"} ["libmad"] {os-distribution = "archlinux"} ["libmad-devel"] {os-distribution = "centos"} ["libmad-devel"] {os-distribution = "fedora"} ["libmad-devel"] {os-family = "suse"} ["libmad0-dev"] {os-family = "debian"} ["libmad"] {os-distribution = "nixos"} ["mad"] {os = "macos" & os-distribution = "homebrew"} ] ocaml-mad-0.5.0/src/000077500000000000000000000000001373734671600141565ustar00rootroot00000000000000ocaml-mad-0.5.0/src/config/000077500000000000000000000000001373734671600154235ustar00rootroot00000000000000ocaml-mad-0.5.0/src/config/discover.ml000066400000000000000000000011301373734671600175660ustar00rootroot00000000000000module C = Configurator.V1 let () = C.main ~name:"mad-pkg-config" (fun c -> let default : C.Pkg_config.package_conf = { libs = ["-lmad"]; cflags = [] } in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> ( match C.Pkg_config.query_expr_err pc ~package:"mad" ~expr:"mad" with | Error msg -> failwith msg | Ok deps -> deps ) in C.Flags.write_sexp "c_flags.sexp" conf.cflags; C.Flags.write_sexp "c_library_flags.sexp" conf.libs) ocaml-mad-0.5.0/src/config/dune000066400000000000000000000000751373734671600163030ustar00rootroot00000000000000(executable (name discover) (libraries dune.configurator)) ocaml-mad-0.5.0/src/dune000066400000000000000000000004711373734671600150360ustar00rootroot00000000000000(library (name mad) (public_name mad) (synopsis "OCaml bindings for mad") (foreign_stubs (language c) (names mad_stubs) (flags (:include c_flags.sexp))) (c_library_flags (:include c_library_flags.sexp))) (rule (targets c_flags.sexp c_library_flags.sexp) (action (run ./config/discover.exe))) ocaml-mad-0.5.0/src/mad.ml000066400000000000000000000071121373734671600152520ustar00rootroot00000000000000(* * Copyright 2003-2006 Savonet team * * This file is part of Ocaml-mad. * * Ocaml-mad 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 2 of the License, or * (at your option) any later version. * * Ocaml-mad 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 Ocaml-mad; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Functions for decoding mp3 files using libmad. * * @author Samuel Mimram *) (* $Id$ *) type read = bytes -> int -> int -> int type mad_file type mpeg_layer = Layer_I | Layer_II | Layer_III type emphasis = None | MS_50_15 | CCITT_J_17 | Reserved type channel_mode = Single_channel | Dual_channel | Joint_stereo | Stereo type frame_format = { layer : mpeg_layer; mode : channel_mode; emphasis : emphasis; bitrate : int; samplerate : int; channels : int; samples_per_channel : int; original : bool; copyright : bool; private_bit : bool; } exception Mad_error of string exception Read_error of string exception End_of_stream exception Openfile_error of string exception Closefile_error of string let _ = Callback.register_exception "mad_exn_mad_error" (Mad_error ""); Callback.register_exception "mad_exn_read_error" (Read_error ""); Callback.register_exception "mad_exn_end_of_stream" End_of_stream; Callback.register_exception "mad_exn_openfile_error" (Openfile_error ""); Callback.register_exception "mad_exn_closefile_error" (Closefile_error "") external openfile : string -> mad_file = "ocaml_mad_openfile" external openstream : read -> mad_file = "ocaml_mad_openstream" external skip_id3tags : read -> (int -> int) -> (unit -> int) -> unit = "ocaml_mad_skip_id3tag" let skip_id3tags ~read ~seek ~tell = skip_id3tags read seek tell external close : mad_file -> unit = "ocaml_mad_close" external get_current_position : mad_file -> int = "ocaml_mad_get_current_position" external get_current_time : mad_file -> int -> int = "ocaml_mad_time" type time_unit = | Hours | Minutes | Seconds | Deciseconds | Centiseconds | Milliseconds let int_of_time_unit = function | Hours -> -2 | Minutes -> -1 | Seconds -> 0 | Deciseconds -> 10 | Centiseconds -> 100 | Milliseconds -> 1000 let get_current_time dec u = get_current_time dec (int_of_time_unit u) external skip_frame : mad_file -> unit = "ocaml_mad_skip_frame" external decode_frame : mad_file -> string = "ocaml_mad_decode_frame" external decode_frame_float : mad_file -> float array array = "ocaml_mad_decode_frame_float" external decode_frame_float_ba : mad_file -> (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t array = "ocaml_mad_decode_frame_float_ba" external get_frame_format : mad_file -> frame_format = "ocaml_mad_get_frame_format" let get_output_format mf = let header = get_frame_format mf in (header.samplerate, header.channels, header.samples_per_channel) let duration file = let mf = openfile file in let close () = try close mf with _ -> () in try begin try while true do skip_frame mf done with _ -> () end; let ret = float (get_current_time mf Centiseconds) /. 100. in close (); ret with _ -> close (); 0. ocaml-mad-0.5.0/src/mad.mli000066400000000000000000000102531373734671600154230ustar00rootroot00000000000000(* * Copyright 2003-2006 Savonet team * * This file is part of Ocaml-mad. * * Ocaml-mad 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 2 of the License, or * (at your option) any later version. * * Ocaml-mad 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 Ocaml-mad; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Functions for decoding mp3 files using the libmad. * * @author Samuel Mimram *) (* $Id$ *) (** {1 Exceptions} *) (** An error occured with libmad. *) exception Mad_error of string (** An error occured while reading a file. *) exception Read_error of string (** The end of the mp3 stream was reached. *) exception End_of_stream (** Could not open a file. *) exception Openfile_error of string (** Could not close a file. *) exception Closefile_error of string (** {1 Decoding files} *) (** An mp3 file opened for decoding. *) type mad_file type mpeg_layer = Layer_I | Layer_II | Layer_III type emphasis = None | MS_50_15 | CCITT_J_17 | Reserved type channel_mode = Single_channel | Dual_channel | Joint_stereo | Stereo type frame_format = { layer : mpeg_layer; mode : channel_mode; emphasis : emphasis; bitrate : int; samplerate : int; channels : int; samples_per_channel : int; original : bool; copyright : bool; private_bit : bool; } (** Type for abstract reader. *) type read = bytes -> int -> int -> int (** * Open an mp3 file. * * @raise Openfile_error if an error occured while trying to open the file. *) val openfile : string -> mad_file (** * [openstream read_func] opens a stream where [read_func n] should be a * function which returns [n] bytes of data or less, the second component of * the result being the number of bytes to read in the fist component. *) val openstream : read -> mad_file (** * Skip ID3 tags that may be present at * the beginning of a stream. This function * may be used to a mp3 file opened using [openstream]. * ID3 tags are always skipped when using [openfile]. * * [seek] is a callback to seek to an absolute * position on the encoded data, and [tell] a callback * to fetch the current position. [read] is the reading * callback. *) val skip_id3tags : read:read -> seek:(int -> int) -> tell:(unit -> int) -> unit (** * Close an mp3 file previously opened with [openfile]. * * @raise Closefile_error if an error occured while trying to close the file. *) val close : mad_file -> unit (** * Get the current position (in bytes) of the decoder in the mp3 file which * should have been opened with [openfile]. *) val get_current_position : mad_file -> int type time_unit = | Hours | Minutes | Seconds | Deciseconds | Centiseconds | Milliseconds (** * Get the current time position (in the given unit) of the decoder. *) val get_current_time : mad_file -> time_unit -> int (** Decode an mp3 frame. * Returned data in interleaved when * there are two channels, and mono data * when there is only one. *) val decode_frame : mad_file -> string (** Decode an mp3 frame. *) val decode_frame_float : mad_file -> float array array val decode_frame_float_ba : mad_file -> (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t array (** Skip one frame. The current time/position is * updated but the frame is not decoded. *) val skip_frame : mad_file -> unit (* * Get the format of the latest decoded frame. This should be called after [decode_frame] or * [decode_frame_float]. *) val get_frame_format : mad_file -> frame_format (* This function is DEPRECATED. Please use [get_frame_format] instead. *) val get_output_format : mad_file -> int * int * int (** Compute the duration of a file, in seconds. * Never raises any exception, but returns 0. in case of error. *) val duration : string -> float ocaml-mad-0.5.0/src/mad_stubs.c000066400000000000000000000505551373734671600163150ustar00rootroot00000000000000/* * OCaml bindings for libmad * * Copyright 2001 Bertrand Petit * Copyright 2003-2006 Savonet team * * This file is part of Ocaml-mad. * The libmad's stubs are based on madlld (see README for details). * * Ocaml-mad 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 2 of the License, or * (at your option) any later version. * * Ocaml-mad 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 Ocaml-mad; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @author Samuel Mimram, David Baelde */ #define CAML_INTERNALS #include #include #include #include #include #include #include #include #ifdef WIN32 #include #endif #include #include #ifndef Bytes_val #define Bytes_val String_val #endif #include #include #include #include #ifdef __MINGW32__ #include #else #include #endif #include #include // The theoretical maximum frame size is 2881 bytes, // MPEG 2.5 Layer II, 8000 Hz @ 160 kbps, with a padding slot plus 8 byte // MAD_BUFFER_GUARD. #define READ_SIZE 4096 #define BUFFER_SIZE READ_SIZE + MAD_BUFFER_GUARD #define FRAME_SIZE 2881 struct madfile__t { struct mad_stream stream; struct mad_frame frame; struct mad_synth synth; mad_timer_t timer; FILE *fd; value read_func; unsigned char buf[BUFFER_SIZE]; int eof; value data; }; typedef struct madfile__t madfile_t; /* Utility to scale and round samples to 16 bits * It converts a sample from mad's fixed point number format to an unsigned * short (16 bits). * * Shamelessly taken from the MPlayer source code. */ static short short_of_madfixed(mad_fixed_t sample) { /* A fixed point number is formed of the following bit pattern: * * SWWWFFFFFFFFFFFFFFFFFFFFFFFFFFFF * MSB LSB * S ==> Sign (0 is positive, 1 is negative) * W ==> Whole part bits * F ==> Fractional part bits * * This pattern contains MAD_F_FRACBITS fractional bits, one * should alway use this macro when working on the bits of a fixed * point number. It is not guaranteed to be constant over the * different platforms supported by libmad. * * The unsigned short value is formed by the least significant * whole part bit, followed by the 15 most significant fractional * part bits. */ /* round */ sample += (1L << (MAD_F_FRACBITS - 16)); /* clip */ if (sample >= MAD_F_ONE) sample = MAD_F_ONE - 1; else if (sample < -MAD_F_ONE) sample = -MAD_F_ONE; /* quantize */ return sample >> (MAD_F_FRACBITS + 1 - 16); return (short)sample; } #define Madfile_val(v) (*((madfile_t **)Data_custom_val(v))) static void finalize_madfile(value madf) { madfile_t *mf = Madfile_val(madf); if (mf->read_func) caml_remove_generational_global_root(&mf->read_func); if (mf->data) caml_remove_generational_global_root(&mf->data); mad_synth_finish(&mf->synth); mad_frame_finish(&mf->frame); mad_stream_finish(&mf->stream); free(mf); } static struct custom_operations madfile_ops = { "ocaml_mad_madfile", finalize_madfile, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; static inline madfile_t *create_mf() { madfile_t *mf; mf = malloc(sizeof(madfile_t)); mad_stream_init(&mf->stream); mad_frame_init(&mf->frame); mad_synth_init(&mf->synth); mad_timer_reset(&mf->timer); mf->read_func = (value)NULL; mf->eof = 0; mf->data = (value)NULL; return (mf); } /* Returns a "normal" 4-bytes integer from * a synchsafe integer */ int unsynchsafe(unsigned int in) { int out = 0, i; unsigned int mask = 0x7F000000; for (i = 0; i < 4; ++i) { out >>= 1; out |= in & mask; mask >>= 8; } return out; } // TODO: unify file/callback API? CAMLprim value ocaml_mad_openfile(value file) { CAMLparam1(file); CAMLlocal1(block); madfile_t *mf; #ifdef WIN32 FILE *fd; wchar_t *fname = caml_stat_strdup_to_os(String_val(file)); errno_t err = _wfopen_s(&fd, fname, L"rb"); free(fname); if (err != 0) caml_raise_with_arg(*caml_named_value("mad_exn_openfile_error"), caml_copy_string(strerror(err))); #else FILE *fd = fopen(String_val(file), "rb"); #endif if (!fd) caml_raise_with_arg(*caml_named_value("mad_exn_openfile_error"), caml_copy_string(strerror(errno))); /* Remove ID3 tag * Ref: http://www.id3.org/id3v2.4.0-structure */ char id3_header[3]; uint32_t id3_len; int footer_len = 0; fread(&id3_header, sizeof(char), 3, fd); /* Check for ID3 tag magic */ if ((id3_header[0] == 0x49) & (id3_header[1] == 0x44) & (id3_header[2] == 0x33)) { /* Read version and flags */ fread(&id3_header, sizeof(char), 3, fd); /* Check for footer flag */ if (id3_header[2] & 0x10) // 0b00010000 doesn't seem to work will all compilers.. footer_len = 10; /* Get synchsafe len of ID3 tag */ fread(&id3_len, sizeof(char), 4, fd); fseek(fd, unsynchsafe(ntohl(id3_len)) + footer_len, SEEK_CUR); } else rewind(fd); mf = create_mf(); mf->fd = fd; if (!mf->fd) caml_raise_with_arg(*caml_named_value("mad_exn_openfile_error"), caml_copy_string(strerror(errno))); memset(mf->buf, 0, BUFFER_SIZE); // The amount of data "secretly" owned by the madfile_t may be underestimated // here since I only take into account mf->buf, while it may be possible // that the mad_*_init functions also allocate stuff. block = caml_alloc_custom(&madfile_ops, sizeof(madfile_t *), BUFFER_SIZE, 1000000); Madfile_val(block) = mf; CAMLreturn(block); } CAMLprim value ocaml_mad_openstream(value read_func) { CAMLparam1(read_func); CAMLlocal1(block); madfile_t *mf; mf = create_mf(); mf->read_func = read_func; caml_register_generational_global_root(&mf->read_func); mf->data = caml_alloc_string(BUFFER_SIZE); caml_register_generational_global_root(&mf->data); mf->fd = 0; memset(mf->buf, 0, BUFFER_SIZE); block = caml_alloc_custom(&madfile_ops, sizeof(madfile_t *), 0, 1); Madfile_val(block) = mf; CAMLreturn(block); } CAMLprim value ocaml_mad_close(value madf) { CAMLparam1(madf); madfile_t *mf = Madfile_val(madf); if (!mf->read_func && fclose(mf->fd) != 0) caml_raise_with_arg(*caml_named_value("mad_exn_closefile_error"), caml_copy_string(strerror(errno))); CAMLreturn(Val_unit); } CAMLprim value ocaml_mad_skip_id3tag(value read, value seek, value tell) { CAMLparam3(read, seek, tell); CAMLlocal3(ret, buf, s); /* These values are used to * store integers. Therefore, they do * not need to be protected. */ value initial_position; int readlen; /* Get initial position. */ initial_position = Int_val(caml_callback(tell, Val_unit)); /* Remove ID3 tag * Ref: http://www.id3.org/id3v2.4.0-structure */ uint32_t *id3_len; int footer_len = 0; /* Here we assume that such small read length * will always have either 0 (end of stream) * or the right amount of data... */ buf = caml_alloc_string(4); ret = caml_callback3(read, buf, Val_int(0), Val_int(3)); readlen = Int_val(ret); if (readlen == 0) { caml_raise_constant(*caml_named_value("mad_exn_end_of_stream")); } const char *id3_header = (const char *)String_val(buf); /* Check for ID3 tag magic */ if ((id3_header[0] == 0x49) & (id3_header[1] == 0x44) & (id3_header[2] == 0x33)) { /* Read version and flags */ ret = caml_callback3(read, buf, Val_int(0), Val_int(3)); readlen = Int_val(ret); if (readlen == 0) { caml_raise_constant(*caml_named_value("mad_exn_end_of_stream")); } id3_header = (const char *)String_val(buf); /* Check for footer flag */ if (id3_header[2] & 0x10) // 0b00010000 doesn't seem to work will all compilers.. footer_len = 10; /* Get synchsafe len of ID3 tag */ ret = caml_callback3(read, buf, Val_int(0), Val_int(3)); readlen = Int_val(ret); if (readlen == 0) { caml_raise_constant(*caml_named_value("mad_exn_end_of_stream")); } id3_len = (uint32_t *)String_val(buf); int position = Int_val(caml_callback(tell, Val_unit)); caml_callback( seek, Val_int(position + unsynchsafe(ntohl(*id3_len)) + footer_len)); } else caml_callback(seek, initial_position); CAMLreturn(Val_unit); } CAMLprim value ocaml_mad_get_current_position(value madf) { CAMLparam1(madf); madfile_t *mf = Madfile_val(madf); if (mf->read_func) caml_raise_with_arg(*caml_named_value("mad_exn_closefile_error"), caml_copy_string("Not created with openfile.")); int pos = (int)ftell(mf->fd); CAMLreturn(Val_int(pos)); } /* * Shamelessly inspired of the Madlld source code. */ static void mf_fill_buffer(madfile_t *mf) { CAMLparam0(); if (mf->eof) return; /* The input bucket must be filled if it becomes empty */ if (mf->stream.buffer == NULL || mf->stream.error == MAD_ERROR_BUFLEN) { size_t read_size, remaining; unsigned char *read_start; /* {1} libmad may not consume all bytes of the input * buffer. If the last frame in the buffer is not wholly * contained by it, then that frame's start is pointed by * the next_frame member of the Stream structure. This * common situation occurs when mad_frame_decode() fails, * sets the stream error code to MAD_ERROR_BUFLEN, and * sets the next_frame pointer to a non NULL value. (See * also the comment marked {2} bellow.) * * When this occurs, the remaining unused bytes must be * put back at the beginning of the buffer and taken in * account before refilling the buffer. This means that * the input buffer must be large enough to hold a whole * frame at the highest observable bit-rate (currently 448 * kb/s). */ if (mf->stream.error != MAD_ERROR_BUFLEN) { remaining = 0; } else if (mf->stream.next_frame) { remaining = mf->stream.bufend - mf->stream.next_frame; } else if ((mf->stream.bufend - mf->stream.buffer) < BUFFER_SIZE) { remaining = mf->stream.bufend - mf->stream.buffer; } else { remaining = BUFFER_SIZE - FRAME_SIZE; } if (remaining) memmove(mf->buf, mf->stream.bufend - remaining, remaining); read_start = mf->buf + remaining; read_size = READ_SIZE - remaining; /* Fill-in the buffer. If an error occurs print a message * and leave the decoding loop. If the end of stream is * reached we also leave the loop but the return status is * left untouched. */ if (mf->read_func) { read_size = Int_val(caml_callback3(mf->read_func, mf->data, Val_int(0), Val_int(read_size))); if (read_size > 0) memcpy(read_start, String_val(mf->data), read_size); else if (read_size == 0) mf->eof = 1; else caml_raise_with_arg(*caml_named_value("mad_exn_read_error"), caml_copy_string("reading callback error")); } else { read_size = fread(read_start, 1, read_size, mf->fd); if (read_size <= 0) { if (ferror(mf->fd)) { /* Read error on bitstream. */ caml_raise_with_arg(*caml_named_value("mad_exn_read_error"), caml_copy_string((char *)strerror(errno))); } if (feof(mf->fd)) mf->eof = 1; } } /* {3} When decoding the last frame of a file, it must be * followed by MAD_BUFFER_GUARD zero bytes if one wants to * decode that last frame. When the end of file is * detected we append that quantity of bytes at the end of * the available data. Note that the buffer can't overflow * as the guard size was allocated but not used the the * buffer managment code. (See also the comment marked * {1}.) * * In a message to the mad-dev mailing list on May 29th, * 2001, Rob leslie explains the guard zone as follows: * * "The reason for MAD_BUFFER_GUARD has to do with the * way decoding is performed. In Layer III, Huffman * decoding may inadvertently read a few bytes beyond * the end of the buffer in the case of certain invalid * input. This is not detected until after the fact. To * prevent this from causing problems, and also to * ensure the next frame's main_data_begin pointer is * always accessible, MAD requires MAD_BUFFER_GUARD * (currently 8) bytes to be present in the buffer past * the end of the current frame in order to decode the * frame." */ if (mf->eof) { read_size += MAD_BUFFER_GUARD; memset(mf->buf + read_size + remaining, 0, MAD_BUFFER_GUARD); } /* Pipe the new buffer content to libmad's stream decoder * facility. */ mad_stream_buffer(&mf->stream, mf->buf, read_size + remaining); mf->stream.error = 0; } CAMLreturn0; } /* Returns 1 if a recoverable error occured, 0 else. */ static int mf_decode(madfile_t *mf, int synth) { int dec; caml_enter_blocking_section(); /* Decode the next mpeg frame. The streams is read from the * buffer, its constituents are break down and stored the the * Frame structure, ready for examination/alteration or PCM * synthesis. Decoding options are carried in the Frame * structure from the Stream structure. * * Error handling: mad_frame_decode() returns a non zero value * when an error occurs. The error condition can be checked in * the error member of the Stream structure. A mad error is * recoverable or fatal, the error status is checked with the * MAD_RECOVERABLE macro. * * {2} When a fatal error is encountered all decoding * activities shall be stopped, except when a MAD_ERROR_BUFLEN * is signaled. This condition means that the * mad_frame_decode() function needs more input to achieve * it's work. One shall refill the buffer and repeat the * mad_frame_decode() call. Some bytes may be left unused at * the end of the buffer if those bytes forms an incomplete * frame. Before refilling, the remainign bytes must be moved * to the begining of the buffer and used for input for the * next mad_frame_decode() invocation. (See the comments marked * {1} earlier for more details.) * * Recoverable errors are caused by malformed bit-streams, in * this case one can call again mad_frame_decode() in order to * skip the faulty part and re-sync to the next frame. */ dec = mad_frame_decode(&mf->frame, &mf->stream); if (dec) { caml_leave_blocking_section(); if (MAD_RECOVERABLE(mf->stream.error) || mf->stream.error == MAD_ERROR_BUFLEN) { if (mf->eof) caml_raise_constant(*caml_named_value("mad_exn_end_of_stream")); return 1; } else { caml_raise_with_arg(*caml_named_value("mad_exn_mad_error"), caml_copy_string(mad_stream_errorstr(&mf->stream))); } } /* Accounting. The computed frame duration is in the frame * header structure. It is expressed as a fixed point number * whole data type is mad_timer_t. It is different from the * samples fixed point format and unlike it, it can't directly * be added or substracted. The timer module provides several * functions to operate on such numbers. Be careful there, as * some functions of mad's timer module receive some of their * mad_timer_t arguments by value! */ mad_timer_add(&mf->timer, mf->frame.header.duration); /* Once decoded the frame is synthesized to PCM samples. No errors * are reported by mad_synth_frame(); */ if (synth == 1) mad_synth_frame(&mf->synth, &mf->frame); caml_leave_blocking_section(); return 0; } CAMLprim value ocaml_mad_decode_frame(value madf) { CAMLparam1(madf); CAMLlocal1(ret); madfile_t *mf = Madfile_val(madf); char *output_buf = NULL; int output_pos = 0; int i; int chans = MAD_NCHANNELS(&mf->frame.header); do { mf_fill_buffer(mf); } while (mf_decode(mf, 1) == 1); /* Synthesized samples must be converted from mad's fixed * point number to the consumer format. Here we use unsigned * 16 bit little endian integers on two channels. Integer samples * are temporarily stored in a buffer that is flushed when * full. */ ret = caml_alloc_string(mf->synth.pcm.length * chans * 2); output_buf = (char *)Bytes_val(ret); for (i = 0; i < mf->synth.pcm.length; i++) { unsigned short sample; /* Left channel */ sample = short_of_madfixed(mf->synth.pcm.samples[0][i]); *(output_buf + output_pos + 0) = sample & 0xff; *(output_buf + output_pos + 1) = sample >> 8; output_pos += 2; /* Right channel. If the decoded stream is monophonic then * the right output channel is the same as the left one * and we omit it here. */ if (chans > 1) { sample = short_of_madfixed(mf->synth.pcm.samples[1][i]); *(output_buf + output_pos + 0) = sample & 0xff; *(output_buf + output_pos + 1) = sample >> 8; output_pos += 2; } } CAMLreturn(ret); } CAMLprim value ocaml_mad_decode_frame_float(value madf) { CAMLparam1(madf); CAMLlocal1(ret); madfile_t *mf = Madfile_val(madf); int chans; int i, c; do { mf_fill_buffer(mf); } while (mf_decode(mf, 1) == 1); chans = MAD_NCHANNELS(&mf->frame.header); ret = caml_alloc_tuple(chans); for (c = 0; c < chans; c++) Store_field( ret, c, caml_alloc(mf->synth.pcm.length * Double_wosize, Double_array_tag)); for (c = 0; c < chans; c++) for (i = 0; i < mf->synth.pcm.length; i++) Store_double_field(Field(ret, c), i, mad_f_todouble(mf->synth.pcm.samples[c][i])); CAMLreturn(ret); } CAMLprim value ocaml_mad_decode_frame_float_ba(value madf) { CAMLparam1(madf); CAMLlocal1(ret); madfile_t *mf = Madfile_val(madf); float *data; int chans; int i, c; do { mf_fill_buffer(mf); } while (mf_decode(mf, 1) == 1); chans = MAD_NCHANNELS(&mf->frame.header); ret = caml_alloc_tuple(chans); for (c = 0; c < chans; c++) { caml_release_runtime_system(); data = malloc(mf->synth.pcm.length * sizeof(float)); for (i = 0; i < mf->synth.pcm.length; i++) data[i] = mad_f_todouble(mf->synth.pcm.samples[c][i]); caml_acquire_runtime_system(); Store_field(ret, c, caml_ba_alloc_dims(CAML_BA_C_LAYOUT | CAML_BA_MANAGED, 1, data, mf->synth.pcm.length)); } CAMLreturn(ret); } CAMLprim value ocaml_mad_skip_frame(value madf) { CAMLparam1(madf); madfile_t *mf = Madfile_val(madf); int err; do { mf_fill_buffer(mf); err = mf_decode(mf, 1); } while (!mf->eof && err == 1); if (err == 1) caml_raise_constant(*caml_named_value("mad_exn_end_of_stream")); CAMLreturn(Val_unit); } CAMLprim value ocaml_mad_time(value madf, value u) { CAMLparam1(madf); madfile_t *mf = Madfile_val(madf); CAMLreturn(Val_long(mad_timer_count(mf->timer, Int_val(u)))); } CAMLprim value ocaml_mad_get_frame_format(value madf) { CAMLparam1(madf); CAMLlocal1(ans); madfile_t *mf = Madfile_val(madf); int private = 0; if ((mf->frame.header.private_bits & MAD_PRIVATE_HEADER) > 0) private = 1; int copyright = 0; if ((mf->frame.header.flags & MAD_FLAG_COPYRIGHT) > 0) copyright = 1; int original = 0; if ((mf->frame.header.flags & MAD_FLAG_ORIGINAL) > 0) original = 1; ans = caml_alloc_tuple(10); Store_field(ans, 0, Val_int(mf->frame.header.layer - 1)); // Layers start at 1.. Store_field(ans, 1, Val_int(mf->frame.header.mode)); Store_field(ans, 2, Val_int(mf->frame.header.emphasis)); Store_field(ans, 3, Val_long(mf->frame.header.bitrate)); Store_field(ans, 4, Val_int(mf->synth.pcm.samplerate)); Store_field(ans, 5, Val_int(mf->synth.pcm.channels)); Store_field(ans, 6, Val_int(mf->synth.pcm.length)); Store_field(ans, 7, Val_bool(original)); Store_field(ans, 8, Val_bool(copyright)); Store_field(ans, 9, Val_bool(private)); CAMLreturn(ans); }