pax_global_header00006660000000000000000000000064140214307520014510gustar00rootroot0000000000000052 comment=7b0e5523f1122ce2c55233d0327a62471ece4d2e ocaml-vorbis-0.8.0/000077500000000000000000000000001402143075200141125ustar00rootroot00000000000000ocaml-vorbis-0.8.0/.github/000077500000000000000000000000001402143075200154525ustar00rootroot00000000000000ocaml-vorbis-0.8.0/.github/workflows/000077500000000000000000000000001402143075200175075ustar00rootroot00000000000000ocaml-vorbis-0.8.0/.github/workflows/main.yml000066400000000000000000000006621402143075200211620ustar00rootroot00000000000000name: 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 vorbis - run: opam install -t . ocaml-vorbis-0.8.0/.gitignore000066400000000000000000000000631402143075200161010ustar00rootroot00000000000000*~ _build *.byte *.native _tests .merlin *.install ocaml-vorbis-0.8.0/.ocamlformat000066400000000000000000000003201402143075200164120ustar00rootroot00000000000000profile = 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-vorbis-0.8.0/CHANGES000066400000000000000000000073141402143075200151120ustar00rootroot000000000000000.8.0 (08-03-2021) ===== * Use `bytes` instead of `string` in `File.Decoder.decode`. * Switch to `dune` 0.7.1 (08-29-2018) ===== * Fix compilation with OCaml >= 4.06 0.7.0 (05-28-2017) ===== * Allow any tag. 0.6.2 (03-08-2015) ===== * Switched to Bytes and uppercast_ascii APIs. * Changed types to match new ocaml-ogg's API. Should be fully backward compatible. 0.6.1 (04-10-2011) ===== * Added optional encoder field for headerout functions. 0.6.0 (04-07-2011) ===== * Changed Vorbis.File opening API * Fixed segfault when finalizing a file decoder. * Only encode or decode an array with the same number of channels that the encoder/decoder requires. * Cleaned unused exceptions. * Added function to return a string representation of the exceptions defined in this module. * Register previous function with Printexc.register_printer when available (ocaml >= 3.11.2) * Added decoding module for the new Ogg_demuxer module. 0.5.1 (14-10-2009) ===== * Added support for --enable-debugging configure option * Added NO_CUSTOM to build in standard mode. * 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. 0.5.0 (17-02-2009) ==== * Binded low-level decoding API in order to decode ogg streams. Previous Decoder module has been moved to File.Decoder * Added time_of_granulepos to get the relative time corresponding to a granulepos. 0.4.1 (16-04-2008) ===== * Minor fixes * More portable make invokation * Install .cmx file 0.4.0 (16-10-2007) ===== * Complete rewrite of the library in order to use ocaml-ogg. 0.3.1 (20-05-2007) ===== * Added decode_float to decode directly to float arrays. * Added encode_float to encode directly from float arrays. * Made the output format optional for function creating decoders since it is not used for float output. 0.3.0 (02-03-2007) ===== * Changed duration value from int to float for more precision. It is an interface change, hence the new version number. * Polishing and minor memory related fixes. 0.2.3 (11-11-2006) ===== * More releases of ocaml's master lock. * Fine-tuning of CAMLparams, cleaning up. 0.2.2 (07-07-2006) ===== * Added set_charset function. * Added blocking section in functions to open files. * Optional information reading, avoids the computation of the file duration. * Support for the "comment" metadata field. * Code hardening, cleanup and documentation. 0.2.1 (15-11-2005) ===== * Using caml_alloc_custom to create custom blocks. * Added open_dec_file function to handle decoding of streams using callback functions. * Added encode_buffer_part function to encode only a portion of a buffer. * Added get_dec_file_bitstream, get_dec_file_comments and get_dec_file_info functions. * Removed some unused fields in dec_params (sorry for the breakage of interface). * Fixed some memory leaks with tags. 0.2.0 (20-04-2005) ===== * Better conversion of the input audio data: downsampling supported, conversion from stereo to mono doesn't segfaults anymore. Added a blocking_section by the way, and a few inline. * Reverted removal of open_dec_fd. * Updated OCamlMakefile and improved build system. * Using caml namespace functions. * Added wav2ogg encoder example. 0.1.1 (30-06-2004) ===== * Cleanup of the stubs with better use of the CAML* macros * Prototype of "create_encoder" changed. * "get_header_frame" is removed (replaced by the new create_encoder). * Added "encoder_reset". * Removed "enc_serial_number" parameter (it is randomly generated by "create_encoder"). * Removed "open_dec_fd" since it is not necessary and fdopen(2) is not ANSI C. * Improved the mli documentation. 0.1.0 (05-02-2004) ===== * Initial release. ocaml-vorbis-0.8.0/COPYING000066400000000000000000000431311402143075200151470ustar00rootroot00000000000000 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-vorbis-0.8.0/README.md000066400000000000000000000010761402143075200153750ustar00rootroot00000000000000ocaml-vorbis ============ This package contains an OCaml interface for the `vorbis` library Please read the COPYING file before using this software. Prerequisites: ============== - ocaml - libvorbis - findlib - ocaml-ogg >= 0.7.0 - dune >= 2.0 Compilation: ============ ``` $ dune build ``` This should build both the native and the byte-code version of the extension library. Installation: ============= Via `opam`: ``` $ opam install vorbis ``` Via `dune` (for developers): ``` $ dune install ``` This should install the library file in the appropriate place. ocaml-vorbis-0.8.0/dune-project000066400000000000000000000006631402143075200164410ustar00rootroot00000000000000(lang dune 2.0) (version 0.8.0) (name vorbis) (source (github savonet/ocaml-vorbis)) (license GPL-2.0) (authors "The Savonet Team ") (maintainers "The Savonet Team ") (generate_opam_files true) (package (name vorbis) (synopsis "Bindings to libvorbis") (depends conf-libvorbis conf-pkg-config (dune (>= 2.0)) dune-configurator (ogg (>= 0.7.0))) ) ocaml-vorbis-0.8.0/examples/000077500000000000000000000000001402143075200157305ustar00rootroot00000000000000ocaml-vorbis-0.8.0/examples/.merlin000066400000000000000000000000321402143075200172120ustar00rootroot00000000000000B ../src S ../src PKG ogg ocaml-vorbis-0.8.0/examples/dune000066400000000000000000000003241402143075200166050ustar00rootroot00000000000000(executable (name ogg2wav) (modules ogg2wav) (libraries vorbis)) (executable (name stream2wav) (modules stream2wav) (libraries vorbis)) (executable (name wav2ogg) (modules wav2ogg) (libraries vorbis)) ocaml-vorbis-0.8.0/examples/ogg2wav.ml000066400000000000000000000110331402143075200176340ustar00rootroot00000000000000(* * Copyright 2003 Savonet team * * This file is part of OCaml-Vorbis. * * OCaml-Vorbis 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-Vorbis 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-Vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * An ogg to wav converter using OCaml-Vorbis. * * @author Samuel Mimram *) let bufsize = 16 * 1024 let src = ref "" let dst = ref "" open Unix 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: ogg2wav [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); let df, dfd = Vorbis.File.Decoder.openfile !src in let infos = Vorbis.File.Decoder.info df (-1) in let vdr, cmt = Vorbis.File.Decoder.comments df (-1) in let duration = Vorbis.File.Decoder.duration df (-1) in let samples = Vorbis.File.Decoder.samples df (-1) in Printf.printf "Input file characteristics: vorbis codec v%d, %d channels, %d Hz, %.02f \ s, %d samples\n" infos.Vorbis.vorbis_version infos.Vorbis.audio_channels infos.Vorbis.audio_samplerate duration samples; Printf.printf "* vendor: %s\n" vdr; List.iter (fun (c, v) -> Printf.printf "* %s: %s\n" (String.lowercase_ascii c) v) cmt; (* Using vorbis to decode the ogg. *) Printf.printf "\n"; let tmpdst, oc = Filename.open_temp_file ~mode:[Open_binary] "ogg2wav" ".raw" in (let buf = Bytes.create bufsize in let pos = ref 0 in let tot = samples in try while true do let r = Vorbis.File.Decoder.decode df buf 0 bufsize in output oc buf 0 r; pos := !pos + r; progress_bar "Decoding ogg:" (!pos / 4) tot done; close_out oc; Unix.close dfd with End_of_file -> close_out oc; Unix.close dfd); 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 44100; (* freq *) output_int oc (44100 * 2 * 2); (* bytes / s *) output_short oc (2 * 2); (* block alignment *) output_short oc 16; (* bits per sample *) output_string oc "data"; 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"; Gc.full_major () ocaml-vorbis-0.8.0/examples/stream2wav.ml000066400000000000000000000146061402143075200203640ustar00rootroot00000000000000(* * Copyright 2003 Savonet team * * This file is part of OCaml-Vorbis. * * OCaml-Vorbis 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-Vorbis 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-Vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * An ogg to wav converter using OCaml-Vorbis stream interface. * * @author Samuel Mimram *) (* $Id$ *) let bufsize = 1024 let src = ref "" let dst = ref "" open Unix 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: stream2wav [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); let sync, _ = Ogg.Sync.create_from_file !src in let eos = ref false in let rec fill os = let page = Ogg.Sync.read sync in try Ogg.Stream.put_page os page; if Ogg.Page.eos page then eos := true with Ogg.Bad_data -> fill os (*Do not care about page that are not for us.. *) in (* Test wether the stream contains vorbis *) let test_vorbis () = (* Get First page *) let page = Ogg.Sync.read sync in (* Check wether this is a b_o_s *) if not (Ogg.Page.bos page) then raise Not_found; (* Create a stream with this ID *) let serial = Ogg.Page.serialno page in let os = Ogg.Stream.create ~serial () in Ogg.Stream.put_page os page; (* Get first packet *) let packet = Ogg.Stream.get_packet os in if not (Vorbis.Decoder.check_packet packet) then raise Not_found; fill os; let page = Ogg.Sync.read sync in Ogg.Stream.put_page os page; let packet2 = Ogg.Stream.get_packet os in fill os; let page = Ogg.Sync.read sync in Ogg.Stream.put_page os page; let packet3 = Ogg.Stream.get_packet os in let decoder = Vorbis.Decoder.init packet packet2 packet3 in Printf.printf "Got a vorbis stream !\n"; flush_all (); (serial, os, decoder) in let rec init () = try test_vorbis () with (* Not_found is not catched: ogg stream always start with all b_o_s and we don't care about sequenced streams here *) | Ogg.Bad_data | Not_found -> Printf.printf "This stream was not vorbis..\n"; flush_all (); init () in let _, os, decoder = init () in let infos = Vorbis.Decoder.info decoder in let vdr, cmt = Vorbis.Decoder.comments decoder in Printf.printf "Input stream characteristics: vorbis codec v%d, %d channels, %d Hz\n" infos.Vorbis.vorbis_version infos.Vorbis.audio_channels infos.Vorbis.audio_samplerate; Printf.printf "* vendor: %s\n" vdr; List.iter (fun (c, v) -> Printf.printf "* %s: %s\n" (String.lowercase_ascii c) v) cmt; flush_all (); (* Using vorbis to decode the ogg. *) print_newline (); Printf.printf "Decoding stream..\n"; flush_all (); let tmpdst, oc = Filename.open_temp_file ~mode:[Open_binary] "stream2wav" ".raw" in (let chan _ = Array.make bufsize 0. in let buf = Array.init infos.Vorbis.audio_channels chan in try while true do try let r = Vorbis.Decoder.decode_pcm decoder os buf 0 bufsize in (* Yea, dirty quick hack ! *) let buf = Array.map (fun x -> Array.sub x 0 r) buf in let buf = Array.map (Array.map (fun x -> int_of_float (x *. 32767.))) buf in let chans = Array.length buf in Array.iteri (fun x _ -> for i = 0 to chans - 1 do output_short oc buf.(i).(x) done) buf.(0) with Ogg.Not_enough_data -> fill os done; close_out oc with _ -> close_out oc); Printf.printf "\n"; (* Do the wav stuff. *) let samplerate = infos.Vorbis.audio_samplerate in 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 infos.Vorbis.audio_channels; (* channels *) output_int oc samplerate; (* freq *) output_int oc (samplerate * 2 * 2); (* bytes / s *) output_short oc (2 * 2); (* block alignment *) output_short oc 16; (* bits per sample *) output_string oc "data"; 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"; Gc.full_major () ocaml-vorbis-0.8.0/examples/wav2ogg.ml000066400000000000000000000115401402143075200176370ustar00rootroot00000000000000(* * Copyright 2003 Savonet team * * This file is part of OCaml-Vorbis. * * OCaml-Vorbis 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-Vorbis 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-Vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * An wav to ogg converter using OCaml-Vorbis. * * @author Samuel Mimram, and many others... *) open Vorbis let src = ref "" let dst = ref "" let buflen = ref 1024 let input_string chan len = let ans = Bytes.create len in (* TODO: check length *) ignore (input chan ans 0 len); Bytes.unsafe_to_string ans let input_int chan = let buf = input_string chan 4 in int_of_char buf.[0] + (int_of_char buf.[1] lsl 8) + (int_of_char buf.[2] lsl 16) + (int_of_char buf.[3] lsl 24) let input_short chan = let buf = input_string chan 2 in int_of_char buf.[0] + (int_of_char buf.[1] lsl 8) let bitrate = ref 128000 let usage = "usage: wav2ogg [options] source destination" let _ = Arg.parse [ ( "--bitrate", Arg.Int (fun b -> bitrate := b * 1000), "Bitrate, in kilobits per second, defaults to 128kbps" ); ( "--buflen", Arg.Int (fun i -> buflen := i), "Size of chunks successively encoded" ); ] (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); let ic = open_in_bin !src in let oc = open_out_bin !dst in (* TODO: improve! *) if input_string ic 4 <> "RIFF" then invalid_arg "No RIFF tag"; ignore (input_string ic 4); if input_string ic 4 <> "WAVE" then invalid_arg "No WAVE tag"; if input_string ic 4 <> "fmt " then invalid_arg "No fmt tag"; let _ = input_int ic in let _ = input_short ic in (* TODO: should be 1 *) let channels = input_short ic in let infreq = input_int ic in let _ = input_int ic in (* bytes / s *) let _ = input_short ic in (* block align *) let bits = input_short ic in let fos buf = let len = String.length buf / (2 * channels) in let ans = Array.init channels (fun _ -> Array.make len 0.) in for i = 0 to len - 1 do for c = 0 to channels - 1 do let n = int_of_char buf.[(2 * channels * i) + (2 * c)] + (int_of_char buf.[(2 * channels * i) + (2 * c) + 1] lsl 8) in let n = if n land (1 lsl 15) = 0 then n else (n land 0b111111111111111) - 32768 in ans.(c).(i) <- float n /. 32768.; ans.(c).(i) <- max (-1.) (min 1. ans.(c).(i)) done done; ans in let enc = Encoder.create channels infreq (-1) !bitrate (-1) in let os = Ogg.Stream.create () in let encode buf = let fbuf = fos buf in Encoder.encode_buffer_float enc os fbuf 0 (Array.length fbuf.(0)) in let start = Unix.time () in Printf.printf "Input detected: PCM WAVE %d channels, %d Hz, %d bits\n%!" channels infreq bits; Printf.printf "Encoding to: OGG %d channels, %d Hz, %d kbps\nPlease wait...\n%!" channels infreq !bitrate; Encoder.headerout enc os [("ARTIST", "test")]; (* skip headers *) let rec aux () = let tag = input_string ic 4 in match tag with | "LIST" -> let n = input_int ic in let _ = input_string ic n in aux () | "data" -> () | _ -> invalid_arg "No data tag" in aux (); (* This ensures the actual audio data will start on a new page, as per * spec. *) let ph, pb = Ogg.Stream.flush_page os in output_string oc (ph ^ pb); let buflen = !buflen in let buf = Bytes.create buflen in begin try while true do try really_input ic buf 0 buflen; encode (Bytes.unsafe_to_string buf); while true do let ph, pb = Ogg.Stream.get_page os in output_string oc (ph ^ pb) done with Ogg.Not_enough_data -> () done with End_of_file -> () end; Encoder.end_of_stream enc os; begin try while true do let ph, pb = Ogg.Stream.get_page os in output_string oc (ph ^ pb) done with Ogg.Not_enough_data -> () end; close_in ic; close_out oc; Printf.printf "Finished in %.0f seconds.\n" (Unix.time () -. start); Gc.full_major () ocaml-vorbis-0.8.0/src/000077500000000000000000000000001402143075200147015ustar00rootroot00000000000000ocaml-vorbis-0.8.0/src/config/000077500000000000000000000000001402143075200161465ustar00rootroot00000000000000ocaml-vorbis-0.8.0/src/config/discover.ml000066400000000000000000000011671402143075200203230ustar00rootroot00000000000000module C = Configurator.V1 let () = C.main ~name:"vorbis-pkg-config" (fun c -> let default : C.Pkg_config.package_conf = { libs = ["-lvorbis"; "-lvorbisfile"; "-lvorbisenc"]; cflags = [] } in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> ( match C.Pkg_config.query pc ~package:"vorbis vorbisfile vorbisenc" with | None -> default | Some deps -> deps) in C.Flags.write_sexp "c_flags.sexp" conf.cflags; C.Flags.write_sexp "c_library_flags.sexp" conf.libs) ocaml-vorbis-0.8.0/src/config/dune000066400000000000000000000000751402143075200170260ustar00rootroot00000000000000(executable (name discover) (libraries dune.configurator)) ocaml-vorbis-0.8.0/src/dune000066400000000000000000000010361402143075200155570ustar00rootroot00000000000000(library (name vorbis) (public_name vorbis) (synopsis "OCaml bindings for libvorbis") (libraries ogg) (modules vorbis) (foreign_stubs (language c) (names vorbis_stubs) (flags (:include c_flags.sexp))) (c_library_flags (:include c_library_flags.sexp))) (library (name vorbis_decoder) (public_name vorbis.decoder) (synopsis "Vorbis decoder for the ogg-decoder library") (libraries ogg.decoder vorbis) (modules vorbis_decoder)) (rule (targets c_flags.sexp c_library_flags.sexp) (action (run ./config/discover.exe))) ocaml-vorbis-0.8.0/src/vorbis.ml000066400000000000000000000226601402143075200165450ustar00rootroot00000000000000(* * Copyright 2003-2011 Savonet team * * This file is part of Ocaml-vorbis. * * Ocaml-vorbis 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-vorbis 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-vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Decode from or encode to the Ogg Vorbis compressed audio format; or get * informations about an Ogg Vorbis file. * * @author Samuel Mimram *) (* $Id$ *) exception Invalid_parameters exception Invalid_channels exception Could_not_open_file exception Not_vorbis exception Hole_in_data exception Bad_link exception Version_mismatch exception Bad_header exception Read_error exception Internal_fault exception Invalid_argument exception Not_implemented exception Unknown_error of int exception Not_audio exception False exception Utf8_failure of string (* New register exception printer *) let string_of_exc e = let f s = Some s in match e with | Invalid_parameters -> f "Invalid vorbis parameters" | Invalid_channels -> f "Invalid vorbis channels" | Could_not_open_file -> f "Vorbis: could not open file" | Not_vorbis -> f "Bitstream is not Vorbis data" | Hole_in_data -> f "Interruption in the vorbis data (one of: garbage between pages, \ loss of sync followed by recapture, or a corrupt page)" | Bad_link -> f "An invalid vorbis stream section was supplied, or the requested \ link is corrupt" | Version_mismatch -> f "Vorbis bitstream version mismatch" | Bad_header -> f "Invalid Vorbis bitstream header" | Read_error -> f "Vorbis: read error" | Internal_fault -> f "Internal vorbis logic fault; indicates a bug or heap/stack \ corruption" | Invalid_argument -> f "Invalid vorbis setup request, e.g. out of range argument" | Not_implemented -> f "Unimplemented vorbis feature (e.g. -0.2 quality is only available \ in aoTuV's implementation)" | Unknown_error i -> f (Printf.sprintf "Unknown vorbis error %i (it should not have happened, please \ report)" i) | Not_audio -> f "Ogg packet doesn't contain audio data" | False -> f "Vorbis call returned a 'false' status (eg, playback is not in \ progress, and thus there is no instantaneous bitrate information to \ report.)" | Utf8_failure s -> f (Printf.sprintf "UTF8 failure in string: %S" s) | _ -> None let () = Printexc.register_printer string_of_exc let _ = Callback.register_exception "vorbis_exn_invalid_parameters" Invalid_parameters; Callback.register_exception "vorbis_exn_invalid_channels" Invalid_channels; Callback.register_exception "vorbis_exn_could_not_open_file" Could_not_open_file; Callback.register_exception "vorbis_exn_not_vorbis" Not_vorbis; Callback.register_exception "vorbis_exn_hole_in_data" Hole_in_data; Callback.register_exception "vorbis_exn_bad_link" Bad_link; Callback.register_exception "vorbis_exn_version_mismatch" Version_mismatch; Callback.register_exception "vorbis_exn_bad_header" Bad_header; Callback.register_exception "vorbis_exn_read_error" Read_error; Callback.register_exception "vorbis_exn_internal_fault" Internal_fault; Callback.register_exception "vorbis_exn_invalid" Invalid_argument; Callback.register_exception "vorbis_exn_not_implemented" Not_implemented; Callback.register_exception "vorbis_exn_not_audio" Not_audio; Callback.register_exception "vorbis_exn_unknown_error" (Unknown_error 0); Callback.register_exception "vorbis_exn_false" False; Callback.register_exception "vorbis_exn_utf8_failure" (Utf8_failure "") let tags m () = let ans = ref [] in let add t v = ans := (t, v) :: !ans in Hashtbl.iter add m; List.rev !ans let encoder_tag = "ocaml-vorbis by the savonet team (http://savonet.sf.net/)" module Encoder = struct type t external create : int -> int -> int -> int -> int -> t = "ocaml_vorbis_analysis_init" external create_vbr : int -> int -> float -> t = "ocaml_vorbis_analysis_init_vbr" external reset : t -> unit = "ocaml_vorbis_reset" external headerout_packetout : t -> (string * string) array -> Ogg.Stream.packet * Ogg.Stream.packet * Ogg.Stream.packet = "ocaml_vorbis_analysis_headerout" let headerout_packetout ?(encoder = encoder_tag) state tags = let tags = Array.of_list (tags @ [("ENCODER", encoder)]) in headerout_packetout state tags let headerout ?encoder state os tags = let p1, p2, p3 = headerout_packetout ?encoder state tags in Ogg.Stream.put_packet os p1; Ogg.Stream.put_packet os p2; Ogg.Stream.put_packet os p3 external get_channels : t -> int = "ocaml_vorbis_encode_get_channels" external encode_buffer_float : t -> Ogg.Stream.stream -> float array array -> int -> int -> unit = "ocaml_vorbis_encode_float" external time_of_granulepos : t -> Int64.t -> Nativeint.t = "ocaml_vorbis_encode_time_of_granulepos" (* We encode a buffer with 0 samples to finish * the stream, according to the documentation of * vorbis_analysis_wrote: * "A value of zero means all input data has been provided and * the compressed stream should be finalized." *) let end_of_stream enc os = let chans = get_channels enc in let data = Array.make chans [||] in encode_buffer_float enc os data 0 0 end let split_comment comment = try let equal_pos = String.index_from comment 0 '=' in let c1 = String.uppercase_ascii (String.sub comment 0 equal_pos) in let c2 = String.sub comment (equal_pos + 1) (String.length comment - equal_pos - 1) in (c1, c2) with Not_found -> (comment, "") type bitstream = int type info = { vorbis_version : int; audio_channels : int; audio_samplerate : int; bitrate_upper : int; bitrate_nominal : int; bitrate_lower : int; bitrate_window : int; } module File = struct module Decoder = struct type t external create : (int -> string * int) -> (int -> Unix.seek_command -> int) -> (unit -> int) -> t = "ocaml_vorbis_open_dec_stream" let openfile_with_fd fd = try create (fun n -> let buf = Bytes.create n in let r = Unix.read fd buf 0 n in (Bytes.unsafe_to_string buf, r)) (fun n cmd -> Unix.lseek fd n cmd) (fun () -> Unix.lseek fd 0 Unix.SEEK_CUR) with e -> Unix.close fd; raise e let openfile f = let fd = Unix.openfile f [Unix.O_RDONLY] 0o400 in (openfile_with_fd fd, fd) external decode_float : t -> float array array -> int -> int -> int = "ocaml_vorbis_decode_float" external decode_float_alloc : t -> int -> float array array = "ocaml_vorbis_decode_float_alloc" external decode : t -> bool -> int -> bool -> bytes -> int -> int -> int = "ocaml_vorbis_decode_byte" "ocaml_vorbis_decode" let decode df ?(big_endian = false) ?(sample_size = 2) ?(signed = true) buf ofs len = decode df big_endian sample_size signed buf ofs len external bitstream : t -> int = "ocaml_vorbis_get_dec_file_bitstream" external comments : t -> int -> string * string array = "ocaml_vorbis_get_dec_file_comments" let comments df bitstream = let vd, cmts = comments df bitstream in (vd, Array.to_list (Array.map split_comment cmts)) external info : t -> int -> info = "ocaml_vorbis_decoder_info" external bitrate : t -> int -> int = "ocaml_vorbis_decoder_bitrate" external duration : t -> int -> float = "ocaml_vorbis_decoder_time_total" external streams : t -> int = "ocaml_vorbis_decoder_streams" external serialnumber : t -> int -> int = "ocaml_vorbis_decoder_serialnumber" external samples : t -> int -> int = "ocaml_vorbis_decoder_pcm_total" end end module Decoder = struct type t external init : Ogg.Stream.packet -> Ogg.Stream.packet -> Ogg.Stream.packet -> t = "ocaml_vorbis_synthesis_init" external info : t -> info = "ocaml_vorbis_val_info_of_decoder" external comments : t -> string * string array = "ocaml_vorbis_val_comments_of_decoder" let comments dec = let vend, cmts = comments dec in (vend, Array.to_list (Array.map split_comment cmts)) external check_packet : Ogg.Stream.packet -> bool = "ocaml_vorbis_check_packet" external decode_pcm : t -> Ogg.Stream.stream -> float array array -> int -> int -> int = "ocaml_vorbis_decode_pcm" external restart : t -> unit = "ocaml_vorbis_synthesis_restart" end module Skeleton = struct external fisbone : Nativeint.t -> Int64.t -> Int64.t -> string -> Ogg.Stream.packet = "ocaml_vorbis_skeleton_fisbone" let fisbone ?(start_granule = Int64.zero) ?(headers = [("Content-type", "audio/vorbis")]) ~serialno ~samplerate () = let concat s (h, v) = Printf.sprintf "%s%s: %s\r\n" s h v in let s = List.fold_left concat "" headers in fisbone serialno samplerate start_granule s end ocaml-vorbis-0.8.0/src/vorbis.mli000066400000000000000000000223601402143075200167130ustar00rootroot00000000000000(* * Copyright 2003-2011 The Savonet team * * This file is part of Ocaml-vorbis. * * Ocaml-vorbis 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-vorbis 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-vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Decode from or encode to the Ogg Vorbis compressed audio format; * or get informations about an Ogg Vorbis file. * * @author Samuel Mimram, Julien Cristau, David Baelde *) (* $Id$ *) (** {1 Exceptions} *) (** The call returned a 'false' status (eg, ov_bitrate_instant * can return OV_FALSE if playback is not in progress, and thus * there is no instantaneous bitrate information to report. *) exception False (** Some parameters are invalid for this function. *) exception Invalid_parameters (** The given number of channels is invalid. *) exception Invalid_channels (** Invalid setup request, e.g. out of range argument. *) exception Invalid_argument (** The given file could not be opened. *) exception Could_not_open_file (** Bitstream is not Vorbis data. *) exception Not_vorbis (** Invalid Vorbis bitstream header. *) exception Bad_header (** A read from media returned an error. *) exception Read_error (** Ogg packet doesn't contain audio data *) exception Not_audio (** Internal logic fault; indicates a bug or heap/stack corruption. *) exception Internal_fault (** Indicates there was an interruption in the data (one of: garbage between * pages, loss of sync followed by recapture, or a corrupt page). *) exception Hole_in_data (** Indicates that an invalid stream section was supplied, * or the requested link is corrupt. *) exception Bad_link (** Invalid Vorbis bitstream header. *) exception Version_mismatch (** Unimplemented mode. *) exception Not_implemented (** An unknown error happened (it should not have happened, please report). *) exception Unknown_error of int (** Error while converting utf8. *) exception Utf8_failure of string (** Return a string representation * of an exception *) val string_of_exc : exn -> string option (** {1 Useful types} *) (** Index of a logical bitstream. The special value -1 means the physical * bitsream. *) type bitstream = int (** Vorbis informations about a file. *) type info = { vorbis_version : int; (** version of vorbis codec, must be 0 *) audio_channels : int; (** number of audio channels *) audio_samplerate : int; (** samplerate in Hertz *) bitrate_upper : int; bitrate_nominal : int; bitrate_lower : int; bitrate_window : int; } (** Create a list of vorbis tags. *) val tags : (string, string) Hashtbl.t -> unit -> (string * string) list (** {1 Operations with vorbis streams} *) (** {2 Encoding} *) module Encoder : sig (** Internal state of an encoder. *) type t (** [create chans rate max_br nom_br min_br] creates a new encoder with * [chans] channels, with sample rate [rate] Hz and with respectively [max_br], * [nom_br] and [min_br] as maximal, nominal and minimal bitrates (in bps). *) val create : int -> int -> int -> int -> int -> t (** [create_vbr chans rate quality] creates a new encoder in variable bitrate * with [chans] channels, with sample rate [rate] Hz and with quality * [quality], which should be between -1 and 1 (1 is the best). *) val create_vbr : int -> int -> float -> t val reset : t -> unit (** Encode a header given a list of tags. *) val headerout : ?encoder:string -> t -> Ogg.Stream.stream -> (string * string) list -> unit (** Encoder a header, but do not submit packet to * Ogg Stream. Usefull when multiplexing ogg streams * since the all first packets of each streams must be packed * in the initial pages. *) val headerout_packetout : ?encoder:string -> t -> (string * string) list -> Ogg.Stream.packet * Ogg.Stream.packet * Ogg.Stream.packet (** Get the number of audio channels expected by * the encoder. *) val get_channels : t -> int (** Encode a buffer of PCM data. * The PCM data array must have at least the expected * number of channels. Otherwise, the function raises [Invalid_channels]. *) val encode_buffer_float : t -> Ogg.Stream.stream -> float array array -> int -> int -> unit (** Convert a granulepos to absolute time in seconds. The granulepos is * interpreted in the context of a given encoder, and gives * the end time of a frame's presentation as used in Ogg mux ordering. *) val time_of_granulepos : t -> Int64.t -> Nativeint.t val end_of_stream : t -> Ogg.Stream.stream -> unit end (** {2 Decoding} *) module Decoder : sig (** Internal decoder state *) type t (** Initialize decoder. Needs the first 3 packets of the ogg logical * stream. Use [check_packet] to check against the first one. *) val init : Ogg.Stream.packet -> Ogg.Stream.packet -> Ogg.Stream.packet -> t (** Get vorbis infos from the decoder *) val info : t -> info (** Get vorbis comments from the decoder *) val comments : t -> string * (string * string) list (** Check wether a ogg packet contains vorbis data. * Usefull for parsing ogg containers with multiple streams. *) val check_packet : Ogg.Stream.packet -> bool (** [decode_pcm dec stream buffer pos offset] decodes pcm float data * from [stream]. The floats are written in [buffer], starting at * position [pos]. The function returns the number of samples actually written.*) val decode_pcm : t -> Ogg.Stream.stream -> float array array -> int -> int -> int (** Restart the decoder *) val restart : t -> unit end (** {1 Operations with vorbis files} *) (** {2 Decoding} *) module File : sig module Decoder : sig (** Internal state of a decoder. *) type t (** [create read_func seek_func tell_func params] opens a * stream like [openfile] for decoding but callbacks are used to * manipulate the data. [read_func] should return the requested amount of bytes * (or less if it is the end of file), [seek_funk] should return 0 if the seek * was ok or -1 if the stream is not seekable, [tell_func] should return the current * offset or -1 if there is no notion of offset in the stream. * Raises: [Read_error], [Not_vorbis], [Version_mismatch], [Bad_header], [Internal_fault]. *) val create : (int -> string * int) -> (int -> Unix.seek_command -> int) -> (unit -> int) -> t (** Open a vorbis file for decoding. *) val openfile : string -> t * Unix.file_descr val openfile_with_fd : Unix.file_descr -> t (** [decode_float dec buff ofs len] decodes [len] samples in each channel and puts * the result in [buff] starting at position [ofs]. * @raise Hole_in_data if there was an interruption of the data. * @raise Invalid_parameters if all the data cannot fit in the buffer starting at the given position. *) val decode_float : t -> float array array -> int -> int -> int val decode_float_alloc : t -> int -> float array array (** Same as [decode_float] but decodes to integers. *) val decode : t -> ?big_endian:bool -> ?sample_size:int -> ?signed:bool -> bytes -> int -> int -> int (** Get the number of logical bitstreams within a physical bitstream. *) val streams : t -> int (** Get the index of the sequential logical bitstream currently being decoded * (incremented at chaining boundaries even for non-seekable streams). For * seekable streams, it represents the actual chaining index within the * physical bitstream. *) val bitstream : t -> bitstream (** Get the vorbis comments from a vorbis file. The second argument is the * number of the logical bitstream (the current bitstream is used if it is set * to [None]). *) val comments : t -> bitstream -> string * (string * string) list (** Get the vorbis information from the stream header of a bitstream. *) val info : t -> bitstream -> info (** Get the bitrate of a bitsream (in bps). *) val bitrate : t -> bitstream -> int (** Get the total pcm samples of a bitstream. *) val samples : t -> bitstream -> int (** Get the duration in seconds of a bitstream. *) val duration : t -> bitstream -> float (** Get the serial number of a bitstream. *) val serialnumber : t -> bitstream -> int end end module Skeleton : sig (** Generate a vorbis fisbone packet with * these parameters, to use in an ogg skeleton. * Default value for [start_granule] is [Int64.zero], * Default value for [headers] is ["Content-type","audio/vorbis"] * * See: http://xiph.org/ogg/doc/skeleton.html. *) val fisbone : ?start_granule:Int64.t -> ?headers:(string * string) list -> serialno:Nativeint.t -> samplerate:Int64.t -> unit -> Ogg.Stream.packet end ocaml-vorbis-0.8.0/src/vorbis_decoder.ml000066400000000000000000000061111402143075200202230ustar00rootroot00000000000000(* * Copyright 2003-2011 Savonet team * * This file is part of Ocaml-vorbis. * * Ocaml-vorbis 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-vorbis 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-vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) let check = Vorbis.Decoder.check_packet let buflen = 1024 let decoder os = let decoder = ref None in let packet1 = ref None in let packet2 = ref None in let packet3 = ref None in let os = ref os in let init () = match !decoder with | None -> let packet1 = match !packet1 with | None -> let p = Ogg.Stream.get_packet !os in packet1 := Some p; p | Some p -> p in let packet2 = match !packet2 with | None -> let p = Ogg.Stream.get_packet !os in packet2 := Some p; p | Some p -> p in let packet3 = match !packet3 with | None -> let p = Ogg.Stream.get_packet !os in packet3 := Some p; p | Some p -> p in let d = Vorbis.Decoder.init packet1 packet2 packet3 in let info = Vorbis.Decoder.info d in (* This buffer is created once. The call to Array.sub * below makes a fresh array out of it to pass to * liquidsoap. *) let chan _ = Array.make buflen 0. in let buf = Array.init info.Vorbis.audio_channels chan in let meta = Vorbis.Decoder.comments d in decoder := Some (d, info, buf, meta); (d, info, buf, meta) | Some d -> d in let info () = let _, info, _, meta = init () in ( { Ogg_decoder.channels = info.Vorbis.audio_channels; sample_rate = info.Vorbis.audio_samplerate; }, meta ) in let restart new_os = os := new_os; let d, _, _, _ = init () in Vorbis.Decoder.restart d in let decode feed = let decoder, _, buf, _ = init () in try let ret = Vorbis.Decoder.decode_pcm decoder !os buf 0 buflen in feed (Array.map (fun x -> Array.sub x 0 ret) buf) with (* Apparently, we should hide this one.. *) | Vorbis.False -> raise Ogg.Not_enough_data in Ogg_decoder.Audio { Ogg_decoder.name = "vorbis"; info; decode; restart; samples_of_granulepos = (fun x -> x); } let register () = Hashtbl.add Ogg_decoder.ogg_decoders "vorbis" (check, decoder) ocaml-vorbis-0.8.0/src/vorbis_decoder.mli000066400000000000000000000016601402143075200204000ustar00rootroot00000000000000(* * Copyright 2003-2011 Savonet team * * This file is part of Ocaml-vorbis. * * Ocaml-vorbis 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-vorbis 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-vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** This module provides a vorbis decoder for * the [Ogg_demuxer] module. *) (** Register the vorbis decoder *) val register : unit -> unit ocaml-vorbis-0.8.0/src/vorbis_stubs.c000066400000000000000000000610601402143075200175740ustar00rootroot00000000000000/* * Copyright 2007 Samuel Mimram * * This file is part of ocaml-vorbis. * * ocaml-vorbis 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-vorbis 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-vorbis; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Libvorbis bindings for OCaml. * * @author Samuel Mimram */ #define CAML_NAME_SPACE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef Bytes_val #define Bytes_val String_val #endif static void raise_err(int ret) { switch(ret) { case OV_FALSE: caml_raise_constant(*caml_named_value("vorbis_exn_false")); case OV_HOLE: caml_raise_constant(*caml_named_value("vorbis_exn_hole_in_data")); case OV_EREAD: caml_raise_constant(*caml_named_value("vorbis_exn_read_error")); case OV_EFAULT: caml_raise_constant(*caml_named_value("vorbis_exn_internal_fault")); case OV_ENOTVORBIS: caml_raise_constant(*caml_named_value("vorbis_exn_not_vorbis")); case OV_EBADHEADER: caml_raise_constant(*caml_named_value("vorbis_exn_bad_header")); case OV_EVERSION: caml_raise_constant(*caml_named_value("vorbis_exn_version_mismatch")); case OV_EBADLINK: caml_raise_constant(*caml_named_value("vorbis_exn_bad_link")); case OV_EINVAL: caml_raise_constant(*caml_named_value("vorbis_exn_invalid")); case OV_EIMPL: caml_raise_constant(*caml_named_value("vorbis_exn_not_implemented")); case OV_ENOTAUDIO: caml_raise_constant(*caml_named_value("vorbis_exn_not_audio")); default: caml_raise_with_arg(*caml_named_value("vorbis_exn_unknown_error"), Val_int(ret)); } } /**** Decoding *****/ typedef struct { vorbis_dsp_state vd; vorbis_block vb; vorbis_info vi; vorbis_comment vc; } decoder_t; #define Decoder_val(v) (*((decoder_t**)Data_custom_val(v))) #define Decoder_dsp_state_val(v) (&Decoder_val(v)->vd) #define Decoder_info_val(v) (&Decoder_val(v)->vi) #define Comment_val(v) (&Decoder_val(v)->vc) #define Block_val(v) (&Decoder_val(v)->vb) static void finalize_decoder(value e) { decoder_t *dec = Decoder_val(e); vorbis_block_clear(&dec->vb); vorbis_dsp_clear(&dec->vd); vorbis_info_clear(&dec->vi); vorbis_comment_clear(&dec->vc); free(dec); } static struct custom_operations decoder_ops = { "ocaml_decoder_t", finalize_decoder, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default }; CAMLprim value ocaml_vorbis_val_info_of_decoder(value vorbis_t) { CAMLparam1(vorbis_t); CAMLlocal1 (v); int i = 0; v = caml_alloc_tuple(7); vorbis_info *vi = Decoder_info_val(vorbis_t); Store_field (v, i++, Val_int(vi->version)); Store_field (v, i++, Val_int(vi->channels)); Store_field (v, i++, Val_long(vi->rate)); Store_field (v, i++, Val_long(vi->bitrate_upper)); Store_field (v, i++, Val_long(vi->bitrate_nominal)); Store_field (v, i++, Val_long(vi->bitrate_lower)); Store_field (v, i++, Val_long(vi->bitrate_window)); CAMLreturn(v); } CAMLprim value ocaml_vorbis_val_comments_of_decoder(value decoder) { CAMLparam1(decoder); CAMLlocal2(ans, cmts); int i; vorbis_comment *vc = Comment_val(decoder); cmts = caml_alloc_tuple(vc->comments); for (i = 0; i < vc->comments; i++) Store_field(cmts, i, caml_copy_string(vc->user_comments[i])); ans = caml_alloc_tuple(2); if (vc->vendor != NULL) Store_field(ans, 0, caml_copy_string(vc->vendor)); else Store_field(ans, 0, caml_copy_string("(null)")); Store_field(ans, 1, cmts); CAMLreturn(ans); } CAMLprim value ocaml_vorbis_check_packet(value packet) { CAMLparam1(packet); ogg_packet *op = Packet_val(packet); vorbis_info vi; vorbis_comment vc; vorbis_info_init(&vi); vorbis_comment_init(&vc); int ret = 1; if(vorbis_synthesis_headerin(&vi, &vc, op) < 0) ret = 0; vorbis_info_clear(&vi); vorbis_comment_clear(&vc); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_vorbis_synthesis_init(value packet, value packet2, value packet3) { CAMLparam3(packet,packet2,packet3); CAMLlocal1(ans); ogg_packet *op = Packet_val(packet); ogg_packet *op2 = Packet_val(packet2); ogg_packet *op3 = Packet_val(packet3); int ret; decoder_t *vt = malloc(sizeof(decoder_t)); if (vt == NULL) caml_raise_out_of_memory(); vorbis_info_init(&vt->vi); vorbis_comment_init(&vt->vc); ret = vorbis_synthesis_headerin(&vt->vi, &vt->vc, op); if(ret < 0) { vorbis_info_clear(&vt->vi); vorbis_comment_clear(&vt->vc); free(vt); raise_err(ret); } ret = vorbis_synthesis_headerin(&vt->vi, &vt->vc, op2); if(ret < 0) { vorbis_info_clear(&vt->vi); vorbis_comment_clear(&vt->vc); free(vt); raise_err(ret); } ret = vorbis_synthesis_headerin(&vt->vi, &vt->vc, op3); if (ret < 0) { vorbis_info_clear(&vt->vi); vorbis_comment_clear(&vt->vc); free(vt); raise_err(ret); } vorbis_synthesis_init(&vt->vd, &vt->vi); vorbis_block_init(&vt->vd,&vt->vb); ans = caml_alloc_custom(&decoder_ops, sizeof(decoder_t*), 1, 0); Decoder_val(ans) = vt; CAMLreturn(ans); } CAMLprim value ocaml_vorbis_decode_pcm(value vorbis_state, value stream_state, value buf, value _pos, value _len) { CAMLparam3(vorbis_state,stream_state,buf); CAMLlocal2(buffer,chan); ogg_stream_state *os = Stream_state_val(stream_state); ogg_packet op; vorbis_block *vb = Block_val(vorbis_state); vorbis_dsp_state *vd = Decoder_dsp_state_val(vorbis_state); vorbis_info *vi = Decoder_info_val(vorbis_state); int pos = Int_val(_pos); int len = Int_val(_len); float **pcm; int samples; int i,j,ret; int total_samples = 0; while (1) { while (total_samples < len) { samples = vorbis_synthesis_pcmout(vd,&pcm); if (samples < 0) raise_err(samples); if (samples == 0) break; if (samples > len - total_samples) samples = len - total_samples; if (Wosize_val(buf) != vi->channels) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_channels")); for (i=0 ; ichannels ; i++) { chan = Field(buf,i); if (Wosize_val(chan) / Double_wosize - pos < samples) caml_raise_constant(*caml_named_value("vorbis_exn_invalid")); for (j=0; j 0 and raise * Ogg_not_enough_data otherwise * -1: out of sync */ if (ret == 0) { if (total_samples > 0) CAMLreturn(Val_int(total_samples)); else caml_raise_constant(*caml_named_value("ogg_exn_not_enough_data")); } if (ret == -1) caml_raise_constant(*caml_named_value("ogg_exn_out_of_sync")); caml_enter_blocking_section(); ret = vorbis_synthesis(vb,&op); caml_leave_blocking_section(); if (ret == 0) ret = vorbis_synthesis_blockin(vd,vb); if (ret < 0) raise_err(ret); } CAMLreturn(Val_int(total_samples)); } CAMLprim value ocaml_vorbis_synthesis_restart(value s) { CAMLparam1(s); vorbis_synthesis_restart(Decoder_dsp_state_val(s)); CAMLreturn(Val_unit); } /***** Encoding *****/ typedef struct { vorbis_dsp_state vd; vorbis_block vb; vorbis_info vi; ogg_packet op; } encoder_t; #define Encoder_val(v) (*((encoder_t**)Data_custom_val(v))) #define Enc_dsp_state_val(v) (&Encoder_val(v)->vd) static void finalize_encoder(value e) { encoder_t *enc = Encoder_val(e); vorbis_block_clear(&enc->vb); vorbis_dsp_clear(&enc->vd); vorbis_info_clear(&enc->vi); free(enc); } static struct custom_operations encoder_ops = { "ocaml_vorbis_encoder", finalize_encoder, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default }; CAMLprim value ocaml_vorbis_analysis_init(value channels, value rate, value max_bitrate, value nominal_bitrate, value min_bitrate) { encoder_t *enc = malloc(sizeof(encoder_t)); value ans; int err; vorbis_info_init(&enc->vi); err = vorbis_encode_init(&enc->vi, Int_val(channels), Int_val(rate), Int_val(max_bitrate), Int_val(nominal_bitrate), Int_val(min_bitrate)); if (err) { vorbis_info_clear(&enc->vi); raise_err(err); } vorbis_analysis_init(&enc->vd, &enc->vi); vorbis_block_init(&enc->vd, &enc->vb); ans = caml_alloc_custom(&encoder_ops, sizeof(encoder_t*), 1, 0); Encoder_val(ans) = enc; return ans; } CAMLprim value ocaml_vorbis_analysis_init_vbr(value channels, value rate, value quality) { encoder_t *enc = malloc(sizeof(encoder_t)); value ans; int err; vorbis_info_init(&enc->vi); err = vorbis_encode_init_vbr(&enc->vi, Int_val(channels), Int_val(rate), Double_val(quality)); if (err) { vorbis_info_clear(&enc->vi); raise_err(err); } vorbis_analysis_init(&enc->vd, &enc->vi); vorbis_block_init(&enc->vd, &enc->vb); ans = caml_alloc_custom(&encoder_ops, sizeof(encoder_t*), 1, 0); Encoder_val(ans) = enc; return ans; } CAMLprim value ocaml_vorbis_reset(value vdsp) { encoder_t *enc = Encoder_val(vdsp); vorbis_block_clear(&enc->vb); vorbis_dsp_clear(&enc->vd); vorbis_info_clear(&enc->vi); vorbis_analysis_init(&enc->vd, &enc->vi); vorbis_block_init(&enc->vd, &enc->vb); return Val_unit; } CAMLprim value ocaml_vorbis_analysis_headerout(value vdsp, value comments) { CAMLparam2(vdsp, comments); CAMLlocal4(ret,p1,p2,p3); vorbis_dsp_state *vd = Enc_dsp_state_val(vdsp); vorbis_comment vc; ogg_packet header, header_comm, header_code; int i; vorbis_comment_init(&vc); for(i = 0; i < Wosize_val(comments); i++) vorbis_comment_add_tag(&vc, String_val(Field(Field(comments, i), 0)), String_val(Field(Field(comments, i), 1))); vorbis_analysis_headerout(vd, &vc, &header, &header_comm, &header_code); vorbis_comment_clear(&vc); ret = caml_alloc_tuple(3); Store_field(ret,0,value_of_packet(&header)); Store_field(ret,1,value_of_packet(&header_comm)); Store_field(ret,2,value_of_packet(&header_code)); CAMLreturn(ret); } CAMLprim value ocaml_vorbis_encode_get_channels(value vdsp) { CAMLparam1(vdsp); encoder_t *enc = Encoder_val(vdsp); CAMLreturn(Val_int(enc->vi.channels)); } CAMLprim value ocaml_vorbis_encode_float(value vdsp, value vogg, value data, value _offs, value _len) { CAMLparam3(vdsp, vogg, data); encoder_t *enc = Encoder_val(vdsp); vorbis_block *vb = &enc->vb; vorbis_dsp_state *vd = Enc_dsp_state_val(vdsp); ogg_stream_state *os = Stream_state_val(vogg); ogg_packet *op = &enc->op; int offs = Int_val(_offs); int len = Int_val(_len); float **vorbis_buffer; int c, i; value datac; int channels = enc->vi.channels; if (Wosize_val(data) != channels) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_channels")); vorbis_buffer = vorbis_analysis_buffer(vd, len); for(c = 0; c < channels; c++) { datac = Field(data, c); for(i = 0; i < len; i++) vorbis_buffer[c][i] = Double_field(datac, i + offs); } caml_enter_blocking_section(); vorbis_analysis_wrote(vd, len); /* TODO: split the encoding part? */ while(vorbis_analysis_blockout(vd, vb) == 1) { /* Analysis, assume we want to use bitrate management. */ vorbis_analysis(vb, NULL); vorbis_bitrate_addblock(vb); /* Weld packets into the bitstream. */ while(vorbis_bitrate_flushpacket(vd, op)) ogg_stream_packetin(os, op); } caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_vorbis_encode_time_of_granulepos(value v_state, value gpos) { CAMLparam2(v_state,gpos); encoder_t *enc = Encoder_val(v_state); ogg_int64_t granulepos = Int64_val(gpos); CAMLreturn(caml_copy_nativeint(vorbis_granule_time(&enc->vd,granulepos))); } /***** File Decoding *****/ /* This should be malloced since we might want to register *_func as global root. */ typedef struct { OggVorbis_File *ovf; int bitstream; value read_func; value seek_func; value tell_func; } myvorbis_dec_file_t; #define Decfile_val(v) (*((myvorbis_dec_file_t**)Data_custom_val(v))) static void finalize_dec_file(value _df) { myvorbis_dec_file_t *df = Decfile_val(_df); ov_clear(df->ovf); free(df->ovf); df->ovf=NULL; caml_remove_global_root(&df->read_func); caml_remove_global_root(&df->seek_func); caml_remove_global_root(&df->tell_func); free(df); } static struct custom_operations decfile_ops = { "ocaml_vorbis_decfile", finalize_dec_file, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default }; static size_t read_func_cb(void *ptr, size_t size, size_t nmemb, void *datasource) { myvorbis_dec_file_t *df = datasource; value ret; int len; caml_leave_blocking_section(); ret = caml_callback(df->read_func, Val_int(size*nmemb)); len = Int_val(Field(ret,1)); memcpy(ptr, String_val(Field(ret,0)), len); caml_enter_blocking_section(); return len; } static int seek_func_cb(void *datasource, ogg_int64_t offset, int whence) { myvorbis_dec_file_t *df = datasource; int cmd; int ret; switch(whence) { case SEEK_SET: cmd = 0; break; case SEEK_CUR: cmd = 1; break; case SEEK_END: cmd = 2; break; default: assert(0); } caml_leave_blocking_section(); ret = Int_val(caml_callback2(df->seek_func, Val_int(offset), Val_int(cmd))); caml_enter_blocking_section(); return ret; } static long tell_func_cb(void *datasource) { myvorbis_dec_file_t *df = datasource; int ret; caml_leave_blocking_section(); ret = Int_val(caml_callback(df->tell_func, Val_unit)); caml_enter_blocking_section(); return ret; } static ov_callbacks callbacks = { .read_func = read_func_cb, .seek_func = seek_func_cb, .close_func = NULL, .tell_func = tell_func_cb }; CAMLprim value ocaml_vorbis_open_dec_stream(value read_func, value seek_func, value tell_func, value params) { CAMLparam4(read_func, seek_func, tell_func, params); CAMLlocal1(block); int ret = 0; myvorbis_dec_file_t *df; df = malloc(sizeof(myvorbis_dec_file_t)); df->ovf = (OggVorbis_File*)malloc(sizeof(OggVorbis_File)); df->bitstream = 0; caml_register_global_root(&df->read_func); df->read_func = read_func; caml_register_global_root(&df->seek_func); df->seek_func = seek_func; caml_register_global_root(&df->tell_func); df->tell_func = tell_func; caml_enter_blocking_section(); ret = ov_open_callbacks(df, df->ovf, NULL, 0, callbacks); caml_leave_blocking_section(); if(ret < 0) { caml_remove_global_root(&df->tell_func); caml_remove_global_root(&df->seek_func); caml_remove_global_root(&df->read_func); free(df->ovf); free(df); raise_err(ret); } block = caml_alloc_custom(&decfile_ops, sizeof(myvorbis_dec_file_t*),0,1); Decfile_val(block) = df; CAMLreturn(block); } CAMLprim value ocaml_vorbis_decode(value d_f, value be_, value ss_, value signed_, value buf_, value ofs_, value len_) { CAMLparam2(d_f, buf_); myvorbis_dec_file_t *df = Decfile_val(d_f); int ret = 0; int ofs = Int_val(ofs_); int len = Int_val(len_); int big_endian = Bool_val(be_); int sample_size = Int_val(ss_); int sign = Bool_val(signed_); char* buf; if (!df->ovf) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_parameters")); if (ofs + len > caml_string_length(buf_)) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_parameters")); /* TODO: this buffer could be allocated once when creating the decoder * and reused for every decoding pass. This might be useful to reduce * load or memory fragmentation if needed. */ buf = malloc(len); /* We have to make sure that when a callback is called, the ocaml master lock * has been released. Callbacks are responsible for taking it back if they * need to call ocaml code. */ caml_enter_blocking_section(); ret = ov_read(df->ovf, buf, len, big_endian, sample_size, sign, &df->bitstream); caml_leave_blocking_section(); if (ret <= 0) { free(buf); ret?raise_err(ret):caml_raise_end_of_file(); } memcpy(Bytes_val(buf_) + ofs, buf, ret); free(buf); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_vorbis_decode_byte(value *argv, int argn) { return ocaml_vorbis_decode(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]); } CAMLprim value ocaml_vorbis_decode_float(value d_f, value dst, value ofs_, value len_) { CAMLparam2(d_f, dst); myvorbis_dec_file_t *df = Decfile_val(d_f); int ret = 0; int ofs = Int_val(ofs_); int len = Int_val(len_); float **buf; int chans,c,i; if (!df->ovf) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_parameters")); chans = df->ovf->vi->channels; if (chans > Wosize_val(dst)) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_parameters")); if (Wosize_val(dst) < 1 || Wosize_val(Field(dst,0)) / Double_wosize - ofs < len) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_parameters")); /* We have to make sure that when a callback is called, the ocaml master lock * has been released. Callbacks are responsible for taking it back if they * need to call ocaml code. */ caml_enter_blocking_section(); ret = ov_read_float(df->ovf, &buf, len, &df->bitstream); caml_leave_blocking_section(); if (ret <= 0) ret?raise_err(ret):caml_raise_end_of_file(); for (c = 0; c < chans; c++) for (i = 0; i < ret; i++) Store_double_field(Field(dst, c), i + ofs, buf[c][i]); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_vorbis_decode_float_alloc(value d_f, value len_) { CAMLparam1(d_f); CAMLlocal2(ans, ansc); myvorbis_dec_file_t *df = Decfile_val(d_f); int ret = 0; int len = Int_val(len_); float **buf; int chans, c, i; if (!df->ovf) caml_raise_constant(*caml_named_value("vorbis_exn_invalid_parameters")); chans = df->ovf->vi->channels; /* We have to make sure that when a callback is called, the ocaml master lock * has been released. Callbacks are responsible for taking it back if they * need to call ocaml code. */ caml_enter_blocking_section(); ret = ov_read_float(df->ovf, &buf, len, &df->bitstream); caml_leave_blocking_section(); if (ret <= 0) ret?raise_err(ret):caml_raise_end_of_file(); ans = caml_alloc_tuple(chans); for (c = 0; c < chans; c++) { ansc = caml_alloc(ret * Double_wosize, Double_array_tag); Store_field(ans, c, ansc); for (i = 0; i < ret; i++) Store_double_field(ansc, i, buf[c][i]); } CAMLreturn(ans); } CAMLprim value ocaml_vorbis_get_dec_file_bitstream(value d_f) { myvorbis_dec_file_t *df = Decfile_val(d_f); return Val_int(df->bitstream); } CAMLprim value ocaml_vorbis_decoder_info(value d_f, value bs) { CAMLparam1(d_f); CAMLlocal1(ans); myvorbis_dec_file_t *df = Decfile_val(d_f); int bitstream = Int_val(bs); vorbis_info *vi; caml_enter_blocking_section(); vi = ov_info(df->ovf, bitstream); caml_leave_blocking_section(); assert(vi); ans = caml_alloc_tuple(7); Store_field(ans, 0, Val_int(vi->version)); Store_field(ans, 1, Val_int(vi->channels)); Store_field(ans, 2, Val_int(vi->rate)); Store_field(ans, 3, Val_int(vi->bitrate_upper)); Store_field(ans, 4, Val_int(vi->bitrate_nominal)); Store_field(ans, 5, Val_int(vi->bitrate_lower)); Store_field(ans, 6, Val_int(vi->bitrate_window)); CAMLreturn(ans); } CAMLprim value ocaml_vorbis_get_dec_file_comments(value d_f, value link_) { CAMLparam2(d_f, link_); CAMLlocal2(ans, cmts); myvorbis_dec_file_t *df = Decfile_val(d_f); int link = Int_val(link_); int i; vorbis_comment *vc; caml_enter_blocking_section(); vc = ov_comment(df->ovf, link); caml_leave_blocking_section(); if (!vc) /* TODO: better error */ caml_raise_with_arg(*caml_named_value("vorbis_exn_unknown_error"), Val_int(666)); cmts = caml_alloc_tuple(vc->comments); for (i = 0; i < vc->comments; i++) Store_field(cmts, i, caml_copy_string(vc->user_comments[i])); ans = caml_alloc_tuple(2); if (vc->vendor != NULL) Store_field(ans, 0, caml_copy_string(vc->vendor)); else Store_field(ans, 0, caml_copy_string("(null)")); Store_field(ans, 1, cmts); CAMLreturn(ans); } CAMLprim value ocaml_vorbis_decoder_bitrate(value d_f, value bs) { CAMLparam1(d_f); myvorbis_dec_file_t *df = Decfile_val(d_f); int bitstream = Int_val(bs); long ret; caml_enter_blocking_section(); ret = ov_bitrate(df->ovf, bitstream); caml_leave_blocking_section(); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_vorbis_decoder_time_total(value d_f, value bs) { CAMLparam1(d_f); myvorbis_dec_file_t *df = Decfile_val(d_f); int bitstream = Int_val(bs); double ret; caml_enter_blocking_section(); ret = ov_time_total(df->ovf, bitstream); caml_leave_blocking_section(); CAMLreturn(caml_copy_double(ret)); } CAMLprim value ocaml_vorbis_decoder_pcm_total(value d_f, value bs) { CAMLparam1(d_f); myvorbis_dec_file_t *df = Decfile_val(d_f); int bitstream = Int_val(bs); ogg_int64_t ret; caml_enter_blocking_section(); ret = ov_pcm_total(df->ovf, bitstream); caml_leave_blocking_section(); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_vorbis_decoder_streams(value d_f) { CAMLparam1(d_f); myvorbis_dec_file_t *df = Decfile_val(d_f); long ret; caml_enter_blocking_section(); ret = ov_streams(df->ovf); caml_leave_blocking_section(); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_vorbis_decoder_serialnumber(value d_f, value bs) { CAMLparam1(d_f); myvorbis_dec_file_t *df = Decfile_val(d_f); int bitstream = Int_val(bs); long ret; caml_enter_blocking_section(); ret = ov_serialnumber(df->ovf, bitstream); caml_leave_blocking_section(); CAMLreturn(Val_int(ret)); } /* Ogg skeleton interface */ /* Wrappers */ static void write32le(unsigned char *ptr,ogg_uint32_t v) { ptr[0]=v&0xff; ptr[1]=(v>>8)&0xff; ptr[2]=(v>>16)&0xff; ptr[3]=(v>>24)&0xff; } static void write64le(unsigned char *ptr,ogg_int64_t v) { ogg_uint32_t hi=v>>32; ptr[0]=v&0xff; ptr[1]=(v>>8)&0xff; ptr[2]=(v>>16)&0xff; ptr[3]=(v>>24)&0xff; ptr[4]=hi&0xff; ptr[5]=(hi>>8)&0xff; ptr[6]=(hi>>16)&0xff; ptr[7]=(hi>>24)&0xff; } /* Values from http://xiph.org/ogg/doc/skeleton.html */ #define FISBONE_IDENTIFIER "fisbone\0" #define FISBONE_MESSAGE_HEADER_OFFSET 44 #define FISBONE_SIZE 52 /* Code from theorautils.c in ffmpeg2theora */ CAMLprim value ocaml_vorbis_skeleton_fisbone(value serial, value samplerate, value start, value content) { CAMLparam4(serial,samplerate,start,content); CAMLlocal1(packet); ogg_packet op; int len = FISBONE_SIZE+caml_string_length(content); memset (&op, 0, sizeof (op)); op.packet = malloc(len); if (op.packet == NULL) caml_raise_out_of_memory(); memset (op.packet, 0, len); /* it will be the fisbone packet for the vorbis audio */ memcpy (op.packet, FISBONE_IDENTIFIER, 8); /* identifier */ write32le(op.packet+8, FISBONE_MESSAGE_HEADER_OFFSET); /* offset of the message header fields */ write32le(op.packet+12, Nativeint_val(serial)); /* serialno of the vorbis stream */ write32le(op.packet+16, 3); /* number of header packet */ /* granulerate, temporal resolution of the bitstream in Hz */ write64le(op.packet+20, (ogg_int64_t)Int64_val(samplerate)); /* granulerate numerator */ write64le(op.packet+28, (ogg_int64_t)1); /* granulerate denominator */ write64le(op.packet+36, (ogg_int64_t)Int64_val(start)); /* start granule */ write32le(op.packet+44, 2); /* preroll, for vorbis its 2 */ *(op.packet+48) = 0; /* granule shift, always 0 for vorbis */ memcpy (op.packet+FISBONE_SIZE, String_val(content), caml_string_length(content)); op.b_o_s = 0; op.e_o_s = 0; op.bytes = len; packet = value_of_packet(&op); free(op.packet); CAMLreturn(packet); } ocaml-vorbis-0.8.0/vorbis.opam000066400000000000000000000013541402143075200162770ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.8.0" synopsis: "Bindings to libvorbis" maintainer: ["The Savonet Team "] authors: ["The Savonet Team "] license: "GPL-2.0" homepage: "https://github.com/savonet/ocaml-vorbis" bug-reports: "https://github.com/savonet/ocaml-vorbis/issues" depends: [ "conf-libvorbis" "conf-pkg-config" "dune" {>= "2.0"} "dune-configurator" "ogg" {>= "0.7.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-vorbis.git"