pax_global_header00006660000000000000000000000064140214330200014477gustar00rootroot0000000000000052 comment=9db7f0e40330130cc1765a6d2813f91b0261d165 ocaml-theora-0.4.0/000077500000000000000000000000001402143302000140535ustar00rootroot00000000000000ocaml-theora-0.4.0/.github/000077500000000000000000000000001402143302000154135ustar00rootroot00000000000000ocaml-theora-0.4.0/.github/workflows/000077500000000000000000000000001402143302000174505ustar00rootroot00000000000000ocaml-theora-0.4.0/.github/workflows/main.yml000066400000000000000000000006621402143302000211230ustar00rootroot00000000000000name: 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 theora - run: opam install -t . ocaml-theora-0.4.0/.gitignore000066400000000000000000000000631402143302000160420ustar00rootroot00000000000000*~ _build *.byte *.native _tests .merlin *.install ocaml-theora-0.4.0/.ocamlformat000066400000000000000000000003201402143302000163530ustar00rootroot00000000000000profile = 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-theora-0.4.0/CHANGES000066400000000000000000000014741402143302000150540ustar00rootroot000000000000000.4.0 (08-03-2021) ====== * Switch to dune 0.3.1 (03-08-2015) ===== * Changed types to match new ocaml-ogg's API. Should be fully backward compatible. 0.3.0 (04-07-2011) ===== * New encoding settings, including keyframe frequency * Added decoding module for the new Ogg_demuxer module * Implement new Out_of_sync exception * Efficient seeking support 0.2.0 (19-06-2010) ===== * Binding for 1.1 theora API. 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 COPYING file. 0.1.0 (17-02-2009) ===== * Initial release ocaml-theora-0.4.0/COPYING000066400000000000000000000431311402143302000151100ustar00rootroot00000000000000 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-theora-0.4.0/README.md000066400000000000000000000010761402143302000153360ustar00rootroot00000000000000ocaml-theora ============ This package contains an OCaml interface for the `theora` library Please read the COPYING file before using this software. Prerequisites: ============== - ocaml - libtheora - 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 theora ``` Via `dune` (for developers): ``` $ dune install ``` This should install the library file in the appropriate place. ocaml-theora-0.4.0/dune-project000066400000000000000000000006631402143302000164020ustar00rootroot00000000000000(lang dune 2.0) (version 0.4.0) (name theora) (source (github savonet/ocaml-theora)) (license GPL-2.0) (authors "The Savonet Team ") (maintainers "The Savonet Team ") (generate_opam_files true) (package (name theora) (synopsis "Bindings to libtheora") (depends conf-libtheora conf-pkg-config (dune (>= 2.0)) dune-configurator (ogg (>= 0.7.0))) ) ocaml-theora-0.4.0/examples/000077500000000000000000000000001402143302000156715ustar00rootroot00000000000000ocaml-theora-0.4.0/examples/dune000066400000000000000000000000651402143302000165500ustar00rootroot00000000000000(executable (name thtranscode) (libraries theora)) ocaml-theora-0.4.0/examples/thtranscode.ml000066400000000000000000000107151402143302000205450ustar00rootroot00000000000000(* Shamelessly inspired of http://theora.org/doc/libtheora-1.0beta1/ *) exception No_theora open Theora let infile = ref "input.ogg" let outfile = ref "output.ogg" let debug = ref false let quality = ref 40 let () = Arg.parse [ ("-d", Arg.Set debug, "Show debugging messages"); ("-o", Arg.Set_string outfile, "Output file"); ("-q", Arg.Set_int quality, "Quality of the compression"); ("-i", Arg.Set_string infile, "Input file"); ] ignore "thranscode [options]" let in_init () = let sync, fd = Ogg.Sync.create_from_file !infile in let rec fill os = let page = Ogg.Sync.read sync in try (* We drop pages which are not for us.. *) if Ogg.Page.serialno page = Ogg.Stream.serialno os then Ogg.Stream.put_page os page with Ogg.Bad_data -> fill os (* Do not care about page that are not for us.. *) in (* Test wether the stream is theora *) let test_theora () = (* 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 No_theora; (* Create a stream with this ID *) let serial = Ogg.Page.serialno page in Printf.printf "Testing stream %nx\n" serial; let os = Ogg.Stream.create ~serial () in Ogg.Stream.put_page os page; let packet = Ogg.Stream.get_packet os in (* Test header. Do not catch anything, first page should be sufficient *) if not (Decoder.check packet) then raise Not_found; Printf.printf "Got a theora stream !\n"; let dec = Decoder.create () in (* Decode headers *) let rec f packet = try Decoder.headerin dec packet with Ogg.Not_enough_data -> let rec g () = try let packet = Ogg.Stream.get_packet os in f packet with Ogg.Not_enough_data -> fill os; g () in g () in let dec, info, vendor, comments = f packet in (serial, os, dec, info, vendor, comments) in (* Now find a theora stream *) let rec init () = try test_theora () with | Not_found -> Printf.printf "This stream was not theora..\n"; init () | No_theora -> Printf.printf "No theora stream was found..\n%!"; raise No_theora in let serial, os, t, info, vendor, comments = init () in Printf.printf "Ogg logical stream %nx is Theora %dx%d %.02f fps video\n" serial info.frame_width info.frame_height (float_of_int info.fps_numerator /. float_of_int info.fps_denominator); Printf.printf "Encoded frame content is %dx%d with %dx%d offset\n" info.picture_width info.picture_height info.picture_x info.picture_y; Printf.printf "YUV4MPEG2 W%d H%d F%d:%d I%c A%d:%d\n" info.frame_width info.frame_height info.fps_numerator info.fps_denominator 'p' info.aspect_numerator info.aspect_denominator; Printf.printf "Vendor: %s\n" vendor; List.iter (fun (x, y) -> Printf.printf "%s: %s\n" x y) comments; flush_all (); (t, os, fill, info, fd) let out_init info = let oc = open_out !outfile in let out s = output_string oc s; flush oc in let os = Ogg.Stream.create () in let settings = { Encoder.keyframe_frequency = None; vp3_compatible = None; soft_target = None; buffer_delay = None; speed = None; } in let comments = [("artitst", "test artist"); ("title", "test title")] in let t = Encoder.create info settings comments in let s_o_p (h, b) = h ^ b in Encoder.encode_header t os; out (s_o_p (Ogg.Stream.flush_page os)); (t, os, out) let () = let dec, is, fill, info, fd = in_init () in let info = { info with target_bitrate = 0; quality = !quality } in let enc, os, out = out_init info in let latest_yuv = ref None in let rec generator () = try let yuv = Decoder.get_yuv dec is in latest_yuv := Some yuv; yuv with | Ogg.Not_enough_data when not (Ogg.Stream.eos is) -> fill is; generator () | Duplicate_frame -> ( (* Got a duplicate frame, sending previous one ! *) match !latest_yuv with Some x -> x | None -> raise Internal_error) in let s_o_p (h, b) = h ^ b in Printf.printf "Starting transcoding loop !\n%!"; begin try while true do let op = Encoder.encode_page enc os generator in let op = s_o_p op in out op done with Ogg.Not_enough_data -> () end; Encoder.eos enc os; out (s_o_p (Ogg.Stream.flush_page os)); Unix.close fd; Gc.full_major () ocaml-theora-0.4.0/src/000077500000000000000000000000001402143302000146425ustar00rootroot00000000000000ocaml-theora-0.4.0/src/config/000077500000000000000000000000001402143302000161075ustar00rootroot00000000000000ocaml-theora-0.4.0/src/config/discover.ml000066400000000000000000000011031402143302000202520ustar00rootroot00000000000000module C = Configurator.V1 let () = C.main ~name:"theora-pkg-config" (fun c -> let default : C.Pkg_config.package_conf = { libs = ["-ltheoraenc";"-ltheoradec"]; cflags = [] } in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> ( match C.Pkg_config.query pc ~package:"theoradec theoraenc" 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-theora-0.4.0/src/config/dune000066400000000000000000000000751402143302000167670ustar00rootroot00000000000000(executable (name discover) (libraries dune.configurator)) ocaml-theora-0.4.0/src/dune000066400000000000000000000010361402143302000155200ustar00rootroot00000000000000(library (name theora) (public_name theora) (synopsis "OCaml bindings for libtheora") (libraries ogg) (modules theora) (foreign_stubs (language c) (names theora_stubs) (flags (:include c_flags.sexp))) (c_library_flags (:include c_library_flags.sexp))) (library (name theora_decoder) (public_name theora.decoder) (synopsis "Theora decoder for the ogg-decoder library") (libraries ogg.decoder theora) (modules theora_decoder)) (rule (targets c_flags.sexp c_library_flags.sexp) (action (run ./config/discover.exe))) ocaml-theora-0.4.0/src/theora.ml000066400000000000000000000137361402143302000164700ustar00rootroot00000000000000(* * Copyright 2007-2011 Savonet team * * This file is part of ocaml-theora. * * ocaml-theora 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-theora 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-theora; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Functions for encoding theora files using libtheora. * * @author Samuel Mimram * @author Romain Beauxis *) exception Internal_error exception Invalid_data exception Unknown_error of int exception Duplicate_frame exception Done exception Not_initialized let () = Callback.register_exception "theora_exn_fault" Internal_error; Callback.register_exception "theora_exn_inval" Invalid_data; Callback.register_exception "theora_exn_unknown" (Unknown_error 0); Callback.register_exception "theora_exn_dup_frame" Duplicate_frame; Callback.register_exception "theora_exn_not_enough_data" Ogg.Not_enough_data; Callback.register_exception "theora_exn_end_of_file" End_of_file external version_string : unit -> string = "ocaml_theora_version_string" let version_string = version_string () external version_number : unit -> int = "ocaml_theora_version_number" let version_number = let n = version_number () in (n lsr 16, (n lsr 8) land 0xff, n land 0xff) type colorspace = | CS_unspecified | CS_ITU_REC_470M | CS_ITU_REC_470BG | CS_NSPACES type pixelformat = PF_420 | PF_reserved | PF_422 | PF_444 type info = { frame_width : int; (** The encoded frame width. *) frame_height : int; (** The encoded frame height. *) picture_width : int; (** The displayed picture width. *) picture_height : int; (** The displayed picture height. *) picture_x : int; (** The X offset of the displayed picture. *) picture_y : int; (** The Y offset of the displayed picture. *) colorspace : colorspace; (** The color space. *) pixel_fmt : pixelformat; (** The pixel format. *) target_bitrate : int; (** The target bit-rate in bits per second. *) quality : int; (** The target quality level. *) keyframe_granule_shift : int; (** The amount to shift to extract the last keyframe number from the granule position. *) version_major : int; version_minor : int; version_subminor : int; fps_numerator : int; fps_denominator : int; aspect_numerator : int; aspect_denominator : int; } external default_granule_shift : unit -> int = "ocaml_theora_default_granuleshift" let default_granule_shift = default_granule_shift () type data_buffer = (int, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t type yuv_buffer = { y_width : int; y_height : int; y_stride : int; y : data_buffer; u_width : int; u_height : int; u_stride : int; u : data_buffer; v_width : int; v_height : int; v_stride : int; v : data_buffer; } let encoder_tag = "ocaml-theora by the savonet team (http://savonet.sf.net/)" external is_keyframe : Ogg.Stream.packet -> int = "ocaml_theora_ogg_packet_iskeyframe" let is_keyframe op = match is_keyframe op with 1 -> true | 0 -> false | _ -> raise Invalid_data module Encoder = struct type t type settings = { keyframe_frequency : int option; vp3_compatible : bool option; soft_target : bool option; buffer_delay : int option; speed : int option; } external create : info -> settings -> (string * string) array -> t = "ocaml_theora_encode_init" let create info params comments = let comments = ("ENCODER", encoder_tag) :: comments in create info params (Array.of_list comments) external encode_header : t -> Ogg.Stream.stream -> bool = "ocaml_theora_encode_header" let encode_header enc os = let rec f () = if not (encode_header enc os) then f () in f () external encode_buffer : t -> Ogg.Stream.stream -> yuv_buffer -> unit = "ocaml_theora_encode_buffer" let encode_page enc os generator = let rec f () = try let yuv = generator () in encode_buffer enc os yuv; Ogg.Stream.get_page os with Ogg.Not_enough_data -> f () in f () external frames_of_granulepos : t -> Int64.t -> Int64.t = "ocaml_theora_encoder_frame_of_granulepos" external eos : t -> Ogg.Stream.stream -> unit = "ocaml_theora_encode_eos" end module Decoder = struct type decoder type t external check : Ogg.Stream.packet -> bool = "caml_theora_check" external create : unit -> decoder = "ocaml_theora_create_dec" external headerin : decoder -> Ogg.Stream.packet -> info * string array = "ocaml_theora_dec_headerin" let headerin dec p = let info, comments = headerin dec p in let vendor, comments = match Array.to_list comments with e :: l -> (e, l) | [] -> ("", []) in let split s = try let pos = String.index s '=' in (String.sub s 0 pos, String.sub s (pos + 1) (String.length s - pos - 1)) with Not_found -> ("", s) in (Obj.magic dec, info, vendor, List.map split comments) external frames_of_granulepos : t -> Int64.t -> Int64.t = "ocaml_theora_decoder_frame_of_granulepos" external get_yuv : t -> Ogg.Stream.stream -> yuv_buffer = "ocaml_theora_decode_YUVout" end module Skeleton = struct external fisbone : Nativeint.t -> info -> Int64.t -> string -> Ogg.Stream.packet = "ocaml_theora_skeleton_fisbone" let fisbone ?(start_granule = Int64.zero) ?(headers = [("Content-type", "video/theora")]) ~serialno ~info () = 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 info start_granule s end ocaml-theora-0.4.0/src/theora.mli000066400000000000000000000174261402143302000166410ustar00rootroot00000000000000(* * Copyright 2007-2009 Samuel Mimram, Romain Beauxis * * This file is part of ocaml-theora. * * ocaml-theora 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-theora 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-theora; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Functions for encoding theora files using libtheora. * * @author Samuel Mimram * @author Romain Beauxis *) (** {2 Exceptions} *) (** General failure. *) exception Internal_error (** Library encountered invalid internal data. *) exception Invalid_data (** An unhandled error happened. *) exception Unknown_error of int (** The decoded packet represented a dropped frame. * The player can continue to display the current frame, * as the contents of the decoded frame buffer have not * changed. *) exception Duplicate_frame (** Exceptions used by the decoding module. *) exception Done exception Not_initialized (** {2 General functions} *) (** * Human-readable string to identify the encoder vendor and version. *) val version_string : string (** major, minor and sub version numbers of the encoder. *) val version_number : int * int * int (** Determines whether a theora packet is a key frame or not. * * raises [Invalid_data] if The packet is not a video data * packet. *) val is_keyframe : Ogg.Stream.packet -> bool (** {2 Types and datastructures} *) (** A Colorspace. *) type colorspace = | CS_unspecified (** The colorspace is unknown or unspecified *) | CS_ITU_REC_470M (** This is the best option for 'NTSC' content *) | CS_ITU_REC_470BG (** This is the best option for 'PAL' content *) | CS_NSPACES (** This marks the end of the defined colorspaces *) (** * A Chroma subsampling * * These enumerate the available chroma subsampling options supported * by the theora format. See Section 4.4 of the specification for * exact definitions. *) type pixelformat = | PF_420 (** Chroma subsampling by 2 in each direction (4:2:0) *) | PF_reserved (** Reserved value *) | PF_422 (** Horizonatal chroma subsampling by 2 (4:2:2) *) | PF_444 (** No chroma subsampling at all (4:4:4) *) (** Theora bitstream info. *) type info = { frame_width : int; (** The encoded frame width. *) frame_height : int; (** The encoded frame height. *) picture_width : int; (** The displayed picture width. *) picture_height : int; (** The displayed picture height. *) picture_x : int; (** The X offset of the displayed picture. *) picture_y : int; (** The Y offset of the displayed picture. *) colorspace : colorspace; (** The color space. *) pixel_fmt : pixelformat; (** The pixel format. *) target_bitrate : int; (** The target bit-rate in bits per second. *) quality : int; (** The target quality level. *) keyframe_granule_shift : int; (** The amount to shift to extract the last keyframe number from the granule position. *) version_major : int; version_minor : int; version_subminor : int; fps_numerator : int; fps_denominator : int; aspect_numerator : int; aspect_denominator : int; } val default_granule_shift : int type data_buffer = (int, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t (** * A YUV buffer for passing uncompressed frames to and from the codec. * This holds a Y'CbCr frame in planar format. The CbCr planes can be * subsampled and have their own separate dimensions and row stride * offsets. Note that the strides may be negative in some * configurations. For theora the width and height of the largest plane * must be a multiple of 16. The actual meaningful picture size and * offset are stored in the [info] structure; frames returned by * the decoder may need to be cropped for display. * * All samples are 8 bits. Within each plane samples are ordered by * row from the top of the frame to the bottom. Within each row samples * are ordered from left to right. *) type yuv_buffer = { y_width : int; y_height : int; y_stride : int; y : data_buffer; u_width : int; u_height : int; u_stride : int; u : data_buffer; v_width : int; v_height : int; v_stride : int; v : data_buffer; } (** {2 Encoding} *) module Encoder : sig type t type settings = { keyframe_frequency : int option; vp3_compatible : bool option; soft_target : bool option; buffer_delay : int option; speed : int option; } (** Initialize a [state] handle for decoding. *) val create : info -> settings -> (string * string) list -> t (** * Fills the given stream with the header packets. *) val encode_header : t -> Ogg.Stream.stream -> unit (** * Encode data until a page is filled. *) val encode_page : t -> Ogg.Stream.stream -> (unit -> yuv_buffer) -> Ogg.Page.t (** Encode a buffer. *) val encode_buffer : t -> Ogg.Stream.stream -> yuv_buffer -> unit (** Convert a granulepos to an absolute frame index, starting at 0. * The granulepos is interpreted in the context of a given theora_state handle. *) val frames_of_granulepos : t -> Int64.t -> Int64.t (** Set end of stream *) val eos : t -> Ogg.Stream.stream -> unit end module Decoder : sig (** Type for an uninitialized decoder. *) type decoder (** Type for an initialized decoder. *) type t (** * Check wether an ogg logical stream contains theora data * * This function shall be called just after you put * the first page in the stream. See examples/thdecode.ml * * Raises [Ogg.Bad_data] if the stream does not contain theora data. *) val check : Ogg.Stream.packet -> bool (** Initialize the decoding structure. * The decoder should then be processed with [headerin]. *) val create : unit -> decoder (** Add one packet from the stream and try to parse theora headers. * * Returns an initialized decoder. * * Raises [Ogg.Not_enough_data] is decoding header needs another packet. * * This function should be called with the first packets of the stream * until it returns the requested values. It may consume at most 5 packets * (3 header packet, 1 additional packet and the initial video packet) *) val headerin : decoder -> Ogg.Stream.packet -> t * info * string * (string * string) list (** * Output the next available frame of decoded YUV data. * * Raises [Ogg.Not_enough_data] if the Ogg.Stream.stream which * has been used to initialize the handler does not contain * enought data. You should submit a new page to it, and * run this function again until it returns. * * Raises [Not_initialized] if the decoder was not properly * initialized with [headerin]. *) val get_yuv : t -> Ogg.Stream.stream -> yuv_buffer (** Convert a granulepos to an absolute frame index, starting at 0. * The granulepos is interpreted in the context of a given theora_state handle. *) val frames_of_granulepos : t -> Int64.t -> Int64.t end module Skeleton : sig (** Generate a theora 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","video/theora"] * * See: http://xiph.org/ogg/doc/skeleton.html. *) val fisbone : ?start_granule:Int64.t -> ?headers:(string * string) list -> serialno:Nativeint.t -> info:info -> unit -> Ogg.Stream.packet end ocaml-theora-0.4.0/src/theora_decoder.ml000066400000000000000000000055741402143302000201560ustar00rootroot00000000000000(* * Copyright 2007-2011 Savonet team * * This file is part of ocaml-theora. * * ocaml-theora 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-theora 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-theora; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) let check = Theora.Decoder.check let decoder os = let decoder = Theora.Decoder.create () in let data = ref None in let latest_yuv = ref None in let os = ref os in let init () = match !data with | Some (dec, info, m) -> (dec, info, m) | None -> let packet = Ogg.Stream.get_packet !os in let decoder, info, vendor, m = Theora.Decoder.headerin decoder packet in let meta = (vendor, m) in data := Some (decoder, info, meta); (decoder, info, meta) in let decode feed = let decoder, info, _ = init () in let ret = try let yuv = Theora.Decoder.get_yuv decoder !os in latest_yuv := Some yuv; yuv with Theora.Duplicate_frame -> ( match !latest_yuv with | Some yuv -> yuv | None -> raise Theora.Internal_error) in let format = match info.Theora.pixel_fmt with | Theora.PF_420 -> Ogg_decoder.Yuvj_420 | Theora.PF_reserved -> assert false | Theora.PF_422 -> Ogg_decoder.Yuvj_422 | Theora.PF_444 -> Ogg_decoder.Yuvj_444 in let ret = { Ogg_decoder.format; frame_width = info.Theora.frame_width; frame_height = info.Theora.frame_height; y_stride = ret.Theora.y_stride; uv_stride = ret.Theora.u_stride; y = ret.Theora.y; u = ret.Theora.u; v = ret.Theora.v; } in feed ret in let info () = let _, info, m = init () in ( { Ogg_decoder.fps_numerator = info.Theora.fps_numerator; fps_denominator = info.Theora.fps_denominator; width = info.Theora.frame_width; height = info.Theora.frame_height; }, m ) in let restart new_os = os := new_os in let samples_of_granulepos pos = let decoder, _, _ = init () in Theora.Decoder.frames_of_granulepos decoder pos in Ogg_decoder.Video { Ogg_decoder.name = "theora"; info; decode; restart; samples_of_granulepos; } let register () = Hashtbl.add Ogg_decoder.ogg_decoders "theora" (check, decoder) ocaml-theora-0.4.0/src/theora_decoder.mli000066400000000000000000000016511402143302000203170ustar00rootroot00000000000000(* * Copyright 2007-2011 Savonet team * * This file is part of ocaml-theora. * * ocaml-theora 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-theora 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-theora; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** Implementation of the theora decoder * for the [Ogg_demuxer] module. *) (** Register the decoder. *) val register : unit -> unit ocaml-theora-0.4.0/src/theora_stubs.c000066400000000000000000000477711402143302000175300ustar00rootroot00000000000000/* * Copyright 2007-2009 Samuel Mimram and Romain Beauxis * * This file is part of ocaml-theora. * * ocaml-theora 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-theora 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-theora; 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 #ifndef Bytes_val #define Byles_val String_val #endif /***** Error handling ******/ static void check_err(int n) { switch (n) { case 0: return; case TH_EFAULT: caml_raise_constant(*caml_named_value("theora_exn_fault")); /* TODO: finer-grained exc raising. */ case TH_EINVAL: case TH_EVERSION: case TH_EBADPACKET: case TH_ENOTFORMAT: case TH_EBADHEADER: case TH_EIMPL: caml_raise_constant(*caml_named_value("theora_exn_inval")); case TH_DUPFRAME: caml_raise_constant(*caml_named_value("theora_exn_dup_frame")); default: caml_raise_with_arg(*caml_named_value("theora_exn_unknown"), Val_int(n)); } } /***** Version *****/ CAMLprim value ocaml_theora_version_string(value unit) { return caml_copy_string(th_version_string()); } CAMLprim value ocaml_theora_version_number(value unit) { return Val_int(th_version_number()); } /***** Helper functions *****/ static th_colorspace cs_of_val(value v) { switch (Int_val(v)) { case 0: return TH_CS_UNSPECIFIED; case 1: return TH_CS_ITU_REC_470M; case 2: return TH_CS_ITU_REC_470BG; case 3: return TH_CS_NSPACES; default: assert(0); } } static value val_of_cs(th_colorspace c) { switch (c) { case TH_CS_UNSPECIFIED: return Int_val(0); case TH_CS_ITU_REC_470M: return Int_val(1); case TH_CS_ITU_REC_470BG: return Int_val(2); case TH_CS_NSPACES: return Int_val(3); default: assert(0); } } static th_pixel_fmt pf_of_val(value v) { switch (Int_val(v)) { case 0: return TH_PF_420; case 1: return TH_PF_RSVD; case 2: return TH_PF_422; case 3: return TH_PF_444; default: assert(0); } } static value val_of_pf(th_pixel_fmt p) { switch (p) { case TH_PF_420: return Int_val(0); case TH_PF_RSVD: return Int_val(1); case TH_PF_422: return Int_val(2); case TH_PF_444: return Int_val(3); default: assert(0); } } /* ti is *not* allocated: codec_setup may be allocated by * theora_info_init and its memory lost. You better check what you need */ static th_info *info_of_val(value v, th_info *ti) { int i = 0; ti->frame_width = Int_val(Field(v, i++)); ti->frame_height = Int_val(Field(v, i++)); ti->pic_width = Int_val(Field(v, i++)); ti->pic_height = Int_val(Field(v, i++)); ti->pic_x = Int_val(Field(v, i++)); ti->pic_y = Int_val(Field(v, i++)); ti->colorspace = cs_of_val(Field(v, i++)); ti->pixel_fmt = pf_of_val(Field(v, i++)); ti->target_bitrate = Int_val(Field(v, i++)); ti->quality = Int_val(Field(v, i++)); ti->keyframe_granule_shift = Int_val(Field(v, i++)); ti->version_major = Int_val(Field(v, i++)); ti->version_minor = Int_val(Field(v, i++)); ti->version_subminor = Int_val(Field(v, i++)); ti->fps_numerator = Int_val(Field(v, i++)); ti->fps_denominator = Int_val(Field(v, i++)); ti->aspect_numerator = Int_val(Field(v, i++)); ti->aspect_denominator = Int_val(Field(v, i++)); return ti; } static value val_of_info(th_info *ti) { CAMLparam0(); CAMLlocal1(v); int i = 0; v = caml_alloc_tuple(18); Store_field(v, i++, Val_int(ti->frame_width)); Store_field(v, i++, Val_int(ti->frame_height)); Store_field(v, i++, Val_int(ti->pic_width)); Store_field(v, i++, Val_int(ti->pic_height)); Store_field(v, i++, Val_int(ti->pic_x)); Store_field(v, i++, Val_int(ti->pic_y)); Store_field(v, i++, val_of_cs(ti->colorspace)); Store_field(v, i++, val_of_pf(ti->pixel_fmt)); Store_field(v, i++, Val_int(ti->target_bitrate)); Store_field(v, i++, Val_int(ti->quality)); Store_field(v, i++, Val_int(ti->keyframe_granule_shift)); Store_field(v, i++, Val_int(ti->version_major)); Store_field(v, i++, Val_int(ti->version_minor)); Store_field(v, i++, Val_int(ti->version_subminor)); Store_field(v, i++, Val_int(ti->fps_numerator)); Store_field(v, i++, Val_int(ti->fps_denominator)); Store_field(v, i++, Val_int(ti->aspect_numerator)); Store_field(v, i++, Val_int(ti->aspect_denominator)); CAMLreturn(v); } static void yuv_of_val(value v, th_ycbcr_buffer buffer) { int i = 0; struct caml_ba_array *ba; /* Y plane */ buffer[0].width = Int_val(Field(v, i++)); buffer[0].height = Int_val(Field(v, i++)); buffer[0].stride = Int_val(Field(v, i++)); ba = Caml_ba_array_val(Field(v, i++)); if (ba->dim[0] != buffer[0].stride * buffer[0].height) caml_raise_constant(*caml_named_value("theora_exn_inval")); buffer[0].data = (unsigned char *)ba->data; /* Cb plane */ buffer[1].width = Int_val(Field(v, i++)); buffer[1].height = Int_val(Field(v, i++)); buffer[1].stride = Int_val(Field(v, i++)); ba = Caml_ba_array_val(Field(v, i++)); if (ba->dim[0] != buffer[1].stride * buffer[1].height) caml_raise_constant(*caml_named_value("theora_exn_inval")); buffer[1].data = (unsigned char *)ba->data; /* Cr plane */ buffer[2].width = Int_val(Field(v, i++)); buffer[2].height = Int_val(Field(v, i++)); buffer[2].stride = Int_val(Field(v, i++)); ba = Caml_ba_array_val(Field(v, i++)); if (ba->dim[0] != buffer[2].stride * buffer[2].height) caml_raise_constant(*caml_named_value("theora_exn_inval")); buffer[2].data = (unsigned char *)ba->data; return; } /* The result must be freed afterwards! */ /* This should not be called in a blocking section. */ static value val_of_yuv(th_ycbcr_buffer buffer) { CAMLparam0(); CAMLlocal4(ret, y, u, v); int i = 0; intnat len; ret = caml_alloc_tuple(12); unsigned char *data; /* Y plane */ Store_field(ret, i++, Val_int(buffer[0].width)); Store_field(ret, i++, Val_int(buffer[0].height)); Store_field(ret, i++, Val_int(buffer[0].stride)); len = buffer[0].stride * buffer[0].height; y = caml_ba_alloc(CAML_BA_C_LAYOUT | CAML_BA_UINT8, 1, NULL, &len); data = Caml_ba_data_val(y); memcpy(data, buffer[0].data, len); Store_field(ret, i++, y); /* Cb plane */ Store_field(ret, i++, Val_int(buffer[1].width)); Store_field(ret, i++, Val_int(buffer[1].height)); Store_field(ret, i++, Val_int(buffer[1].stride)); len = buffer[1].stride * buffer[1].height; u = caml_ba_alloc(CAML_BA_C_LAYOUT | CAML_BA_UINT8, 1, NULL, &len); data = Caml_ba_data_val(u); memcpy(data, buffer[1].data, len); Store_field(ret, i++, u); /* Cr plane */ Store_field(ret, i++, Val_int(buffer[2].width)); Store_field(ret, i++, Val_int(buffer[2].height)); Store_field(ret, i++, Val_int(buffer[2].stride)); len = buffer[2].stride * buffer[2].height; v = caml_ba_alloc(CAML_BA_C_LAYOUT | CAML_BA_UINT8, 1, NULL, &len); data = Caml_ba_data_val(v); memcpy(data, buffer[2].data, len); Store_field(ret, i++, v); CAMLreturn(ret); } CAMLprim value ocaml_theora_default_granuleshift(value unit) { CAMLparam0(); th_info info; th_info_init(&info); int ret = info.keyframe_granule_shift; th_info_clear(&info); CAMLreturn(Int_val(ret)); } CAMLprim value ocaml_theora_ogg_packet_iskeyframe(value _op) { CAMLparam1(_op); ogg_packet *op = Packet_val(_op); CAMLreturn(Val_int(th_packet_iskeyframe(op))); } /** Encoding API **/ typedef struct enc_state_t { th_enc_ctx *ts; th_info ti; th_comment tc; ogg_int64_t granulepos; ogg_int64_t packetno; } enc_state_t; #define Theora_enc_state_val(v) (*((enc_state_t **)Data_custom_val(v))) static void finalize_enc_state(value s) { enc_state_t *state = Theora_enc_state_val(s); th_encode_free(state->ts); th_info_clear(&state->ti); th_comment_clear(&state->tc); free(state); } static struct custom_operations enc_state_ops = { "ocaml_enc_theora_state", finalize_enc_state, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; /* Thanks you * http://www.linux-nantes.org/~fmonnier/ocaml/ocaml-wrapping-c.php#ref_option */ #define Val_none Val_int(0) #define Some_val(v) Field(v, 0) CAMLprim value ocaml_theora_encode_init(value info, value params, value comments) { CAMLparam3(info, params, comments); CAMLlocal2(ans, c); enc_state_t *state = malloc(sizeof(enc_state_t)); th_info_init(&state->ti); info_of_val(info, &state->ti); th_comment_init(&state->tc); int i; for (i = 0; i < Wosize_val(comments); i++) th_comment_add_tag(&state->tc, (char *)Bytes_val(Field(Field(comments, i), 0)), (char *)Bytes_val(Field(Field(comments, i), 1))); state->ts = th_encode_alloc(&state->ti); if (state->ts == NULL) { th_info_clear(&state->ti); th_comment_clear(&state->tc); free(state); check_err(TH_EINVAL); } state->granulepos = 0; state->packetno = 0; /* Apply settings */ int j = 0; int v; c = Field(params, j++); if (c != Val_none) { v = Int_val(Some_val(c)); check_err(th_encode_ctl(state->ts, TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE, &v, sizeof(int))); } c = Field(params, j++); if (c != Val_none) { v = 0; if (Some_val(c) == Val_true) v = 1; check_err(th_encode_ctl(state->ts, TH_ENCCTL_SET_VP3_COMPATIBLE, &v, sizeof(int))); } c = Field(params, j++); if (c != Val_none) { if (Some_val(c) == Val_true) { v = TH_RATECTL_CAP_UNDERFLOW; check_err( th_encode_ctl(state->ts, TH_ENCCTL_SET_RATE_FLAGS, &v, sizeof(int))); } } c = Field(params, j++); if (c != Val_none) { v = Int_val(Some_val(c)); check_err( th_encode_ctl(state->ts, TH_ENCCTL_SET_RATE_BUFFER, &v, sizeof(int))); } c = Field(params, j++); if (c != Val_none) { v = Int_val(Some_val(c)); check_err(th_encode_ctl(state->ts, TH_ENCCTL_SET_SPLEVEL, &v, sizeof(int))); } ans = caml_alloc_custom(&enc_state_ops, sizeof(enc_state_t *), 1, 0); Theora_enc_state_val(ans) = state; CAMLreturn(ans); } CAMLprim value ocaml_theora_encoder_frame_of_granulepos(value t_state, value gpos) { CAMLparam2(t_state, gpos); enc_state_t *state = Theora_enc_state_val(t_state); CAMLreturn(caml_copy_int64(th_granule_frame(state->ts, Int64_val(gpos)))); } CAMLprim value ocaml_theora_encode_header(value t_state, value o_stream_state) { CAMLparam2(t_state, o_stream_state); enc_state_t *state = Theora_enc_state_val(t_state); ogg_stream_state *os = Stream_state_val(o_stream_state); ogg_packet op; int ret; ret = th_encode_flushheader(state->ts, &state->tc, &op); if (ret < 0) check_err(ret); if (ret == 0) CAMLreturn(Val_true); else { state->granulepos = op.granulepos; state->packetno = op.packetno; ogg_stream_packetin(os, &op); CAMLreturn(Val_false); } } CAMLprim value ocaml_theora_encode_buffer(value t_state, value o_stream_state, value frame) { CAMLparam3(t_state, o_stream_state, frame); CAMLlocal1(v); enc_state_t *state = Theora_enc_state_val(t_state); ogg_stream_state *os = Stream_state_val(o_stream_state); th_ycbcr_buffer yb; ogg_packet op; int ret = 1; if (ogg_stream_eos(os)) caml_raise_constant(*caml_named_value("theora_exn_end_of_file")); /* Encode the theora packet. */ yuv_of_val(frame, yb); caml_enter_blocking_section(); ret = th_encode_ycbcr_in(state->ts, yb); caml_leave_blocking_section(); if (ret != 0) /* TODO: * \retval OC_EINVAL Encoder is not ready, or is finished. * \retval -1 The size of the given frame differs from those previously * input */ check_err(ret); ret = 1; while (ret > 0) { ret = th_encode_packetout(state->ts, 0, &op); if (ret > 0) { state->granulepos = op.granulepos; state->packetno = op.packetno; ogg_stream_packetin(os, &op); } } if (ret < 0) check_err(ret); CAMLreturn(Val_unit); } CAMLprim value ocaml_theora_encode_eos(value t_state, value o_stream_state) { CAMLparam2(t_state, o_stream_state); enc_state_t *state = Theora_enc_state_val(t_state); ogg_stream_state *os = Stream_state_val(o_stream_state); ogg_packet op; int ret; ogg_int64_t iframe; ogg_int64_t pframe; /* TODO: a proper eos should be acheived using an empty ogg page with the * eos marker.. */ /* Try to grab a packet */ ret = th_encode_packetout(state->ts, 1, &op); if (ret <= 0) { check_err(ret); /* No packet was produced: we bake our own ! */ op.packet = (unsigned char *)NULL; op.bytes = 0; op.b_o_s = 0; op.e_o_s = 1; /* Set the granulepos as a new frame */ iframe = state->granulepos >> state->ti.keyframe_granule_shift; pframe = state->granulepos & ~iframe; op.granulepos = (iframe << state->ti.keyframe_granule_shift) | (pframe + 1); op.packetno = state->packetno + 1; } ogg_stream_packetin(os, &op); CAMLreturn(Val_unit); } /** Decoding API **/ typedef struct dec_state_t { th_dec_ctx *ts; th_info ti; th_comment tc; th_setup_info *tsi; int init; ogg_packet init_packet; } dec_state_t; #define Theora_dec_state_val(v) (*((dec_state_t **)Data_custom_val(v))) static void finalize_dec_state(value s) { dec_state_t *state = Theora_dec_state_val(s); if (state->ts != NULL) th_decode_free(state->ts); th_info_clear(&state->ti); th_comment_clear(&state->tc); if (state->tsi != NULL) th_setup_free(state->tsi); free(state); } static struct custom_operations dec_state_ops = { "ocaml_dec_theora_state", finalize_dec_state, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; CAMLprim value caml_theora_check(value packet) { CAMLparam1(packet); ogg_packet *op = Packet_val(packet); th_info ti; th_comment tc; th_setup_info *tsi = NULL; th_comment_init(&tc); th_info_init(&ti); int ret; ret = th_decode_headerin(&ti, &tc, &tsi, op); th_comment_clear(&tc); th_info_clear(&ti); if (tsi != NULL) th_setup_free(tsi); if (ret > 0) CAMLreturn(Val_true); else CAMLreturn(Val_false); } CAMLprim value ocaml_theora_create_dec(value unit) { CAMLparam0(); CAMLlocal1(ret); dec_state_t *state = malloc(sizeof(dec_state_t)); if (state == NULL) caml_raise_out_of_memory(); th_comment_init(&state->tc); th_info_init(&state->ti); state->ts = NULL; state->tsi = NULL; state->init_packet.packet = NULL; ret = caml_alloc_custom(&dec_state_ops, sizeof(dec_state_t *), 1, 0); Theora_dec_state_val(ret) = state; CAMLreturn(ret); } CAMLprim value ocaml_theora_dec_headerin(value decoder, value packet) { CAMLparam1(packet); CAMLlocal4(ret, t, comment, tmp); dec_state_t *state = Theora_dec_state_val(decoder); ogg_packet *op = Packet_val(packet); int v; v = th_decode_headerin(&state->ti, &state->tc, &state->tsi, op); if (v < 0) caml_raise_constant(*caml_named_value("theora_exn_inval")); if (v == 0) { /* Keep this packet for the first YUV decoding.. */ memcpy(&state->init_packet, op, sizeof(ogg_packet)); state->init = 1; comment = caml_alloc_tuple(state->tc.comments + 1); Store_field(comment, 0, caml_copy_string(state->tc.vendor)); if (state->tc.comments) { int i; int len; for (i = 0; i < state->tc.comments; i++) { if (state->tc.user_comments[i]) { len = state->tc.comment_lengths[i]; tmp = caml_alloc_string(len); memcpy(Bytes_val(tmp), state->tc.user_comments[i], len); Store_field(comment, i + 1, tmp); } } } state->ts = th_decode_alloc(&state->ti, state->tsi); ret = caml_alloc_tuple(2); Store_field(ret, 0, val_of_info(&state->ti)); Store_field(ret, 1, comment); CAMLreturn(ret); } else { caml_raise_constant(*caml_named_value("theora_exn_not_enough_data")); } } CAMLprim value ocaml_theora_decode_YUVout(value decoder, value _os) { CAMLparam2(decoder, _os); ogg_stream_state *os = Stream_state_val(_os); dec_state_t *state = Theora_dec_state_val(decoder); th_ycbcr_buffer yb; ogg_packet op; int ret; if (state->init != 1) { ret = ogg_stream_packetout(os, &op); if (ret == 0) 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")); /* TODO: use the third argument (granulepos of the decoded packet) */ check_err(th_decode_packetin(state->ts, &op, NULL)); } else { check_err(th_decode_packetin(state->ts, &state->init_packet, NULL)); state->init = 0; } caml_enter_blocking_section(); th_decode_ycbcr_out(state->ts, yb); caml_leave_blocking_section(); CAMLreturn(val_of_yuv(yb)); } CAMLprim value ocaml_theora_decoder_frame_of_granulepos(value t_state, value gpos) { CAMLparam2(t_state, gpos); dec_state_t *state = Theora_dec_state_val(t_state); CAMLreturn(caml_copy_int64(th_granule_frame(state->ts, Int64_val(gpos)))); } /* 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_theora_skeleton_fisbone(value serial, value info, value start, value content) { CAMLparam4(serial, info, start, content); CAMLlocal1(packet); ogg_packet op; th_info ti; info_of_val(info, &ti); 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 theora video */ 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 theora stream */ write32le(op.packet + 16, 3); /* number of header packets */ /* granulerate, temporal resolution of the bitstream in samples/microsecond */ write64le(op.packet + 20, (ogg_int64_t)ti.fps_numerator); /* granulrate numerator */ write64le(op.packet + 28, (ogg_int64_t)ti.fps_denominator); /* granulrate denominator */ write64le(op.packet + 36, (ogg_int64_t)Int64_val(start)); /* start granule */ write32le(op.packet + 44, 0); /* preroll, for theora its 0 */ *(op.packet + 48) = ti.keyframe_granule_shift; /* granule shift */ memcpy(op.packet + FISBONE_SIZE, String_val(content), caml_string_length(content)); /* message header field */ op.b_o_s = 0; op.e_o_s = 0; op.bytes = len; packet = value_of_packet(&op); free(op.packet); CAMLreturn(packet); } ocaml-theora-0.4.0/theora.opam000066400000000000000000000013541402143302000162160ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.4.0" synopsis: "Bindings to libtheora" maintainer: ["The Savonet Team "] authors: ["The Savonet Team "] license: "GPL-2.0" homepage: "https://github.com/savonet/ocaml-theora" bug-reports: "https://github.com/savonet/ocaml-theora/issues" depends: [ "conf-libtheora" "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-theora.git"