pax_global_header00006660000000000000000000000064141653361720014522gustar00rootroot0000000000000052 comment=5afcef0df4b8751a9c19a0608dd8e780a5e3ddff ocaml-speex-0.4.1/000077500000000000000000000000001416533617200137415ustar00rootroot00000000000000ocaml-speex-0.4.1/.github/000077500000000000000000000000001416533617200153015ustar00rootroot00000000000000ocaml-speex-0.4.1/.github/workflows/000077500000000000000000000000001416533617200173365ustar00rootroot00000000000000ocaml-speex-0.4.1/.github/workflows/main.yml000066400000000000000000000006611416533617200210100ustar00rootroot00000000000000name: 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 speex - run: opam install -t . ocaml-speex-0.4.1/.gitignore000066400000000000000000000000631416533617200157300ustar00rootroot00000000000000*~ _build *.byte *.native _tests .merlin *.install ocaml-speex-0.4.1/.gitmodules000066400000000000000000000001031416533617200161100ustar00rootroot00000000000000[submodule "m4"] path = m4 url = git://github.com/savonet/m4.git ocaml-speex-0.4.1/.merlin000066400000000000000000000000311416533617200152220ustar00rootroot00000000000000B src/** S src/** PKG oggocaml-speex-0.4.1/.ocamlformat000066400000000000000000000003201416533617200162410ustar00rootroot00000000000000profile = 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-speex-0.4.1/CHANGES000066400000000000000000000020441416533617200147340ustar00rootroot000000000000000.4.1 (04-01-2022) ===== * Get rid of naked pointers. 0.4.0 (08-03-2021) ===== * Switch to dune 0.3.0 (16-10-2020) ===== * Switch to Unix.read style API. 0.2.2 (16-10-2020) ===== * Fix Speex header notification spam. 0.2.1 (03-08-2015) ===== * Changed types to match new ocaml-ogg's API. Should be fully backward compatible. * Wrapped more speex functions around enter/leave blocking sections to avoid deadlock when speex writes to stderr 0.2.0 (04-07-2011) ===== * Added decoding module for the new Ogg_demuxer module * Implement new Out_of_sync exception * Efficient seeking support 0.1.2 (14-10-2009) ===== * Added support for --enable-debugging configure option * Makefile now honnors LIBDIRS variable for linking against libraries located in other places than then standard ones. * Added prefix to main compilation variables if passed to configure. * Added NO_CUSTOM to build in standard mode. 0.1.1 (30-03-2009) ===== * Fixed Makefile for BSD: call $(MAKE) for generating documentation. 0.1.0 (17-02-2009) ===== * Initial release ocaml-speex-0.4.1/COPYING000066400000000000000000000431311416533617200147760ustar00rootroot00000000000000 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-speex-0.4.1/README.md000066400000000000000000000010711416533617200152170ustar00rootroot00000000000000ocaml-speex =========== This package contains an OCaml interface for the `speex` library Please read the COPYING file before using this software. Prerequisites: ============== - ocaml - libspeex - 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 speex ``` Via `dune` (for developers): ``` $ dune install ``` This should install the library file in the appropriate place. ocaml-speex-0.4.1/control_define000077500000000000000000000012411416533617200166570ustar00rootroot00000000000000#!/usr/bin/perl my $comment = 0; my @results; my @names; while () { my $new_comment = $comment; s/^\s+//; s/\/\*.*\*\///; s/\/\/.*//; if (m/\/\*/) { $new_comment++; } if (m/\*\//) { $new_comment--; } s/SPEEX_(GET|SET)_PF//; if (!$comment && !$new_comment) { if (/^#define\s+(SPEEX_(?:GET|SET).+)\s+(.+)/) { my $pair = "$1:$2"; push(@results,$pair); push(@names,$1); } } $comment = $new_comment; } my $types = join(" |\n ", @names); print "type control = \n $types\n"; print < $value\n"; } ocaml-speex-0.4.1/dune-project000066400000000000000000000007521416533617200162670ustar00rootroot00000000000000(lang dune 2.8) (version 0.4.1) (name speex) (source (github savonet/ocaml-speex)) (license GPL-2.0) (authors "The Savonet Team ") (maintainers "The Savonet Team ") (generate_opam_files true) (use_standard_c_and_cxx_flags false) (package (name speex) (synopsis "Bindings to libspeex") (depends conf-libogg conf-libspeex conf-pkg-config dune dune-configurator (ocaml (>= 4.07)) (ogg (>= 0.7.0))) ) ocaml-speex-0.4.1/examples/000077500000000000000000000000001416533617200155575ustar00rootroot00000000000000ocaml-speex-0.4.1/examples/.merlin000066400000000000000000000000221416533617200170400ustar00rootroot00000000000000B ../src S ../src ocaml-speex-0.4.1/examples/dune000066400000000000000000000006321416533617200164360ustar00rootroot00000000000000(executable (name speex2wav) (modules speex2wav) (libraries speex speex.decoder ogg.decoder)) (executable (name wav2speex) (modules wav2speex) (libraries speex)) (rule (alias runtest) (package speex) (deps (:speex test.ogg) (:wav2speex ./wav2speex.exe) (:speex2wav ./speex2wav.exe)) (action (progn (run %{speex2wav} %{speex} decoded.wav) (run %{wav2speex} decoded.wav encoded.ogg)))) ocaml-speex-0.4.1/examples/speex2wav.ml000066400000000000000000000077531416533617200200510ustar00rootroot00000000000000(* * Copyright 2008 Savonet team * * This file is part of OCaml-speex. * * OCaml-speex 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-speex 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-speex; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * A speex to wav converter using OCaml-speex. * * @author Samuel Mimram * @author Romain Beauxis *) 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 usage = "usage: speex2wav source destination" let () = Speex_decoder.register () 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 dec, fd = Ogg_decoder.init_from_file !src in let { Ogg_decoder.audio_track; _ } = Ogg_decoder.get_standard_tracks dec in let audio_track = match audio_track with | None -> Printf.eprintf "Error: no audio track\n"; exit 1 | Some audio_track -> audio_track in let { Ogg_decoder.channels; sample_rate }, (encoder, comments) = Ogg_decoder.audio_info dec audio_track in Printf.printf "Encoder: %s\n" encoder; let print_comment (k, v) = Printf.printf "%s: %s\n" k v in Printf.printf "Comments:\n"; List.iter print_comment comments; Printf.printf "\n"; Printf.printf "Input file characteristics: %d channels, %d Hz\n" channels sample_rate; (* Using speex to decode the ogg. *) Printf.printf "\nDecoding...\n"; flush_all (); let tmpdst, oc = Filename.open_temp_file ~mode:[Open_binary] "speex2wav" ".raw" in (try while true do Ogg_decoder.decode_audio dec audio_track (fun data -> let s1 = data.(0) in Array.iteri (fun n _ -> Array.iter (fun s -> let sample = int_of_float (s.(n) *. 32767.) in output_short oc sample) data) s1) done with Ogg_decoder.End_of_stream -> close_out oc); Printf.printf "Decoding finished, writing WAV..\n"; Unix.close fd; (* Do the wav stuff. *) let datalen = (Unix.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 sample_rate; (* freq *) output_int oc (sample_rate * 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 while !r <> 0 do r := input ic buf 0 buflen; output oc buf 0 !r; pos := !pos + !r done); close_in ic; close_out oc; Unix.unlink tmpdst; Printf.printf "Done !\n"; Gc.full_major () ocaml-speex-0.4.1/examples/test.ogg000066400000000000000000000003441416533617200172350ustar00rootroot00000000000000OggSdšžë FPSpeex 1.2.0PD¬ÿÿÿÿ@@OggSdšžN+B¬@8ocaml-speex by the savonet team (http://savonet.sf.net/)OggS@dšž ,xûocaml-speex-0.4.1/examples/wav2speex.ml000066400000000000000000000147221416533617200200430ustar00rootroot00000000000000(* * Copyright 2008 Savonet team * * This file is part of ocaml-speex. * * ocaml-speex 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-speex 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-speex; 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-speex. * * @author Samuel Mimram, Romain Beauxis, and many others... *) open Speex let src = ref "" let dst = ref "" let input_string chan len = let ans = Bytes.create len in really_input chan ans 0 len; Bytes.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 usage = "usage: wav2speex [options] source destination" let float = ref false let mode = ref Wideband let fpp = ref 5 let vbr = ref false let quality = ref 7 let _ = let f = Printf.sprintf in let string_of_mode m = match m with | Narrowband -> "narrowband" | Wideband -> "wideband" | Ultra_wideband -> "ultra-wideband" in Arg.parse [ ( "--float", Arg.Unit (fun _ -> float := true), f "Use floats for decoding. Default: %b" !float ); ( "--mode", Arg.String (fun b -> match b with | "narrowband" -> mode := Narrowband | "wideband" -> mode := Wideband | "ultra-wideband" -> mode := Ultra_wideband | _ -> failwith "unkown mode"), f "Encoding mode, one of \"narrowband\", \"wideband\" or \ \"ultra-wideband\". Default: %s" (string_of_mode !mode) ); ( "--frame_per_packet", Arg.Int (fun b -> fpp := b), f "Frames per Ogg packet. Default: %i" !fpp ); ( "--vbr", Arg.Unit (fun _ -> vbr := true), f "Encode in vbr mode. Default: %b" !vbr ); ( "--quality", Arg.Int (fun b -> quality := b), f "Encoding bitrate, in Kbps. Default: %i" !quality ); ] (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 ibits = input_short ic in if input_string ic 4 <> "data" then invalid_arg "No data tag"; let _ = input_int ic in (* datalen *) 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) <- max (-32768) (min 32767 n) done done; ans in let enc = Encoder.init !mode !fpp in if not !vbr then Encoder.set enc SPEEX_SET_QUALITY !quality else Encoder.set enc SPEEX_SET_VBR_QUALITY !quality; Encoder.set enc SPEEX_SET_SAMPLING_RATE infreq; let ivbr = if !vbr then 1 else 0 in Encoder.set enc SPEEX_SET_VBR ivbr; let fsize = Encoder.get enc SPEEX_GET_FRAME_SIZE in let os = Ogg.Stream.create () in let header = Header.init ~rate:infreq ~nb_channels:channels ~mode:!mode ~vbr:!vbr ~frames_per_packet:!fpp () in Header.encode_header header [] os; let s_o_f (h, b) = h ^ b in let flush s = let rec f v = try let v = v ^ s_o_f (Ogg.Stream.flush_page s) in f v with Ogg.Not_enough_data -> v in f "" in output_string oc (flush os); let start = Unix.time () in let smode = match !mode with | Narrowband -> "narrowband" | Wideband -> "wideband" | Ultra_wideband -> "ultra-wideband" in Printf.printf "Input detected: PCM WAVE %d channels, %d Hz, %d bits\n%!" channels infreq ibits; Printf.printf "Encoding to: SPEEX %d channels, %d Hz, %s, VBR: %s\nPlease wait...\n%!" channels infreq smode (string_of_bool !vbr); begin try while true do let buflen = 2 * fsize * channels in let buf = Bytes.create buflen in let feed () = really_input ic buf 0 buflen; let buf = Bytes.to_string buf in let fbuf = fos buf in assert (Array.length fbuf.(0) = fsize); fbuf in let h, v = if channels = 1 then ( let feed () = let frame = feed () in frame.(0) in if !float then ( let feed () = Array.map float_of_int (feed ()) in Encoder.encode_page enc os feed) else Encoder.encode_page_int enc os feed) else if !float then ( let feed () = Array.map (fun x -> Array.map float_of_int x) (feed ()) in Encoder.encode_page_stereo enc os feed) else Encoder.encode_page_int_stereo enc os feed in output_string oc (h ^ v) done with End_of_file -> () end; Encoder.eos enc os; output_string oc (flush os); close_in ic; close_out oc; Printf.printf "Finished in %.0f seconds.\n" (Unix.time () -. start); Gc.full_major () ocaml-speex-0.4.1/speex.opam000066400000000000000000000014361416533617200157470ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.4.1" synopsis: "Bindings to libspeex" maintainer: ["The Savonet Team "] authors: ["The Savonet Team "] license: "GPL-2.0" homepage: "https://github.com/savonet/ocaml-speex" bug-reports: "https://github.com/savonet/ocaml-speex/issues" depends: [ "conf-libogg" "conf-libspeex" "conf-pkg-config" "dune" {>= "2.8"} "dune-configurator" "ocaml" {>= "4.07"} "ogg" {>= "0.7.0"} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/savonet/ocaml-speex.git" ocaml-speex-0.4.1/src/000077500000000000000000000000001416533617200145305ustar00rootroot00000000000000ocaml-speex-0.4.1/src/config/000077500000000000000000000000001416533617200157755ustar00rootroot00000000000000ocaml-speex-0.4.1/src/config/discover.ml000066400000000000000000000010571416533617200201500ustar00rootroot00000000000000module C = Configurator.V1 let () = C.main ~name:"speex-pkg-config" (fun c -> let default : C.Pkg_config.package_conf = { libs = ["-lspeex"; "-logg"]; cflags = [] } in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> ( match C.Pkg_config.query pc ~package:"speex ogg" 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-speex-0.4.1/src/config/dune000066400000000000000000000001611416533617200166510ustar00rootroot00000000000000(executable (name discover) (foreign_stubs (language c) (names endianess)) (libraries dune.configurator)) ocaml-speex-0.4.1/src/config/endianess.c000066400000000000000000000006161416533617200201150ustar00rootroot00000000000000#include #include enum { OCAML_MM_LITTLE_ENDIAN = 0x0100, OCAML_MM_BIG_ENDIAN = 0x0001, }; static const union { unsigned char bytes[2]; uint16_t value; } host_order = { { 0, 1 } }; CAMLprim value ocaml_mm_is_big_endian(value unit) { CAMLparam0(); if (host_order.value == OCAML_MM_BIG_ENDIAN) CAMLreturn(Val_bool(1)); CAMLreturn(Val_bool(0)); } ocaml-speex-0.4.1/src/dune000066400000000000000000000010241416533617200154030ustar00rootroot00000000000000(library (name speex) (public_name speex) (synopsis "OCaml bindings for libspeex") (libraries ogg) (modules speex) (foreign_stubs (language c) (names speex_stubs) (flags (:include c_flags.sexp))) (c_library_flags (:include c_library_flags.sexp))) (library (name speex_decoder) (public_name speex.decoder) (synopsis "Speex decoder for the ogg-decoder library") (libraries ogg.decoder speex) (modules speex_decoder)) (rule (targets c_flags.sexp c_library_flags.sexp) (action (run ./config/discover.exe))) ocaml-speex-0.4.1/src/speex.ml000066400000000000000000000322401416533617200162070ustar00rootroot00000000000000(* * Copyright 2003-2011 Savonet team * * This file is part of Ocaml-speex. * * Ocaml-speex 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-speex 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-speex; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Functions for decoding speex files using libspeex. * * @author Romain Beauxis *) exception Invalid_frame_size type mode = Narrowband | Wideband | Ultra_wideband (* Internal use only *) type internal_mode external internal_mode_of_int : int -> internal_mode = "caml_speex_get_mode" (* Values from speex.h *) let mode_of_int x = match x with | 0 -> Narrowband | 1 -> Wideband | 2 -> Ultra_wideband | _ -> failwith "unknown mode" let int_of_mode x = match x with Narrowband -> 0 | Wideband -> 1 | Ultra_wideband -> 2 let internal_mode_of_mode x = internal_mode_of_int (int_of_mode x) (* Generated by control_define *) (** TODO: better implementation.. *) type control = | SPEEX_RESET_STATE | SPEEX_SET_ENH | SPEEX_GET_ENH | SPEEX_GET_FRAME_SIZE | SPEEX_SET_QUALITY | SPEEX_SET_MODE | SPEEX_GET_MODE | SPEEX_SET_LOW_MODE | SPEEX_GET_LOW_MODE | SPEEX_SET_HIGH_MODE | SPEEX_GET_HIGH_MODE | SPEEX_SET_VBR | SPEEX_GET_VBR | SPEEX_SET_VBR_QUALITY | SPEEX_GET_VBR_QUALITY | SPEEX_SET_COMPLEXITY | SPEEX_GET_COMPLEXITY | SPEEX_SET_BITRATE | SPEEX_GET_BITRATE | SPEEX_SET_SAMPLING_RATE | SPEEX_GET_SAMPLING_RATE | SPEEX_SET_VAD | SPEEX_GET_VAD | SPEEX_SET_ABR | SPEEX_GET_ABR | SPEEX_SET_DTX | SPEEX_GET_DTX | SPEEX_SET_SUBMODE_ENCODING | SPEEX_GET_SUBMODE_ENCODING | SPEEX_SET_PLC_TUNING | SPEEX_GET_PLC_TUNING | SPEEX_SET_VBR_MAX_BITRATE | SPEEX_GET_VBR_MAX_BITRATE | SPEEX_SET_HIGHPASS | SPEEX_GET_HIGHPASS | SPEEX_GET_ACTIVITY let int_of_control x = match x with | SPEEX_SET_ENH -> 0 | SPEEX_GET_ENH -> 1 | SPEEX_GET_FRAME_SIZE -> 3 | SPEEX_SET_QUALITY -> 4 | SPEEX_SET_MODE -> 6 | SPEEX_GET_MODE -> 7 | SPEEX_SET_LOW_MODE -> 8 | SPEEX_GET_LOW_MODE -> 9 | SPEEX_SET_HIGH_MODE -> 10 | SPEEX_GET_HIGH_MODE -> 11 | SPEEX_SET_VBR -> 12 | SPEEX_GET_VBR -> 13 | SPEEX_SET_VBR_QUALITY -> 14 | SPEEX_GET_VBR_QUALITY -> 15 | SPEEX_SET_COMPLEXITY -> 16 | SPEEX_GET_COMPLEXITY -> 17 | SPEEX_SET_BITRATE -> 18 | SPEEX_GET_BITRATE -> 19 | SPEEX_SET_SAMPLING_RATE -> 24 | SPEEX_GET_SAMPLING_RATE -> 25 | SPEEX_RESET_STATE -> 26 | SPEEX_SET_VAD -> 30 | SPEEX_GET_VAD -> 31 | SPEEX_SET_ABR -> 32 | SPEEX_GET_ABR -> 33 | SPEEX_SET_DTX -> 34 | SPEEX_GET_DTX -> 35 | SPEEX_SET_SUBMODE_ENCODING -> 36 | SPEEX_GET_SUBMODE_ENCODING -> 37 | SPEEX_SET_PLC_TUNING -> 40 | SPEEX_GET_PLC_TUNING -> 41 | SPEEX_SET_VBR_MAX_BITRATE -> 42 | SPEEX_GET_VBR_MAX_BITRATE -> 43 | SPEEX_SET_HIGHPASS -> 44 | SPEEX_GET_HIGHPASS -> 45 | SPEEX_GET_ACTIVITY -> 47 let _ = Callback.register "caml_speex_mode_of_int" mode_of_int; Callback.register "caml_speex_int_of_mode" int_of_mode; Callback.register_exception "ocaml_speex_invfrlen_exn" Invalid_frame_size; Callback.register_exception "ocaml_speex_eos_exn" Ogg.End_of_stream module Header = struct type t = { id : string; version : string; version_id : int; header_size : int; rate : int; mode : mode; mode_bitstream_version : int; nb_channels : int; bitrate : int; frame_size : int; vbr : bool; frames_per_packet : int; extra_headers : int; } (* Defined in speex_header.h *) let header_string_length = 8 let header_version_length = 20 external init : int -> int -> internal_mode -> int -> bool -> t = "caml_speex_init_header" let init ?(frames_per_packet = 1) ?(mode = Wideband) ?(vbr = true) ~nb_channels ~rate () = init rate nb_channels (internal_mode_of_mode mode) frames_per_packet vbr external encode_header_packetout : t -> string array -> Ogg.Stream.packet * Ogg.Stream.packet = "caml_speex_encode_header" let encode_header_packetout e l = let l = List.map (fun (x, y) -> Printf.sprintf "%s=%s" x y) l in encode_header_packetout e (Array.of_list l) let encode_header e l s = let p1, p2 = encode_header_packetout e l in Ogg.Stream.put_packet s p1; Ogg.Stream.put_packet s p2 external header_of_packet : Ogg.Stream.packet -> t = "caml_speex_header_of_packet" external comments_of_packet : Ogg.Stream.packet -> string array = "caml_speex_comments_of_packet" let comments_of_packet p = let x = comments_of_packet p in let vendor = x.(0) in let x = Array.sub x 1 (Array.length x - 1) in let c_k = ref 0 in let c_v = ref 0 in let split s = try let i = String.index s '=' in try (String.sub s 0 i, String.sub s (i + 1) (String.length s - i - 1)) with Invalid_argument _ -> c_v := !c_v + 1; (String.sub s 0 i, Printf.sprintf "unknown_value_%i" !c_k) with Not_found -> c_k := !c_k + 1; (Printf.sprintf "unkown_key_%i" !c_k, s) in (vendor, Array.to_list (Array.map split x)) end module Encoder = struct type t external init : internal_mode -> int -> t = "ocaml_speex_enc_init" let init m x = init (internal_mode_of_mode m) x external get : t -> int -> int = "ocaml_speex_encoder_ctl_get" let get x q = get x (int_of_control q) external set : t -> int -> int -> unit = "ocaml_speex_encoder_ctl_set" let set x q v = set x (int_of_control q) v external encode_page_main : t -> int -> Ogg.Stream.stream -> (unit -> float array) -> Ogg.Page.t = "ocaml_speex_encode_page" let encode_page e s f = encode_page_main e 1 s f let merge frame = let ret = Array.init (2 * Array.length frame.(0)) (fun _ -> frame.(0).(0)) in Array.iteri (fun i _ -> ret.(2 * i) <- frame.(0).(i); ret.((2 * i) + 1) <- frame.(1).(i)) frame.(0); ret let encode_page_stereo e s f = let f () = merge (f ()) in encode_page_main e 2 s f external encode_page_int_main : t -> int -> Ogg.Stream.stream -> (unit -> int array) -> Ogg.Page.t = "ocaml_speex_encode_page_int" let encode_page_int e s f = encode_page_int_main e 1 s f let encode_page_int_stereo e s f = let f () = merge (f ()) in encode_page_int_main e 2 s f external eos : t -> Ogg.Stream.stream -> unit = "ocaml_speex_encoder_eos" end module Decoder = struct type t external init : internal_mode -> t = "ocaml_speex_dec_init" let init m = init (internal_mode_of_mode m) external get : t -> int -> int = "ocaml_speex_decoder_ctl_get" let get x q = get x (int_of_control q) external set : t -> int -> int -> unit = "ocaml_speex_decoder_ctl_set" let set x q v = set x (int_of_control q) v let split frame = let ret = Array.make 2 (Array.make (Array.length frame / 2) frame.(0)) in for i = 0 to (Array.length frame / 2) - 1 do ret.(0).(i) <- frame.(2 * i); ret.(1).(i) <- frame.((2 * i) + 1) done; ret external decode_feed : t -> int -> Ogg.Stream.stream -> (float array -> unit) -> unit = "ocaml_speex_decoder_decode" let decode_gen e s chan func split = let l = ref [] in let feed x = l := split x :: !l in begin try func e chan s feed with Ogg.Not_enough_data -> if List.length !l = 0 then raise Ogg.Not_enough_data end; List.rev !l let decode e s = decode_gen e s 1 decode_feed (fun x -> x) let decode_stereo e s = decode_gen e s 2 decode_feed split let decode_feed_stereo e s feed = let feed x = feed (split x) in decode_feed e 2 s feed let decode_feed e s feed = decode_feed e 1 s feed external decode_int_feed : t -> int -> Ogg.Stream.stream -> (int array -> unit) -> unit = "ocaml_speex_decoder_decode_int" let decode_int e s = decode_gen e s 2 decode_int_feed (fun x -> x) let decode_int_stereo e s = decode_gen e s 2 decode_int_feed split let decode_int_feed_stereo e s feed = let feed x = feed (split x) in decode_int_feed e 2 s feed let decode_int_feed e s feed = decode_int_feed e 1 s feed end module Wrapper = struct module Decoder = struct exception Not_speex exception Internal type t = (Decoder.t * Ogg.Stream.stream * Ogg.Sync.t * nativeint * int * (string * (string * string) list) * Header.t) ref type read = bytes -> int -> int -> int let open_sync sync = (* Test wether the stream contains speex data *) let test_speex () = (* 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; (* Test header. Do not catch anything, first page should be sufficient *) let packet = Ogg.Stream.get_packet os in try let header = Header.header_of_packet packet in (* Get comments *) let page = ref (Ogg.Sync.read sync) in while Ogg.Page.serialno !page <> serial do page := Ogg.Sync.read sync done; Ogg.Stream.put_page os !page; let comments = Ogg.Stream.get_packet os in let comments = Header.comments_of_packet comments in (serial, os, header, comments) with _ -> Printf.printf "Not a speex stream..\n"; raise Internal in let rec init () = try test_speex () with (* Not_found is not catched: ogg stream always start with all b_o_s and we don't care about sequenced streams here *) | Internal -> init () | Ogg.Not_enough_data -> raise Not_speex in let serial, os, header, comments = init () in let chans = header.Header.nb_channels in let rate = header.Header.rate in let mode = header.Header.mode in let dec = Decoder.init mode in Decoder.set dec SPEEX_SET_SAMPLING_RATE rate; ref (dec, os, sync, serial, chans, comments, header) let open_file file = let sync, fd = Ogg.Sync.create_from_file file in (open_sync sync, fd) let open_feed feed = let sync = Ogg.Sync.create feed in open_sync sync let serial x = let _, _, _, serial, _, _, _ = !x in serial let comments x = let _, _, _, _, _, (_, l), _ = !x in l let header x = let _, _, _, _, _, _, h = !x in h let decode_gen f x = let dec, os, sync, serial, _, _, _ = !x in let dec = ref dec in let serial = ref serial in let os = ref os in let eos = ref false in let rec put () = try if !eos then ( try (* Try to open a new stream *) let y = open_sync sync in let ndec, nos, _, nserial, _, _, _ = !y in x := !y; dec := ndec; serial := nserial; os := nos; eos := false with Not_found -> raise Internal); let page = Ogg.Sync.read sync in if Ogg.Stream.eos !os then eos := true; if Ogg.Page.serialno page = !serial then Ogg.Stream.put_page !os page with | Internal | Ogg.Not_enough_data -> raise Ogg.End_of_stream | Ogg.End_of_stream -> eos := true; put () in let rec get () = try f !dec !os with | Ogg.End_of_stream -> eos := true; put (); get () | Ogg.Not_enough_data -> put (); get () in get () let decode v = decode_gen Decoder.decode v let decode_stereo v = decode_gen Decoder.decode_stereo v let decode_feed v feed = decode_gen (fun x y -> Decoder.decode_feed x y feed) v let decode_feed_stereo v feed = decode_gen (fun x y -> Decoder.decode_feed_stereo x y feed) v let decode_int v = decode_gen Decoder.decode_int v let decode_int_stereo v = decode_gen Decoder.decode_int_stereo v let decode_int_feed v feed = decode_gen (fun x y -> Decoder.decode_int_feed x y feed) v let decode_int_feed_stereo v feed = decode_gen (fun x y -> Decoder.decode_int_feed_stereo x y feed) v end end module Skeleton = struct external fisbone : nativeint -> Header.t -> Int64.t -> string -> Ogg.Stream.packet = "ocaml_speex_skeleton_fisbone" let fisbone ?(start_granule = Int64.zero) ?(headers = [("Content-type", "audio/speex")]) ~serialno ~header () = 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 header start_granule s end ocaml-speex-0.4.1/src/speex.mli000066400000000000000000000217741416533617200163720ustar00rootroot00000000000000(* * Copyright 2003-2006 Savonet team * * This file is part of Ocaml-speex. * * Ocaml-speex 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-speex 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-speex; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Functions for manipulating speex audio data using libspeex. * * @author Romain Beauxis *) exception Invalid_frame_size type mode = Narrowband | Wideband | Ultra_wideband (* Generated by control_define *) type control = | (* Reset the encoder/decoder memories to zero *) SPEEX_RESET_STATE | (* Set/get enhancement on/off (decoder only) *) SPEEX_SET_ENH | SPEEX_GET_ENH | (* Obtain frame size used by encoder/decoder *) SPEEX_GET_FRAME_SIZE | (* Set/get quality value *) SPEEX_SET_QUALITY | (* Set/get sub-mode to use *) SPEEX_SET_MODE | SPEEX_GET_MODE | (* Set/get low-band sub-mode to use (wideband only)*) SPEEX_SET_LOW_MODE | SPEEX_GET_LOW_MODE | (* Set/get high-band sub-mode to use (wideband only)*) SPEEX_SET_HIGH_MODE | SPEEX_GET_HIGH_MODE | (* Set/get VBR on (1) or off (0) *) SPEEX_SET_VBR | SPEEX_GET_VBR | (* Set/get quality value for VBR encoding (0-10) *) SPEEX_SET_VBR_QUALITY | SPEEX_GET_VBR_QUALITY | (* Set/get complexity of the encoder (0-10) *) SPEEX_SET_COMPLEXITY | SPEEX_GET_COMPLEXITY | (* Set/get bitrate *) SPEEX_SET_BITRATE | SPEEX_GET_BITRATE | (* Set/get sampling rate *) SPEEX_SET_SAMPLING_RATE | SPEEX_GET_SAMPLING_RATE | (* Set/get VAD status (1 for on, 0 for off) *) SPEEX_SET_VAD | SPEEX_GET_VAD | (* Set/get Average Bit-Rate (ABR) to n bits per seconds *) SPEEX_SET_ABR | SPEEX_GET_ABR | (* Set/get DTX status (1 for on, 0 for off) *) SPEEX_SET_DTX | SPEEX_GET_DTX | (* Set/get submode encoding in each frame (1 for yes, 0 for no, setting to no breaks the standard) *) SPEEX_SET_SUBMODE_ENCODING | SPEEX_GET_SUBMODE_ENCODING | (* Set/get tuning for packet-loss concealment (expected loss rate) *) SPEEX_SET_PLC_TUNING | SPEEX_GET_PLC_TUNING | (* Set/get the max bit-rate allowed in VBR mode *) SPEEX_SET_VBR_MAX_BITRATE | SPEEX_GET_VBR_MAX_BITRATE | (* Turn on/off input/output high-pass filtering *) SPEEX_SET_HIGHPASS | SPEEX_GET_HIGHPASS | (* Get "activity level" of the last decoded frame, i.e. how much damage we cause if we remove the frame *) SPEEX_GET_ACTIVITY module Header : sig (** Type for speex header. *) type t = { id : string; version : string; version_id : int; header_size : int; rate : int; mode : mode; mode_bitstream_version : int; nb_channels : int; bitrate : int; frame_size : int; vbr : bool; frames_per_packet : int; extra_headers : int; } (* Defined in speex_header.h *) val header_string_length : int val header_version_length : int (** Initiate a new speex header. *) val init : ?frames_per_packet:int -> ?mode:mode -> ?vbr:bool -> nb_channels:int -> rate:int -> unit -> t (** [encode_header_packetout header metadata]: output ogg packets containing the header. * First packet contains speex audio codec settings, second the metadata. *) val encode_header_packetout : t -> (string * string) list -> Ogg.Stream.packet * Ogg.Stream.packet (** Output ogg packets containing the header and put them into the given stream. *) val encode_header : t -> (string * string) list -> Ogg.Stream.stream -> unit (** Decode the speex header contained in the given packet. * * Raises [Invalid_argument] if the packet does not contain speex audio codec data. *) val header_of_packet : Ogg.Stream.packet -> t (** Decode the metadata contained in the given packet. * * Raises [Invalid_argument] if the packet does not contain speex metadata. *) val comments_of_packet : Ogg.Stream.packet -> string * (string * string) list end module Encoder : sig (** Opaque type for the speex encoder. *) type t (** Initiate a new encoder. *) val init : mode -> int -> t (** Get a parameter. *) val get : t -> control -> int (** Set a parameter. *) val set : t -> control -> int -> unit (** [encode_page encoder stream f]: calls [f] to get audio data and encode it until a page is ready. * * Known issue: float expected values seem not to be in [-1..1] but in * [-32768..32767] which does not seem to be correct. *) val encode_page : t -> Ogg.Stream.stream -> (unit -> float array) -> Ogg.Page.t (** Same as [encode_page] except that it encodes stereo data into mono. *) val encode_page_stereo : t -> Ogg.Stream.stream -> (unit -> float array array) -> Ogg.Page.t (** Same as [encode_page] but using integers. *) val encode_page_int : t -> Ogg.Stream.stream -> (unit -> int array) -> Ogg.Page.t (** Same as [encode_page_stereo] but using integers. *) val encode_page_int_stereo : t -> Ogg.Stream.stream -> (unit -> int array array) -> Ogg.Page.t (** Set the end of stream for this stream. *) val eos : t -> Ogg.Stream.stream -> unit end module Decoder : sig (** Opaque type for the speex decoder. *) type t (** Initiate a new decoder. *) val init : mode -> t (** Get a setting. *) val get : t -> control -> int (** Set a setting. *) val set : t -> control -> int -> unit (** Decode data. *) val decode : t -> Ogg.Stream.stream -> float array list (** Decode stereo data. *) val decode_stereo : t -> Ogg.Stream.stream -> float array array list (** Decode data, passing them to the given feed. *) val decode_feed : t -> Ogg.Stream.stream -> (float array -> unit) -> unit (** Decode stereo data, passing them to the given feed. *) val decode_feed_stereo : t -> Ogg.Stream.stream -> (float array array -> unit) -> unit (** Same as [decode] but with integers. *) val decode_int : t -> Ogg.Stream.stream -> int array list (** Same as [decode_stereo] but with integers. *) val decode_int_stereo : t -> Ogg.Stream.stream -> int array array list (** Same as [decode_feed] but with integers. *) val decode_int_feed : t -> Ogg.Stream.stream -> (int array -> unit) -> unit (** Same as [decode_feed_stereo] but with integers. *) val decode_int_feed_stereo : t -> Ogg.Stream.stream -> (int array array -> unit) -> unit end module Wrapper : sig (** High level wrappers for speex. *) module Decoder : sig (** High level wrapper to easily decode speex files. *) exception Not_speex (** Opaque type for the decoder. *) type t (** Type for data read. Same signature as [Unix.read]. *) type read = bytes -> int -> int -> int (** Open the passed [Ogg.Sync] as a new speex stream. *) val open_sync : Ogg.Sync.t -> t (** Open the passed file name as a new speex stream. *) val open_file : string -> t * Unix.file_descr (** Open the passed feed as a new speex stream. *) val open_feed : read -> t (** Get the serial of the stream currently being decoded. * This value may change if the stream contains sequentialized ogg streams. *) val serial : t -> nativeint (** Get current comments. *) val comments : t -> (string * string) list (** Get current header. *) val header : t -> Header.t (** Decode audio data. *) val decode : t -> float array list (** Decode stereo audio data. *) val decode_stereo : t -> float array array list (** Decode audio data, passing it to a feed. *) val decode_feed : t -> (float array -> unit) -> unit (** Same as [decode_feed] but with stereo data. *) val decode_feed_stereo : t -> (float array array -> unit) -> unit (** Same as [decode] but with integers. *) val decode_int : t -> int array list (** Same as [decode_stereo] but with integers. *) val decode_int_stereo : t -> int array array list (** Same as [decode_feed] but with integers. *) val decode_int_feed : t -> (int array -> unit) -> unit (** Same as [decode_int_feed_stereo] but with integers. *) val decode_int_feed_stereo : t -> (int array array -> unit) -> unit 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/speex"] * * See: http://xiph.org/ogg/doc/skeleton.html. *) val fisbone : ?start_granule:Int64.t -> ?headers:(string * string) list -> serialno:nativeint -> header:Header.t -> unit -> Ogg.Stream.packet end ocaml-speex-0.4.1/src/speex_decoder.ml000066400000000000000000000061121416533617200176730ustar00rootroot00000000000000(* * Copyright 2003-2011 Savonet team * * This file is part of Ocaml-speex. * * Ocaml-speex 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-speex 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-speex; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) let check p = try let _ = Speex.Header.header_of_packet p in true with _ -> false let decoder os = let dec_p = ref None in let decoder = ref None in let com_p = ref None in let os = ref os in let init () = match !decoder with | None -> let dec_p = match !dec_p with | None -> let packet = Ogg.Stream.get_packet !os in dec_p := Some packet; packet | Some p -> p in let com_p = match !com_p with | None -> let packet = Ogg.Stream.get_packet !os in com_p := Some packet; packet | Some p -> p in let header = Speex.Header.header_of_packet dec_p in let meta = Speex.Header.comments_of_packet com_p in let mode = header.Speex.Header.mode in let dec = Speex.Decoder.init mode in let sample_freq = header.Speex.Header.rate in let chans = header.Speex.Header.nb_channels in Speex.Decoder.set dec Speex.SPEEX_SET_SAMPLING_RATE sample_freq; decoder := Some (dec, sample_freq, chans, meta); (dec, sample_freq, chans, meta) | Some d -> d in let info () = let _, rate, chans, meta = init () in ({ Ogg_decoder.channels = chans; sample_rate = rate }, meta) in let decode feed = let dec, _, chans, _ = init () in let len = ref 0 in let feed buf = let buf = Array.map (Array.map (fun x -> float x /. 32768.)) buf in len := !len + Array.length buf.(0); feed buf in try let decode dec os feed = if chans = 2 then Speex.Decoder.decode_int_feed_stereo dec os feed else ( let feed x = feed [| x |] in Speex.Decoder.decode_int_feed dec os feed) in decode dec !os feed with Ogg.Not_enough_data -> if !len = 0 then raise Ogg.Not_enough_data in let restart new_os = os := new_os; let d, _, _, _ = init () in Speex.Decoder.set d Speex.SPEEX_RESET_STATE 0 in Ogg_decoder.Audio { Ogg_decoder.name = "speex"; info; restart; decode; samples_of_granulepos = (fun x -> x); } let register () = Hashtbl.add Ogg_decoder.ogg_decoders "speex" (check, decoder) ocaml-speex-0.4.1/src/speex_decoder.mli000066400000000000000000000016121416533617200200440ustar00rootroot00000000000000(* * Copyright 2003-2011 Savonet team * * This file is part of Ocaml-speex. * * Ocaml-speex 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-speex 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-speex; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** Speex decoder for the [Ogg_demuxer] module. *) (** Register the decoder. *) val register : unit -> unit ocaml-speex-0.4.1/src/speex_stubs.c000066400000000000000000000565051416533617200172530ustar00rootroot00000000000000/* Copyright 2003-2008 Savonet team This file is part of Ocaml-speex. Ocaml-speex 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-speex 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-speex; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef Bytes_val #define Bytes_val String_val #endif /* Comment API */ /* This is stolen from speexenc.c * It should definitely be part of the library.. */ /* Comments will be stored in the Vorbis style. It is describled in the "Structure" section of http://www.xiph.org/ogg/vorbis/doc/v-comment.html The comment header is decoded as follows: 1) [vendor_length] = read an unsigned integer of 32 bits 2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets 3) [user_comment_list_length] = read an unsigned integer of 32 bits 4) iterate [user_comment_list_length] times { 5) [length] = read an unsigned integer of 32 bits 6) this iteration's user comment = read a UTF-8 vector as [length] octets } 7) [framing_bit] = read a single bit as boolean 8) if ( [framing_bit] unset or end of packet ) then ERROR 9) done. If you have troubles, please write to ymnk@jcraft.com. */ #define readint(buf, base) \ (((buf[base + 3] << 24) & 0xff000000) | ((buf[base + 2] << 16) & 0xff0000) | \ ((buf[base + 1] << 8) & 0xff00) | (buf[base] & 0xff)) #define writeint(buf, base, val) \ do { \ buf[base + 3] = ((val) >> 24) & 0xff; \ buf[base + 2] = ((val) >> 16) & 0xff; \ buf[base + 1] = ((val) >> 8) & 0xff; \ buf[base] = (val)&0xff; \ } while (0) void comment_init(char **comments, int *length, char *vendor_string) { int vendor_length = strlen(vendor_string); int user_comment_list_length = 0; int len = 4 + vendor_length + 4; char *p = (char *)malloc(len); if (p == NULL) caml_raise_out_of_memory(); writeint(p, 0, vendor_length); memcpy(p + 4, vendor_string, vendor_length); writeint(p, 4 + vendor_length, user_comment_list_length); *length = len; *comments = p; } void comment_add(char **comments, int *length, char *val) { char *p = *comments; int vendor_length = readint(p, 0); int user_comment_list_length = readint(p, 4 + vendor_length); int val_len = strlen(val); int len = (*length) + 4 + val_len; p = (char *)realloc(p, len); if (p == NULL) { caml_failwith("realloc"); } writeint(p, *length, val_len); /* length of comment */ memcpy(p + *length + 4, val, val_len); /* comment */ writeint(p, 4 + vendor_length, user_comment_list_length + 1); *comments = p; *length = len; } CAMLprim value caml_speex_comments_of_packet(value o_packet) { CAMLparam1(o_packet); CAMLlocal2(ret, tmp); ogg_packet *op = Packet_val(o_packet); char *c = (char *)op->packet; int length = op->bytes; int len, i, nb_fields; char *end; if (length < 8) caml_failwith("Invalid comments raw length"); end = c + length; len = readint(c, 0); c += 4; if (len < 0 || c + len > end) caml_failwith("Invalid comments raw data"); tmp = caml_alloc_string(len); memcpy(Bytes_val(tmp), c, len); c += len; if (c + 4 > end) caml_failwith("Invalid comments raw data"); nb_fields = readint(c, 0); ret = caml_alloc_tuple(nb_fields + 1); Store_field(ret, 0, tmp); c += 4; for (i = 0; i < nb_fields; i++) { if (c + 4 > end) caml_failwith("Invalid comments raw data"); len = readint(c, 0); c += 4; if (len < 0 || c + len > end) caml_failwith("Invalid comments raw data"); tmp = caml_alloc_string(len); memcpy(Bytes_val(tmp), c, len); Store_field(ret, i + 1, tmp); c += len; } CAMLreturn(ret); } #undef readint #undef writeint /* Mode API */ #define Mode_val(v) (*((SpeexMode **)Data_abstract_val(v))) static inline value value_of_speex_mode(value v, const SpeexMode *s) { v = caml_alloc(1, Abstract_tag); *((const SpeexMode **)Data_abstract_val(v)) = s; return v; } CAMLprim value caml_speex_get_mode(value i) { CAMLparam0(); CAMLlocal1(ret); CAMLreturn(value_of_speex_mode(ret, speex_lib_get_mode(Int_val(i)))); } /* Header API */ static SpeexHeader *header_of_value(value v, SpeexHeader *header) { int i = 0; value tmp; tmp = Field(v, i++); if (caml_string_length(tmp) > SPEEX_HEADER_STRING_LENGTH) caml_invalid_argument("wrong argument: speex_string too long"); memcpy(header->speex_string, String_val(tmp), caml_string_length(tmp)); tmp = Field(v, i++); if (caml_string_length(tmp) > SPEEX_HEADER_VERSION_LENGTH) caml_invalid_argument("wrong argument: speex_version too long"); memcpy(header->speex_version, String_val(tmp), caml_string_length(tmp)); #define shv(x) header->x = Int_val(Field(v, i++)) shv(speex_version_id); shv(header_size); shv(rate); header->mode = Int_val(caml_callback( *caml_named_value("caml_speex_int_of_mode"), Field(v, i++))); shv(mode_bitstream_version); shv(nb_channels); shv(bitrate); shv(frame_size); Store_field(v, i++, Val_bool(header->vbr)); shv(frames_per_packet); shv(extra_headers); return header; } CAMLprim value value_of_header(SpeexHeader *header) { CAMLparam0(); CAMLlocal2(ret, tmp); ret = caml_alloc_tuple(13); int i = 0; tmp = caml_alloc_string(SPEEX_HEADER_STRING_LENGTH); memcpy(Bytes_val(tmp), header->speex_string, SPEEX_HEADER_STRING_LENGTH); Store_field(ret, i++, tmp); tmp = caml_alloc_string(SPEEX_HEADER_VERSION_LENGTH); memcpy(Bytes_val(tmp), header->speex_version, SPEEX_HEADER_VERSION_LENGTH); Store_field(ret, i++, tmp); #define svh(v) Store_field(ret, i++, Val_int(header->v)); svh(speex_version_id); svh(header_size); svh(rate); Store_field(ret, i++, caml_callback(*caml_named_value("caml_speex_mode_of_int"), Val_int(header->mode))); svh(mode_bitstream_version); svh(nb_channels); svh(bitrate); svh(frame_size); Store_field(ret, i++, Val_bool(header->vbr)); svh(frames_per_packet); svh(extra_headers); CAMLreturn(ret); } CAMLprim value caml_speex_init_header(value rate, value chans, value mode, value fpp, value vbr) { CAMLparam1(mode); struct SpeexMode *m = Mode_val(mode); SpeexHeader header; speex_init_header(&header, Int_val(rate), 1, m); header.frames_per_packet = Int_val(fpp); header.vbr = Int_val(vbr); header.nb_channels = Int_val(chans); CAMLreturn(value_of_header(&header)); } CAMLprim value caml_speex_encode_header(value v, value o_comments) { CAMLparam2(v, o_comments); CAMLlocal1(ret); ogg_packet op; int packet_size; SpeexHeader header; char *vendor_string = "ocaml-speex by the savonet team (http://savonet.sf.net/)"; char *comments; int comments_length; int i; ret = caml_alloc_tuple(2); unsigned char *data = (unsigned char *)speex_header_to_packet( header_of_value(v, &header), &packet_size); op.packet = data; op.bytes = packet_size; op.b_o_s = 1; op.e_o_s = 0; op.granulepos = 0; op.packetno = 0; Store_field(ret, 0, value_of_packet(&op)); free(data); /* Comment Packet */ comment_init(&comments, &comments_length, vendor_string); for (i = 0; i < Wosize_val(o_comments); i++) comment_add(&comments, &comments_length, (char *)Bytes_val(Field(o_comments, i))); op.packet = (unsigned char *)comments; op.bytes = comments_length; op.b_o_s = 0; op.e_o_s = 0; op.granulepos = 0; op.packetno = 1; Store_field(ret, 1, value_of_packet(&op)); free(comments); CAMLreturn(ret); } CAMLprim value caml_speex_header_of_packet(value packet) { CAMLparam1(packet); CAMLlocal1(ret); ogg_packet *op = Packet_val(packet); if (op->bytes < sizeof(SpeexHeader)) caml_invalid_argument("not a speex header"); caml_enter_blocking_section(); SpeexHeader *header = speex_packet_to_header((char *)op->packet, op->bytes); caml_leave_blocking_section(); if (header == NULL) caml_invalid_argument("not a speex header"); ret = value_of_header(header); speex_header_free(header); CAMLreturn(ret); } /* Encoder API */ typedef struct cenc_t { int position; SpeexBits bits; void *enc; int fpp; } cenc_t; #define Enc_val(v) (*((cenc_t **)Data_custom_val(v))) static void finalize_speex_enc(value v) { cenc_t *enc = Enc_val(v); speex_bits_destroy(&enc->bits); speex_encoder_destroy(enc->enc); free(enc); } static struct custom_operations speex_enc_ops = { "ocaml_speex_enc", finalize_speex_enc, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; CAMLprim value ocaml_speex_enc_init(value m, value fpp) { CAMLparam1(m); CAMLlocal1(ret); cenc_t *cen = malloc(sizeof(cenc_t)); if (cen == NULL) caml_raise_out_of_memory(); SpeexMode *mode = Mode_val(m); void *enc = speex_encoder_init(mode); if (enc == NULL) caml_raise_out_of_memory(); speex_bits_init(&cen->bits); cen->enc = enc; cen->position = 0; cen->fpp = Int_val(fpp); ret = caml_alloc_custom(&speex_enc_ops, sizeof(cenc_t *), 1, 0); Enc_val(ret) = cen; CAMLreturn(ret); } CAMLprim value ocaml_speex_encoder_ctl_get(value e, value n) { CAMLparam1(e); cenc_t *cenc = Enc_val(e); void *enc = cenc->enc; int ret; if (speex_encoder_ctl(enc, Int_val(n), &ret) == -2) caml_invalid_argument("wrong argument in speex_encoder_ctl"); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_speex_encoder_ctl_set(value e, value n, value x) { CAMLparam1(e); cenc_t *cenc = Enc_val(e); void *enc = cenc->enc; int arg = Int_val(x); if (speex_encoder_ctl(enc, Int_val(n), &arg) == -2) caml_invalid_argument("wrong argument in speex_encoder_ctl"); CAMLreturn(Val_unit); } CAMLprim value ocaml_speex_encode_page(value e_state, value o_chans, value o_stream_state, value feed) { CAMLparam3(e_state, feed, o_stream_state); CAMLlocal2(v, ret); ogg_stream_state *os = Stream_state_val(o_stream_state); cenc_t *cenc = Enc_val(e_state); void *enc = cenc->enc; ogg_page og; ogg_packet op; int state = cenc->position - 1; int len; int frame_size; int fpp = cenc->fpp; int chans = Int_val(o_chans); speex_encoder_ctl(enc, SPEEX_GET_FRAME_SIZE, &frame_size); int i; float *data = malloc(sizeof(float) * frame_size * chans); if (data == NULL) caml_raise_out_of_memory(); char *cbits = malloc(sizeof(char) * frame_size * chans); if (cbits == NULL) { free(data); caml_raise_out_of_memory(); } int nbBytes; /* Is there an audio page flushed? If not, work until there is. */ do { if (ogg_stream_eos(os)) { free(data); free(cbits); caml_raise_constant(*caml_named_value("ocaml_speex_eos_exn")); } /* Read and process more audio. */ v = caml_callback_exn(feed, Val_unit); if Is_exception_result (v) { free(data); free(cbits); cenc->position = state + 1; caml_raise(Extract_exception(v)); } len = Wosize_val(v) / Double_wosize; if (len != frame_size * chans) { free(data); free(cbits); cenc->position = state + 1; caml_raise_constant(*caml_named_value("ocaml_speex_invfrlen_exn")); } for (i = 0; i < len; i++) data[i] = Double_field(v, i); caml_enter_blocking_section(); if (chans == 2) speex_encode_stereo(data, frame_size, &cenc->bits); speex_encode(enc, data, &cenc->bits); caml_leave_blocking_section(); state++; if ((state + 1) % fpp != 0) continue; speex_bits_insert_terminator(&cenc->bits); nbBytes = speex_bits_write(&cenc->bits, cbits, frame_size * fpp); speex_bits_reset(&cenc->bits); op.packet = (unsigned char *)cbits; op.bytes = nbBytes; op.b_o_s = 0; op.e_o_s = 0; op.granulepos = (state + 1) * frame_size; op.packetno = 2 + state / fpp; /* Put the packet in the ogg stream. */ ogg_stream_packetin(os, &op); } while (ogg_stream_pageout(os, &og) <= 0); cenc->position = state + 1; ret = value_of_page(&og); free(data); free(cbits); CAMLreturn(ret); } CAMLprim value ocaml_speex_encode_page_int(value e_state, value o_chans, value o_stream_state, value feed) { CAMLparam3(e_state, feed, o_stream_state); CAMLlocal2(v, ret); ogg_stream_state *os = Stream_state_val(o_stream_state); cenc_t *cenc = Enc_val(e_state); void *enc = cenc->enc; ogg_page og; ogg_packet op; int state = cenc->position - 1; int len; int chans = Int_val(o_chans); int frame_size; int fpp = cenc->fpp; speex_encoder_ctl(enc, SPEEX_GET_FRAME_SIZE, &frame_size); int i; spx_int16_t *data = malloc(sizeof(spx_int16_t) * frame_size * chans); if (data == NULL) caml_raise_out_of_memory(); char *cbits = malloc(sizeof(char) * frame_size * chans); if (cbits == NULL) { free(data); caml_raise_out_of_memory(); } int nbBytes; /* Is there an audio page flushed? If not, work until there is. */ do { if (ogg_stream_eos(os)) { free(data); free(cbits); caml_raise_constant(*caml_named_value("ocaml_speex_eos_exn")); } /* Read and process more audio. */ v = caml_callback_exn(feed, Val_unit); if Is_exception_result (v) { free(data); free(cbits); cenc->position = state + 1; caml_raise(Extract_exception(v)); } len = Wosize_val(v); if (len != frame_size * chans) { free(data); free(cbits); cenc->position = state + 1; caml_raise_constant(*caml_named_value("ocaml_speex_invfrlen_exn")); } for (i = 0; i < len; i++) data[i] = Int_val(Field(v, i)); caml_enter_blocking_section(); if (chans == 2) speex_encode_stereo_int(data, frame_size, &cenc->bits); speex_encode_int(enc, data, &cenc->bits); caml_leave_blocking_section(); state++; if ((state + 1) % fpp != 0) continue; speex_bits_insert_terminator(&cenc->bits); nbBytes = speex_bits_write(&cenc->bits, cbits, frame_size); speex_bits_reset(&cenc->bits); op.packet = (unsigned char *)cbits; op.bytes = nbBytes; op.b_o_s = 0; op.e_o_s = 0; op.granulepos = (state + 1) * frame_size; op.packetno = 2 + state / fpp; /* Put the packet in the ogg stream. */ ogg_stream_packetin(os, &op); } while (ogg_stream_pageout(os, &og) <= 0); cenc->position = state + 1; ret = value_of_page(&og); free(data); free(cbits); CAMLreturn(ret); } CAMLprim value ocaml_speex_encoder_eos(value v, value o_stream_state) { CAMLparam2(v, o_stream_state); ogg_packet op; ogg_stream_state *os = Stream_state_val(o_stream_state); cenc_t *cenc = Enc_val(v); int state = cenc->position - 1; void *enc = cenc->enc; int frame_size; speex_encoder_ctl(enc, SPEEX_GET_FRAME_SIZE, &frame_size); op.packet = (unsigned char *)NULL; op.bytes = 0; op.b_o_s = 0; op.e_o_s = 1; op.granulepos = (state + 1) * frame_size; op.packetno = 2 + state; ogg_stream_packetin(os, &op); CAMLreturn(Val_unit); } /* Decoder API */ typedef struct cdec_t { SpeexStereoState *stereo; SpeexBits bits; void *dec; } cdec_t; #define Dec_val(v) (*((cdec_t **)Data_custom_val(v))) static void finalize_speex_dec(value v) { cdec_t *cdec = Dec_val(v); speex_stereo_state_destroy(cdec->stereo); speex_bits_destroy(&cdec->bits); speex_decoder_destroy(cdec->dec); free(cdec); } static struct custom_operations speex_dec_ops = { "ocaml_speex_dec", finalize_speex_dec, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; CAMLprim value ocaml_speex_dec_init(value m) { CAMLparam1(m); CAMLlocal1(ret); SpeexMode *mode = Mode_val(m); void *dec = speex_decoder_init(mode); if (dec == NULL) caml_raise_out_of_memory(); SpeexStereoState *stereo = speex_stereo_state_init(); if (stereo == NULL) caml_raise_out_of_memory(); cdec_t *cdec = malloc(sizeof(cdec_t)); if (cdec == NULL) caml_raise_out_of_memory(); cdec->dec = dec; speex_bits_init(&cdec->bits); cdec->stereo = stereo; SpeexCallback callback; callback.callback_id = SPEEX_INBAND_STEREO; callback.func = speex_std_stereo_request_handler; callback.data = stereo; speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback); ret = caml_alloc_custom(&speex_dec_ops, sizeof(cdec_t *), 1, 0); Dec_val(ret) = cdec; CAMLreturn(ret); } CAMLprim value ocaml_speex_decoder_ctl_get(value e, value n) { CAMLparam1(e); cdec_t *cdec = Dec_val(e); void *dec = cdec->dec; int ret; if (speex_decoder_ctl(dec, Int_val(n), &ret) == -2) caml_invalid_argument("wrong argument in speex_decoder_ctl"); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_speex_decoder_ctl_set(value e, value n, value x) { CAMLparam1(e); cdec_t *cdec = Dec_val(e); void *dec = cdec->dec; int arg = Int_val(x); if (speex_decoder_ctl(dec, Int_val(n), &arg) == -2) caml_invalid_argument("wrong argument in speex_decoder_ctl"); CAMLreturn(Val_unit); } CAMLprim value ocaml_speex_decoder_decode(value e, value o_chans, value s, value add) { CAMLparam3(e, s, add); CAMLlocal2(ret, v); ogg_stream_state *os = Stream_state_val(s); cdec_t *cdec = Dec_val(e); void *dec = cdec->dec; SpeexStereoState *stereo = cdec->stereo; int chans = Int_val(o_chans); int err; ogg_packet op; int frame_size; speex_decoder_ctl(dec, SPEEX_GET_FRAME_SIZE, &frame_size); float *out = malloc(sizeof(float) * frame_size * chans); if (out == NULL) caml_raise_out_of_memory(); int i; int n; while (1) { err = ogg_stream_packetout(os, &op); if (err <= 0) { free(out); if (err == 0) caml_raise_constant(*caml_named_value("ogg_exn_not_enough_data")); else caml_raise_constant(*caml_named_value("ogg_exn_out_of_sync")); } /* Copy Ogg packet to Speex bitstream */ caml_enter_blocking_section(); speex_bits_read_from(&cdec->bits, (char *)op.packet, op.bytes); caml_leave_blocking_section(); while (1) { caml_enter_blocking_section(); n = speex_decode(dec, &cdec->bits, out); caml_leave_blocking_section(); if (n == -1) break; if (chans == 2) speex_decode_stereo(out, frame_size, stereo); ret = caml_alloc(frame_size * chans * Double_wosize, Double_array_tag); for (i = 0; i < frame_size * chans; i++) Store_double_field(ret, i, out[i]); v = caml_callback_exn(add, ret); if Is_exception_result (v) { free(out); caml_raise(Extract_exception(v)); } }; } free(out); CAMLreturn(Val_unit); } CAMLprim value ocaml_speex_decoder_decode_int(value e, value o_chans, value s, value add) { CAMLparam3(e, s, add); CAMLlocal2(ret, v); ogg_stream_state *os = Stream_state_val(s); cdec_t *cdec = Dec_val(e); void *dec = cdec->dec; SpeexStereoState *stereo = cdec->stereo; int chans = Int_val(o_chans); int err; ogg_packet op; int frame_size; speex_decoder_ctl(dec, SPEEX_GET_FRAME_SIZE, &frame_size); spx_int16_t *out = malloc(sizeof(spx_int16_t) * frame_size * chans); if (out == NULL) caml_raise_out_of_memory(); int i; int n; while (1) { err = ogg_stream_packetout(os, &op); if (err <= 0) { free(out); if (err == 0) caml_raise_constant(*caml_named_value("ogg_exn_not_enough_data")); else caml_raise_constant(*caml_named_value("ogg_exn_out_of_sync")); } /* Copy Ogg packet to Speex bitstream */ speex_bits_read_from(&cdec->bits, (char *)op.packet, op.bytes); while (1) { caml_enter_blocking_section(); n = speex_decode_int(dec, &cdec->bits, out); caml_leave_blocking_section(); if (n == -1) break; if (chans == 2) speex_decode_stereo_int(out, frame_size, stereo); ret = caml_alloc_tuple(frame_size * chans); for (i = 0; i < frame_size * chans; i++) Store_field(ret, i, Int_val(out[i])); v = caml_callback_exn(add, ret); if Is_exception_result (v) { free(out); caml_raise(Extract_exception(v)); } }; } free(out); CAMLreturn(Val_unit); } /* Ogg skeleton support */ /* 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 /* Values from speexenc.c in speexenc */ CAMLprim value ocaml_speex_skeleton_fisbone(value serial, value _header, value start, value content) { CAMLparam4(serial, _header, start, content); CAMLlocal1(packet); ogg_packet op; SpeexHeader header; header_of_value(_header, &header); 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 speex 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, 2 + header.extra_headers); /* number of header packet */ /* granulerate, temporal resolution of the bitstream in Hz */ write64le(op.packet + 20, (ogg_int64_t)header.rate); /* 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, 3); /* preroll, for speex its 3 */ *(op.packet + 48) = 0; /* granule shift, always 0 for speex */ 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); }