pax_global_header00006660000000000000000000000064137512704170014521gustar00rootroot0000000000000052 comment=c3e2e68d26d0dc8a4d854fb41cfbf1a96a5f7122 ocaml-gstreamer-0.3.1/000077500000000000000000000000001375127041700146045ustar00rootroot00000000000000ocaml-gstreamer-0.3.1/.github/000077500000000000000000000000001375127041700161445ustar00rootroot00000000000000ocaml-gstreamer-0.3.1/.github/workflows/000077500000000000000000000000001375127041700202015ustar00rootroot00000000000000ocaml-gstreamer-0.3.1/.github/workflows/ci.yml000066400000000000000000000011031375127041700213120ustar00rootroot00000000000000name: CI on: [push] jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-20.04, macos-latest] steps: - uses: actions/checkout@v1 - name: Setup OCaml uses: avsm/setup-ocaml@v1.0 - name: Install depext module run: opam install -y depext - name: Pin locally run: opam pin -y add --no-action . - name: Install locally run: opam depext -y -i gstreamer - name: Build locally run: eval $(opam env) && dune build - name: Run tests locally run: eval $(opam env) && dune runtest ocaml-gstreamer-0.3.1/.gitignore000066400000000000000000000000631375127041700165730ustar00rootroot00000000000000*~ _build *.byte *.native _tests .merlin *.install ocaml-gstreamer-0.3.1/.ocamlformat000066400000000000000000000003201375127041700171040ustar00rootroot00000000000000profile = 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-gstreamer-0.3.1/CHANGES000066400000000000000000000014421375127041700156000ustar00rootroot000000000000000.3.1 (2020-11-06) ===== * Correctly raise errors in pipeline_parse_launch. * `Buffer`: add `of_data_list`, `to_data` and `to_string`. * `App_sink`: add `pull_buffer`. * Switched to dune. 0.3.0 (2018-09-09) ===== * Add smarter buffer API to avoid copies. * Add main loop API * Cleanup C thread management. * Cleanup gst_buf management. * Record app{sink,src}->element dependency for proper GC cleanup. 0.2.3 (2017-04-11) ===== * Added timeout to Bus.timed_pop_filtered. * Added datetime tag support. 0.2.2 (2016-06-29) ===== * Added Element.duration. * Added App_src.push_buffer_data. * Completed message types. 0.2.1 (2015-08-03) ===== * Dummy github release. 0.2.0 (2013-02-19) ===== * Complete rewrite to get rid of OCamlIDL, lots of modules added. 0.1.0 (2011-10-04) ===== * Initial release. ocaml-gstreamer-0.3.1/COPYING000066400000000000000000000634761375127041700156570ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 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. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. 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 Library or any portion of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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 Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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. 9. 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. 11. 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. 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. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; 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. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ocaml-gstreamer-0.3.1/README.md000066400000000000000000000013351375127041700160650ustar00rootroot00000000000000ocaml-gstreamer ========== ocaml-gstreamer is an OCaml interface for the GStreamer Multimedia framework. Prerequisites ------------- - ocaml >= 4.02.0 - gstreamer >= 1.0.0 - findlib - dune >= 2.0 Compilation ----------- ```sh dune build ``` This should build both the native and the byte-code version of the extension library. Installation ------------ Via `opam`: ```sh opam install gstreamer ``` Via `dune` (for developers): ```sh dune install ``` This should install the library file (using ocamlfind) in the appropriate place. License ------- Please see the COPYING file. Author ------ This author of this software may be contacted by electronic mail at the following address: savonet-users@lists.sourceforge.net. ocaml-gstreamer-0.3.1/dune-project000066400000000000000000000007631375127041700171340ustar00rootroot00000000000000(lang dune 2.0) (version 0.3.1) (name gstreamer) (source (github savonet/ocaml-gstreamer)) (license LGPL-2.1) (authors "The Savonet Team ") (maintainers "The Savonet Team ") (generate_opam_files true) (package (name gstreamer) (synopsis "Bindings for the GStreamer library which provides functions for playning and manipulating multimedia streams") (depends (ocaml (>= 4.02.0)) (dune (> 2.0)) dune-configurator) ) ocaml-gstreamer-0.3.1/examples/000077500000000000000000000000001375127041700164225ustar00rootroot00000000000000ocaml-gstreamer-0.3.1/examples/appsink.ml000066400000000000000000000037421375127041700204270ustar00rootroot00000000000000open Gstreamer let () = init (); Printf.printf "%s\n\n%!" (version_string ()); let uri = "http://radiopi.org:8080/hiphop" in let read_pipeline = Printf.sprintf "uridecodebin uri=\"%s\" ! decodebin ! audioconvert ! audioresample ! \ appsink max-buffers=10 drop=false sync=false name=\"sink\" \ caps=\"audio/x-raw,format=S16LE,layout=interleaved,channels=2,rate=44100\"" uri in Printf.printf "read_pipeline:\n %s\n\n%!" read_pipeline; let read_bin = Pipeline.parse_launch read_pipeline in let sink = Bin.get_by_name read_bin "sink" in let sink = App_sink.of_element sink in let play_pipeline = "appsrc name=\"src\" block=true \ caps=\"audio/x-raw,format=S16LE,layout=interleaved,channels=2,rate=44100\" \ format=time ! autoaudiosink" in Printf.printf "play_pipeline:\n %s\n\n%!" play_pipeline; let play_bin = Pipeline.parse_launch play_pipeline in let src = Bin.get_by_name play_bin "src" in let src = App_src.of_element src in ignore (Element.set_state play_bin Element.State_playing); ignore (Element.set_state read_bin Element.State_playing); Printf.printf "from App_sink.pull_buffer_data to App_src.push_buffer\n%!"; for _ = 0 to 100 do let buf = App_sink.pull_buffer_data sink in let buf = Buffer.of_data buf 0 (Bigarray.Array1.dim buf) in App_src.push_buffer src buf done; Printf.printf "from App_sink.pull_buffer_string to App_src.push_buffer\n%!"; for _ = 0 to 100 do let buf = App_sink.pull_buffer_string sink in let buf = Buffer.of_string buf 0 (String.length buf) in App_src.push_buffer src buf done; Printf.printf "from App_sink.pull_buffer_data to App_src.push_buffer_data\n%!"; for _ = 0 to 100 do let buf = App_sink.pull_buffer_data sink in App_src.push_buffer_data src buf 0 (Bigarray.Array1.dim buf) done; ignore (Element.set_state read_bin Element.State_null); ignore (Element.set_state play_bin Element.State_null); Gstreamer.deinit (); Gc.full_major () ocaml-gstreamer-0.3.1/examples/caps.ml000066400000000000000000000010651375127041700177040ustar00rootroot00000000000000open Gstreamer let () = Gstreamer.init (); let pipeline = Printf.sprintf "filesrc location=\"%s\" ! typefind name=typefinder ! fakesink" Sys.argv.(1) in let bin = Pipeline.parse_launch pipeline in let tf = Type_find_element.of_element (Gstreamer.Bin.get_by_name bin "typefinder") in let cb proba caps = Printf.printf "Found caps (%d%%):\n%s\n%!" proba (Gstreamer.Caps.to_string caps) in Type_find_element.on_have_type tf cb; ignore (Element.set_state bin Element.State_playing); Unix.sleep 1; Gc.full_major () ocaml-gstreamer-0.3.1/examples/dune000066400000000000000000000010551375127041700173010ustar00rootroot00000000000000(executable (name appsink) (modules appsink) (libraries gstreamer)) (executable (name playlist) (modules playlist) (libraries gstreamer)) (executable (name player) (modules player) (libraries gstreamer)) (executable (name caps) (modules caps) (libraries gstreamer)) (executable (name tags) (modules tags) (libraries gstreamer)) (executable (name sine) (modules sine) (libraries gstreamer)) (executable (name duration) (modules duration) (libraries gstreamer)) (executable (name webrtc) (modules webrtc) (libraries gstreamer)) ocaml-gstreamer-0.3.1/examples/duration.ml000066400000000000000000000025631375127041700206070ustar00rootroot00000000000000open Gstreamer let timeToString nsd = let msd = Int64.(to_int (div nsd (of_int 1_000_000))) in let h = msd / 3_600_000 in let m = (msd - (h * 3_600_000)) / 60_000 in let s = (msd - (h * 3_600_000) - (m * 60_000)) / 1000 in let h = if h = 0 then "" else Printf.sprintf "%d:" h in Printf.sprintf "%s%d:%d" h m s let printProgression bin = let duration = Element.duration bin Format.Time |> timeToString in let rec loop () = let position = Element.position bin Format.Time |> timeToString in Printf.printf "Time : %s / %s \r%!" position duration; (* Refreshing the position every seconds (in nanoseconds) *) let timeout = Int64.of_int 1_000_000_000 in let filter = [`End_of_stream; `Error] in match Bus.timed_pop_filtered (Bus.of_element bin) ~timeout filter with | exception Timeout -> loop () | _ -> Printf.printf "\n" in loop () let () = Gstreamer.init (); let formatPipeline = Printf.sprintf "filesrc location=\"%s\" ! decodebin ! audioconvert ! audioresample ! \ autoaudiosink" in let bin = formatPipeline Sys.argv.(1) |> Pipeline.parse_launch in Element.set_state bin Element.State_playing |> ignore; (* Wait for the state to complete. *) Element.get_state bin |> ignore; printProgression bin; Element.set_state bin Element.State_null |> ignore; Gstreamer.deinit (); Gc.full_major () ocaml-gstreamer-0.3.1/examples/player.ml000066400000000000000000000016761375127041700202620ustar00rootroot00000000000000open Gstreamer let () = init (); Printf.printf "%s\n%!" (version_string ()); let bin = Pipeline.create "pipeline" in let filesrc = Element_factory.make "filesrc" "disk_source" in if Array.length Sys.argv < 2 then ( Printf.eprintf "Please provide an mp3 file as first argument.\n%!"; exit 1 ); Element.set_property_string filesrc "location" Sys.argv.(1); let decoder = Element_factory.make "mad" "decode" in let conv = Element_factory.make "audioconvert" "audioconvert" in let resample = Element_factory.make "audioresample" "audioresample" in let audiosink = Element_factory.make "pulsesink" "play_audio" in Bin.add_many (Bin.of_element bin) [filesrc; decoder; conv; resample; audiosink]; Element.link_many [filesrc; decoder; conv; resample; audiosink]; ignore (Element.set_state bin Element.State_playing); Unix.sleep 5; ignore (Element.set_state bin Element.State_null); Gstreamer.deinit (); Gc.full_major () ocaml-gstreamer-0.3.1/examples/playlist.ml000066400000000000000000000011251375127041700206140ustar00rootroot00000000000000open Gstreamer let () = Gstreamer.init (); if Array.length Sys.argv < 2 then ( Printf.eprintf "Please provide some files as arguments.\n%!"; exit 1 ); let bin = Element_factory.make "playbin" "play" in let play fileName = Element.set_property_string bin "uri" ("file://" ^ fileName); Element.set_state bin Element.State_playing |> ignore; Bus.timed_pop_filtered (Bus.of_element bin) [`End_of_stream] |> ignore; Element.set_state bin Element.State_null |> ignore in Array.to_list Sys.argv |> List.tl |> List.iter play; Gstreamer.deinit (); Gc.full_major () ocaml-gstreamer-0.3.1/examples/sine.ml000066400000000000000000000005501375127041700177120ustar00rootroot00000000000000open Gstreamer let () = init (); Printf.printf "%s\n%!" (version_string ()); let bin = Pipeline.parse_launch "audiotestsrc ! audioconvert ! audioresample ! autoaudiosink" in ignore (Element.set_state bin Element.State_playing); Unix.sleep 5; ignore (Element.set_state bin Element.State_null); Gstreamer.deinit (); Gc.full_major () ocaml-gstreamer-0.3.1/examples/tags.ml000066400000000000000000000017651375127041700177230ustar00rootroot00000000000000open Gstreamer let () = Gstreamer.init (); if Array.length Sys.argv < 2 then ( Printf.eprintf "Please provide a file as first argument.\n%!"; exit 1 ); let pipeline = Printf.sprintf "filesrc location=\"%s\" ! decodebin ! fakesink" Sys.argv.(1) in let bin = Pipeline.parse_launch pipeline in (* Go in paused state. *) ignore (Element.set_state bin Element.State_paused); (* Wait for the state to complete. *) ignore (Element.get_state bin); try while true do let msg = Bus.pop_filtered (Bus.of_element bin) [`Error; `Tag; `Async_done] in let msg = match msg with Some msg -> msg | None -> raise Exit in Printf.printf "Message from %s\n%!" msg.source; match msg.payload with | `Error e -> failwith ("Error message: " ^ e) | `Tag tags -> List.iter (fun (l, v) -> Printf.printf "- %s : %s\n%!" l (String.concat ", " v)) tags | _ -> () done with Exit -> () ocaml-gstreamer-0.3.1/examples/webrtc.ml000066400000000000000000000010601375127041700202370ustar00rootroot00000000000000(* Adapted from http://blog.nirbheek.in/2018/02/gstreamer-webrtc.html *) open Gstreamer let () = init (); Printf.printf "%s\n%!" (version_string ()); let bin = Pipeline.parse_launch "v4l2src ! queue ! vp8enc ! rtpvp8pay ! \ application/x-rtp,media=video,encoding-name=VP8,payload=96 ! webrtcbin \ name=sendrecv" in let _ = Bin.get_by_name bin "sendrecv" in ignore (Element.set_state bin Element.State_playing); Unix.sleep 5; ignore (Element.set_state bin Element.State_null); Gstreamer.deinit (); Gc.full_major () ocaml-gstreamer-0.3.1/gstreamer.opam000066400000000000000000000026601375127041700174570ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.3.1" synopsis: "Bindings for the GStreamer library which provides functions for playning and manipulating multimedia streams" maintainer: ["The Savonet Team "] authors: ["The Savonet Team "] license: "LGPL-2.1" homepage: "https://github.com/savonet/ocaml-gstreamer" bug-reports: "https://github.com/savonet/ocaml-gstreamer/issues" depends: [ "ocaml" {>= "4.02.0"} "dune" {> "2.0"} "dune-configurator" ] 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-gstreamer.git" depexts: [ ["gstreamer-dev" "gst-plugins-base-dev"] {os-distribution = "alpine"} ["gstreamer-devel" "gstreamer-plugins-base-devel"] {os-family = "suse"} ["gstreamer1-devel" "gstreamer1-plugins-base-devel"] {os-distribution = "fedora"} ["gstreamer1-devel" "gstreamer1-plugins-base-devel"] {os-distribution = "centos"} ["libgstreamer1.0-dev" "libgstreamer-plugins-base1.0-dev"] {os-distribution = "debian"} ["libgstreamer1.0-dev" "libgstreamer-plugins-base1.0-dev"] {os-distribution = "ubuntu"} ["gstreamer1"] {os = "freebsd"} ["gstreamer" "gst-plugins-base"] {os = "macos" & os-distribution = "homebrew"} ] ocaml-gstreamer-0.3.1/gstreamer.opam.template000066400000000000000000000012061375127041700212640ustar00rootroot00000000000000depexts: [ ["gstreamer-dev" "gst-plugins-base-dev"] {os-distribution = "alpine"} ["gstreamer-devel" "gstreamer-plugins-base-devel"] {os-family = "suse"} ["gstreamer1-devel" "gstreamer1-plugins-base-devel"] {os-distribution = "fedora"} ["gstreamer1-devel" "gstreamer1-plugins-base-devel"] {os-distribution = "centos"} ["libgstreamer1.0-dev" "libgstreamer-plugins-base1.0-dev"] {os-distribution = "debian"} ["libgstreamer1.0-dev" "libgstreamer-plugins-base1.0-dev"] {os-distribution = "ubuntu"} ["gstreamer1"] {os = "freebsd"} ["gstreamer" "gst-plugins-base"] {os = "macos" & os-distribution = "homebrew"} ] ocaml-gstreamer-0.3.1/src/000077500000000000000000000000001375127041700153735ustar00rootroot00000000000000ocaml-gstreamer-0.3.1/src/config/000077500000000000000000000000001375127041700166405ustar00rootroot00000000000000ocaml-gstreamer-0.3.1/src/config/discover.ml000066400000000000000000000013621375127041700210120ustar00rootroot00000000000000module C = Configurator.V1 let () = C.main ~name:"gstreamer-pkg-config" (fun c -> let default : C.Pkg_config.package_conf = { libs = [ "-lgstapp-1.0 -lgstbase-1.0 -lgstreamer-1.0 -lgobject-2.0 \ -lglib-2.0"; ]; cflags = []; } in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> ( match C.Pkg_config.query pc ~package:"gstreamer-1.0 gstreamer-app-1.0" 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-gstreamer-0.3.1/src/config/dune000066400000000000000000000000751375127041700175200ustar00rootroot00000000000000(executable (name discover) (libraries dune.configurator)) ocaml-gstreamer-0.3.1/src/dune000066400000000000000000000005451375127041700162550ustar00rootroot00000000000000(library (name gstreamer) (public_name gstreamer) (synopsis "OCaml bindings to gstreamer") (libraries threads) (foreign_stubs (language c) (names gstreamer_stubs) (flags (:include c_flags.sexp))) (c_library_flags (:include c_library_flags.sexp))) (rule (targets c_flags.sexp c_library_flags.sexp) (action (run ./config/discover.exe))) ocaml-gstreamer-0.3.1/src/gstreamer.ml000066400000000000000000000321741375127041700177250ustar00rootroot00000000000000exception Error of string exception Stopped exception Timeout exception Failed exception End_of_stream let () = Callback.register_exception "gstreamer_exn_error" (Error ""); Callback.register_exception "gstreamer_exn_stopped" Stopped; Callback.register_exception "gstreamer_exn_timeout" Timeout; Callback.register_exception "gstreamer_exn_failed" Failed; Callback.register_exception "gstreamer_exn_eos" End_of_stream external init : string array option -> unit = "ocaml_gstreamer_init" let init ?argv () = init argv external deinit : unit -> unit = "ocaml_gstreamer_deinit" external version : unit -> int * int * int * int = "ocaml_gstreamer_version" external version_string : unit -> string = "ocaml_gstreamer_version_string" type data = (int, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t module Format = struct type t = Undefined | Default | Bytes | Time | Buffers | Percent external to_string : t -> string = "ocaml_gstreamer_format_to_string" end module Event = struct type seek_flag = | Seek_flag_none | Seek_flag_flush | Seek_flag_accurate | Seek_flag_key_unit | Seek_flag_segment | Seek_flag_skip | Seek_flag_snap_before | Seek_flag_snap_after | Seek_flag_snap_nearest end module Element = struct type t external set_property_string : t -> string -> string -> unit = "ocaml_gstreamer_element_set_property_string" external set_property_int : t -> string -> string -> unit = "ocaml_gstreamer_element_set_property_int" external set_property_bool : t -> string -> string -> unit = "ocaml_gstreamer_element_set_property_bool" type state = | State_void_pending | State_null | State_ready | State_paused | State_playing external string_of_state : state -> string = "ocaml_gstreamer_element_string_of_state" type state_change = | State_change_success | State_change_async | State_change_no_preroll external set_state : t -> state -> state_change = "ocaml_gstreamer_element_set_state" external get_state : t -> state_change * state * state = "ocaml_gstreamer_element_get_state" external link : t -> t -> unit = "ocaml_gstreamer_element_link" let link_many ee = let e, ee = (List.hd ee, List.tl ee) in ignore (List.fold_left (fun e e' -> link e e'; e') e ee) external position : t -> Format.t -> Int64.t = "ocaml_gstreamer_element_position" external duration : t -> Format.t -> Int64.t = "ocaml_gstreamer_element_duration" external seek_simple : t -> Format.t -> Event.seek_flag array -> Int64.t -> unit = "ocaml_gstreamer_element_seek_simple" let seek_simple e fmt flags n = seek_simple e fmt (Array.of_list flags) n end module Element_factory = struct type t = Element.t external make : string -> string -> t = "ocaml_gstreamer_element_factory_make" end module Message = struct type message_type = | Unknown | End_of_stream | Error | Warning | Info | Tag | Buffering | State_changed | State_dirty | Step_done | Clock_provide | Clock_lost | New_clock | Structure_change | Stream_status | Application | Element | Segment_start | Segment_done | Duration_changed | Latency | Async_start | Async_done | Request_state | Step_start | Qos | Progress | Toc | Reset_time | Stream_start | Need_context | Have_context | Any type t type msg = [ `Unknown | `End_of_stream | `Error of string | `Warning of string | `Info of string | `Tag of (string * string list) list | `Buffering of int | `State_changed of Element.state * Element.state * Element.state | `State_dirty | `Step_done | `Clock_provide | `Clock_lost | `New_clock | `Structure_change | `Stream_status | `Application | `Element | `Segment_start | `Segment_done | `Duration_changed | `Latency | `Async_start | `Async_done | `Request_state | `Step_start | `Qos | `Progress | `Toc | `Reset_time | `Stream_start | `Need_context | `Have_context ] external message_type : t -> message_type = "ocaml_gstreamer_message_type" external source_name : t -> string = "ocaml_gstreamer_message_source_name" external parse_tag : t -> (string * string array) array = "ocaml_gstreamer_message_parse_tag" let parse_tag msg = let tags = parse_tag msg in let tags = Array.map (fun (l, v) -> (l, Array.to_list v)) tags in Array.to_list tags external parse_error : t -> string = "ocaml_gstreamer_message_parse_error" external parse_state_changed : t -> Element.state * Element.state * Element.state = "ocaml_gstreamer_message_parse_state_changed" external parse_buffering : t -> int = "ocaml_gstreamer_message_parse_buffering" let message_of_msg msg = match message_type msg with | Unknown -> `Unknown | End_of_stream -> `End_of_stream | Error -> `Error (parse_error msg) | Warning -> `Warning (parse_error msg) | Info -> `Info (parse_error msg) | Tag -> `Tag (parse_tag msg) | Buffering -> `Buffering (parse_buffering msg) | State_changed -> `State_changed (parse_state_changed msg) | State_dirty -> `State_dirty | Step_done -> `Step_done | Clock_provide -> `Clock_provide | Clock_lost -> `Clock_lost | New_clock -> `New_clock | Structure_change -> `Structure_change | Stream_status -> `Stream_status | Application -> `Application | Element -> `Element | Segment_start -> `Segment_start | Segment_done -> `Segment_done | Duration_changed -> `Duration_changed | Latency -> `Latency | Async_start -> `Async_start | Async_done -> `Async_done | Request_state -> `Request_state | Step_start -> `Step_start | Qos -> `Qos | Progress -> `Progress | Toc -> `Toc | Reset_time -> `Reset_time | Stream_start -> `Stream_start | Need_context -> `Need_context | Have_context -> `Have_context | Any -> assert false end module Loop = struct type t external create : unit -> t = "ocaml_gstreamer_loop_create" external run : t -> unit = "ocaml_gstreamer_loop_run" external quit : t -> unit = "ocaml_gstreamer_loop_quit" end module Bus = struct type message_payload = Message.msg type message = { source : string; payload : message_payload } type t type message_type = [ `Unknown | `End_of_stream | `Error | `Warning | `Info | `Tag | `Buffering | `State_changed | `State_dirty | `Step_done | `Clock_provide | `Clock_lost | `New_clock | `Structure_change | `Stream_status | `Application | `Element | `Segment_start | `Segment_done | `Duration_changed | `Latency | `Async_start | `Async_done | `Request_state | `Step_start | `Qos | `Progress | `Toc | `Reset_time | `Stream_start | `Need_context | `Have_context | `Any ] external of_element : Element.t -> t = "ocaml_gstreamer_bus_of_element" let type_of_mesage_type = function | `Unknown -> Message.Unknown | `End_of_stream -> Message.End_of_stream | `Error -> Message.Error | `Warning -> Message.Warning | `Info -> Message.Info | `Tag -> Message.Tag | `Buffering -> Message.Buffering | `State_changed -> Message.State_changed | `State_dirty -> Message.State_dirty | `Step_done -> Message.Step_done | `Clock_provide -> Message.Clock_provide | `Clock_lost -> Message.Clock_lost | `New_clock -> Message.New_clock | `Structure_change -> Message.Structure_change | `Stream_status -> Message.Stream_status | `Application -> Message.Application | `Element -> Message.Element | `Segment_start -> Message.Segment_start | `Segment_done -> Message.Segment_done | `Duration_changed -> Message.Duration_changed | `Latency -> Message.Latency | `Async_start -> Message.Async_start | `Async_done -> Message.Async_done | `Request_state -> Message.Request_state | `Step_start -> Message.Step_start | `Qos -> Message.Qos | `Progress -> Message.Progress | `Toc -> Message.Toc | `Reset_time -> Message.Reset_time | `Stream_start -> Message.Stream_start | `Need_context -> Message.Need_context | `Have_context -> Message.Have_context | `Any -> Message.Any let parse_msg msg = { source = Message.source_name msg; payload = Message.message_of_msg msg } let any_message = function None -> None | Some msg -> Some (parse_msg msg) external pop_filtered : t -> Message.message_type array -> Message.t option = "ocaml_gstreamer_bus_pop_filtered" let pop_filtered bus filter = any_message (pop_filtered bus (Array.of_list (List.map type_of_mesage_type filter))) external timed_pop_filtered : t -> ?timeout:Int64.t -> Message.message_type array -> Message.t = "ocaml_gstreamer_bus_timed_pop_filtered" let timed_pop_filtered bus ?timeout filter = parse_msg (timed_pop_filtered bus ?timeout (Array.of_list (List.map type_of_mesage_type filter))) end module Bin = struct type t = Element.t let of_element e = e external add : t -> Element.t -> unit = "ocaml_gstreamer_bin_add" let add_many bin e = List.iter (add bin) e external get_by_name : t -> string -> Element.t = "ocaml_gstreamer_bin_get_by_name" end module Pipeline = struct type t = Element.t external create : string -> t = "ocaml_gstreamer_pipeline_create" external parse_launch : string -> t = "ocaml_gstreamer_pipeline_parse_launch" end module Buffer = struct type t (* Not allowing the two below for now because they are quite unsafe. *) (* external create : int -> t = "ocaml_gstreamer_buffer_create" *) (* external set_data : t -> int -> data -> int -> int -> unit = "ocaml_gstreamer_buffer_set_data" *) external of_string : string -> int -> int -> t = "ocaml_gstreamer_buffer_of_string" external of_data : data -> int -> int -> t = "ocaml_gstreamer_buffer_of_data" external of_data_list : (data * int * int) list -> t = "ocaml_gstreamer_buffer_of_data_list" external to_data : t -> data = "ocaml_gstreamer_buffer_to_data" external to_string : t -> string = "ocaml_gstreamer_buffer_to_string" external set_presentation_time : t -> Int64.t -> unit = "ocaml_gstreamer_buffer_set_presentation_time" external set_decoding_time : t -> Int64.t -> unit = "ocaml_gstreamer_buffer_set_decoding_time" external set_duration : t -> Int64.t -> unit = "ocaml_gstreamer_buffer_set_duration" end module App_src = struct type t external of_element : Element.t -> t = "ocaml_gstreamer_appsrc_of_element" external to_element : t -> Element.t = "ocaml_gstreamer_appsrc_to_element" external push_buffer : t -> Buffer.t -> unit = "ocaml_gstreamer_appsrc_push_buffer" external push_buffer_bytes : t -> Int64.t -> Int64.t -> bytes -> int -> int -> unit = "ocaml_gstreamer_appsrc_push_buffer_bytes_b" "ocaml_gstreamer_appsrc_push_buffer_bytes_n" let push_buffer_bytes src ?(presentation_time = Int64.minus_one) ?(duration = Int64.minus_one) data ofs len = push_buffer_bytes src presentation_time duration data ofs len external push_buffer_data : t -> Int64.t -> Int64.t -> data -> int -> int -> unit = "ocaml_gstreamer_appsrc_push_buffer_data_b" "ocaml_gstreamer_appsrc_push_buffer_data_n" let push_buffer_data src ?(presentation_time = Int64.minus_one) ?(duration = Int64.minus_one) data ofs len = push_buffer_data src presentation_time duration data ofs len external on_need_data : t -> (int -> unit) -> unit = "ocaml_gstreamer_appsrc_connect_need_data" external end_of_stream : t -> unit = "ocaml_gstreamer_appsrc_end_of_stream" external set_format : t -> Format.t -> unit = "ocaml_gstreamer_appsrc_set_format" end module App_sink = struct type t external of_element : Element.t -> t = "ocaml_gstreamer_appsink_of_element" external pull_buffer : t -> Buffer.t = "ocaml_gstreamer_appsink_pull_buffer" let pull_buffer_data sink = Buffer.to_data (pull_buffer sink) let pull_buffer_string sink = Buffer.to_string (pull_buffer sink) external emit_signals : t -> unit = "ocaml_gstreamer_appsink_emit_signals" external is_eos : t -> bool = "ocaml_gstreamer_appsink_is_eos" external on_new_sample : t -> (unit -> unit) -> unit = "ocaml_gstreamer_appsink_connect_new_sample" external set_max_buffers : t -> int -> unit = "ocaml_gstreamer_appsink_set_max_buffers" end module Caps = struct type t external to_string : t -> string = "ocaml_gstreamer_caps_to_string" end module Type_find_element = struct type t external of_element : Element.t -> t = "ocaml_gstreamer_typefind_element_of_element" external on_have_type : t -> (int -> Caps.t -> unit) -> unit = "ocaml_gstreamer_typefind_element_connect_have_type" end module Tag_setter = struct type t = Element.t type merge_mode = | Undefined | Replace_all | Replace | Append | Prepend | Keep | Keep_all | Count let of_element e = e external add_tag : t -> merge_mode -> string -> string -> unit = "ocaml_gstreamer_tag_setter_add_tag" end ocaml-gstreamer-0.3.1/src/gstreamer.mli000066400000000000000000000172131375127041700200730ustar00rootroot00000000000000(** An error occured (with given explanation). *) exception Error of string exception Timeout exception Stopped exception Failed (** Trying to read data from a stream which has ended. *) exception End_of_stream (** Initialize GStreamer. This function should be called before anything other GStreamer function. *) val init : ?argv:string array -> unit -> unit (** Uninitialize GStreamer. This function does not normally need to be called excepting when debugging memory. *) val deinit : unit -> unit (** Version of GStreamer. *) val version : unit -> int * int * int * int (** Version of GStreamer. *) val version_string : unit -> string (** Type for data in buffers. *) type data = (int, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t (** Formats for durations. *) module Format : sig (** Format for durations. *) type t = | Undefined | Default | Bytes | Time (** Time in nanoseconds. *) | Buffers | Percent (** String representation of a duration format. *) val to_string : t -> string end (** Events. *) module Event : sig (** Seek mode. *) type seek_flag = | Seek_flag_none | Seek_flag_flush | Seek_flag_accurate | Seek_flag_key_unit | Seek_flag_segment | Seek_flag_skip | Seek_flag_snap_before | Seek_flag_snap_after | Seek_flag_snap_nearest end (** Elements. *) module Element : sig (** An element. *) type t val set_property_string : t -> string -> string -> unit val set_property_int : t -> string -> string -> unit val set_property_bool : t -> string -> string -> unit (** State of an element. *) type state = | State_void_pending | State_null | State_ready | State_paused | State_playing (** String representation of a state. *) val string_of_state : state -> string (** Return value for state change. *) type state_change = | State_change_success | State_change_async | State_change_no_preroll val set_state : t -> state -> state_change (** Current state of an element: return value, current state and pending state. *) val get_state : t -> state_change * state * state (** Link two elements. *) val link : t -> t -> unit (** Sequentially link a list of element. *) val link_many : t list -> unit (** Current position of an element. *) val position : t -> Format.t -> Int64.t (** Duration of an element. *) val duration : t -> Format.t -> Int64.t (** Seek to a given position relative to the start of the stream. *) val seek_simple : t -> Format.t -> Event.seek_flag list -> Int64.t -> unit end (** Element factories. *) module Element_factory : sig type t = Element.t val make : string -> string -> t end (** Main loop. *) module Loop : sig type t val create : unit -> t val run : t -> unit val quit : t -> unit end (** Buses. *) module Bus : sig type t type message_type = [ `Unknown | `End_of_stream | `Error | `Warning | `Info | `Tag | `Buffering | `State_changed | `State_dirty | `Step_done | `Clock_provide | `Clock_lost | `New_clock | `Structure_change | `Stream_status | `Application | `Element | `Segment_start | `Segment_done | `Duration_changed | `Latency | `Async_start | `Async_done | `Request_state | `Step_start | `Qos | `Progress | `Toc | `Reset_time | `Stream_start | `Need_context | `Have_context | `Any ] type message_payload = [ `Unknown | `End_of_stream | `Error of string | `Warning of string | `Info of string | `Tag of (string * string list) list | `Buffering of int | `State_changed of Element.state * Element.state * Element.state | `State_dirty | `Step_done | `Clock_provide | `Clock_lost | `New_clock | `Structure_change | `Stream_status | `Application | `Element | `Segment_start | `Segment_done | `Duration_changed | `Latency | `Async_start | `Async_done | `Request_state | `Step_start | `Qos | `Progress | `Toc | `Reset_time | `Stream_start | `Need_context | `Have_context ] type message = { source : string; payload : message_payload } val of_element : Element.t -> t val pop_filtered : t -> message_type list -> message option val timed_pop_filtered : t -> ?timeout:Int64.t -> message_type list -> message end (** Bins. *) module Bin : sig type t = Element.t val of_element : Element.t -> t val add : t -> Element.t -> unit val add_many : t -> Element.t list -> unit (** [get_by_name "foo"] find a bin by name. Raises [Not_found] if element does not exist. *) val get_by_name : t -> string -> Element.t end (** Pipelines. *) module Pipeline : sig type t = Element.t val create : string -> t (** Create a pipeline from a string description. *) val parse_launch : string -> t end (** Buffers. *) module Buffer : sig (** A buffer. *) type t (** Create a buffer containing a given string as contents. *) val of_string : string -> int -> int -> t (** Create a buffer containing given data as contents. *) val of_data : data -> int -> int -> t val of_data_list : (data * int * int) list -> t val to_data : t -> data val to_string : t -> string (** Set the presentation time of a buffer. *) val set_presentation_time : t -> Int64.t -> unit (** Set the decoding time of a buffer. *) val set_decoding_time : t -> Int64.t -> unit (** Set the duration of a buffer. *) val set_duration : t -> Int64.t -> unit end (** App sources. *) module App_src : sig type t val to_element : t -> Element.t val of_element : Element.t -> t (** Push a buffer. *) val push_buffer : t -> Buffer.t -> unit (** Push a buffer in bytes format. *) val push_buffer_bytes : t -> ?presentation_time:Int64.t -> ?duration:Int64.t -> bytes -> int -> int -> unit (** Push a buffer in data format. *) val push_buffer_data : t -> ?presentation_time:Int64.t -> ?duration:Int64.t -> data -> int -> int -> unit (** Register a callback that will be called when data need to be fed into the source (the argument is the number of bytes needed by the source). *) val on_need_data : t -> (int -> unit) -> unit (** Emit an end of stream signal. *) val end_of_stream : t -> unit val set_format : t -> Format.t -> unit end (** App sinks. *) module App_sink : sig type t val of_element : Element.t -> t val pull_buffer : t -> Buffer.t (** Pull a buffer in data format. *) val pull_buffer_data : t -> data (** Pull a buffer in string format. *) val pull_buffer_string : t -> string (** Enable signal emitting. *) val emit_signals : t -> unit (** Check whether the end of stream was reached. *) val is_eos : t -> bool (** Register a callback which will be called whenever a sample (a buffer in GStreamer terminology) is available. [emit_signals] should be called first in order for the callback to be called. *) val on_new_sample : t -> (unit -> unit) -> unit (** Set the maximal number of internal buffers. *) val set_max_buffers : t -> int -> unit end (** Capabilities. *) module Caps : sig type t val to_string : t -> string end (** Type finders. *) module Type_find_element : sig type t val of_element : Element.t -> t val on_have_type : t -> (int -> Caps.t -> unit) -> unit end (** Tag setters. *) module Tag_setter : sig type t type merge_mode = | Undefined | Replace_all | Replace | Append | Prepend | Keep | Keep_all | Count val of_element : Element.t -> t (** Set a tag in an element. *) val add_tag : t -> merge_mode -> string -> string -> unit end ocaml-gstreamer-0.3.1/src/gstreamer_stubs.c000066400000000000000000001171501375127041700207550ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #ifndef Bytes_val #define Bytes_val String_val #endif #include #include #include #include #include #include #include #include #include #include static pthread_key_t ocaml_c_thread_key; static pthread_once_t ocaml_c_thread_key_once = PTHREAD_ONCE_INIT; static void ocaml_gstreamer_on_thread_exit(void *key) { caml_c_thread_unregister(); } static void ocaml_gstreamer_make_key() { pthread_key_create(&ocaml_c_thread_key, ocaml_gstreamer_on_thread_exit); } static void ocaml_gstreamer_register_thread() { static int initialized = 1; void *ptr; pthread_once(&ocaml_c_thread_key_once, ocaml_gstreamer_make_key); if ((ptr = pthread_getspecific(ocaml_c_thread_key)) == NULL) { pthread_setspecific(ocaml_c_thread_key, (void *)&initialized); caml_c_thread_register(); } } CAMLprim value ocaml_gstreamer_init(value _argv) { CAMLparam1(_argv); char **argv = NULL; int argc = 0; int len, i; if (Is_block(_argv)) { _argv = Field(_argv, 0); argc = Wosize_val(_argv); argv = malloc(argc * sizeof(char *)); for (i = 0; i < argc; i++) { len = caml_string_length(Field(_argv, i)); argv[i] = malloc(len + 1); memcpy(argv[i], String_val(Field(_argv, i)), len + 1); } } caml_release_runtime_system(); gst_init(&argc, &argv); for (i = 0; i < argc; i++) free(argv[i]); free(argv); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_deinit(value unit) { CAMLparam0(); caml_release_runtime_system(); gst_deinit(); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_version(value unit) { CAMLparam0(); CAMLlocal1(ans); unsigned int major, minor, micro, nano; gst_version(&major, &minor, µ, &nano); ans = caml_alloc_tuple(4); Store_field(ans, 0, Val_int(major)); Store_field(ans, 1, Val_int(minor)); Store_field(ans, 2, Val_int(micro)); Store_field(ans, 3, Val_int(nano)); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_version_string(value unit) { CAMLparam0(); CAMLreturn(caml_copy_string(gst_version_string())); } /***** Format *****/ #define formats_len 6 static const GstFormat formats[formats_len] = { GST_FORMAT_UNDEFINED, GST_FORMAT_DEFAULT, GST_FORMAT_BYTES, GST_FORMAT_TIME, GST_FORMAT_BUFFERS, GST_FORMAT_PERCENT}; static GstFormat format_val(value v) { return formats[Int_val(v)]; } /* static value val_format(GstFormat fmt) { int i; for (i = 0; i < formats_len; i++) if (fmt == formats[i]) return Val_int(i); assert(0); } */ CAMLprim value ocaml_gstreamer_format_to_string(value _f) { GstFormat f = format_val(_f); return caml_copy_string(gst_format_get_name(f)); } /***** Event *****/ #define seek_flags_len 9 static const GstSeekFlags seek_flags[seek_flags_len] = { GST_SEEK_FLAG_NONE, GST_SEEK_FLAG_FLUSH, GST_SEEK_FLAG_ACCURATE, GST_SEEK_FLAG_KEY_UNIT, GST_SEEK_FLAG_SEGMENT, GST_SEEK_FLAG_SKIP, GST_SEEK_FLAG_SNAP_BEFORE, GST_SEEK_FLAG_SNAP_AFTER, GST_SEEK_FLAG_SNAP_NEAREST}; static GstSeekFlags seek_flags_val(value v) { return seek_flags[Int_val(v)]; } /***** Element ******/ #define Element_val(v) (*(GstElement **)Data_custom_val(v)) static void finalize_element(value v) { GstElement *e = Element_val(v); gst_object_unref(e); } static struct custom_operations element_ops = { "ocaml_gstreamer_element", finalize_element, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; #define value_of_element(e, ans) \ if (!e) \ caml_raise_not_found(); \ ans = caml_alloc_custom(&element_ops, sizeof(GstElement *), 0, 1); \ Element_val(ans) = e; CAMLprim value ocaml_gstreamer_element_set_property_string(value e, value l, value v) { CAMLparam3(e, l, v); g_object_set(Element_val(e), String_val(l), String_val(v), NULL); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_element_set_property_int(value e, value l, value v) { CAMLparam3(e, l, v); g_object_set(Element_val(e), String_val(l), Int_val(v), NULL); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_element_set_property_bool(value e, value l, value v) { CAMLparam3(e, l, v); g_object_set(Element_val(e), String_val(l), Bool_val(v), NULL); CAMLreturn(Val_unit); } #define states_len 5 static const GstState states[states_len] = { GST_STATE_VOID_PENDING, GST_STATE_NULL, GST_STATE_READY, GST_STATE_PAUSED, GST_STATE_PLAYING}; static GstState state_of_val(value v) { int n = Int_val(v); assert(n < states_len); return states[n]; } static value val_of_state(GstState state) { int i; for (i = 0; i < states_len; i++) if (state == states[i]) return Val_int(i); assert(0); } static value value_of_state_change_return(GstStateChangeReturn ret) { switch (ret) { case GST_STATE_CHANGE_FAILURE: caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); case GST_STATE_CHANGE_SUCCESS: return Val_int(0); case GST_STATE_CHANGE_ASYNC: return Val_int(1); case GST_STATE_CHANGE_NO_PREROLL: return Val_int(2); default: assert(0); } } CAMLprim value ocaml_gstreamer_element_string_of_state(value state) { CAMLparam1(state); CAMLreturn(caml_copy_string(gst_element_state_get_name(state_of_val(state)))); } CAMLprim value ocaml_gstreamer_element_set_state(value _e, value _s) { CAMLparam2(_e, _s); GstElement *e = Element_val(_e); GstState s = state_of_val(_s); GstStateChangeReturn ret; caml_release_runtime_system(); ret = gst_element_set_state(e, s); caml_acquire_runtime_system(); CAMLreturn(value_of_state_change_return(ret)); } CAMLprim value ocaml_gstreamer_element_get_state(value _e) { CAMLparam1(_e); CAMLlocal1(ans); GstElement *e = Element_val(_e); GstStateChangeReturn ret; GstState state, pending; GstClockTime timeout = GST_CLOCK_TIME_NONE; /* TODO */ caml_release_runtime_system(); ret = gst_element_get_state(e, &state, &pending, timeout); caml_acquire_runtime_system(); ans = caml_alloc_tuple(3); Store_field(ans, 0, value_of_state_change_return(ret)); Store_field(ans, 1, val_of_state(state)); Store_field(ans, 2, val_of_state(pending)); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_element_link(value _src, value _dst) { CAMLparam2(_src, _dst); GstElement *src = Element_val(_src); GstElement *dst = Element_val(_dst); gboolean ret; caml_release_runtime_system(); ret = gst_element_link(src, dst); caml_acquire_runtime_system(); if (!ret) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_element_position(value _e, value _fmt) { CAMLparam2(_e, _fmt); GstElement *e = Element_val(_e); GstFormat fmt = format_val(_fmt); gint64 pos; gboolean ret; caml_release_runtime_system(); ret = gst_element_query_position(e, fmt, &pos); caml_acquire_runtime_system(); if (!ret) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(caml_copy_int64(pos)); } CAMLprim value ocaml_gstreamer_element_duration(value _e, value _fmt) { CAMLparam2(_e, _fmt); GstElement *e = Element_val(_e); GstFormat fmt = format_val(_fmt); gint64 dur; gboolean ret; caml_release_runtime_system(); ret = gst_element_query_duration(e, fmt, &dur); caml_acquire_runtime_system(); if (!ret) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(caml_copy_int64(dur)); } CAMLprim value ocaml_gstreamer_element_seek_simple(value _e, value _fmt, value _flags, value _pos) { CAMLparam4(_e, _fmt, _flags, _pos); GstElement *e = Element_val(_e); GstFormat fmt = format_val(_fmt); GstSeekFlags flags = 0; gint64 pos = Int64_val(_pos); gboolean ret; int i; for (i = 0; i < Wosize_val(_flags); i++) flags |= seek_flags_val(Field(_flags, i)); caml_release_runtime_system(); ret = gst_element_seek_simple(e, fmt, flags, pos); caml_acquire_runtime_system(); if (!ret) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } /***** Element factory *****/ CAMLprim value ocaml_gstreamer_element_factory_make(value factname, value name) { CAMLparam2(factname, name); CAMLlocal1(ans); GstElement *e; e = gst_element_factory_make(String_val(factname), String_val(name)); value_of_element(e, ans); CAMLreturn(ans); } /**** Message *****/ #define message_types_len 33 static const GstMessageType message_types[message_types_len] = { GST_MESSAGE_UNKNOWN, GST_MESSAGE_EOS, GST_MESSAGE_ERROR, GST_MESSAGE_WARNING, GST_MESSAGE_INFO, GST_MESSAGE_TAG, GST_MESSAGE_BUFFERING, GST_MESSAGE_STATE_CHANGED, GST_MESSAGE_STATE_DIRTY, GST_MESSAGE_STEP_DONE, GST_MESSAGE_CLOCK_PROVIDE, GST_MESSAGE_CLOCK_LOST, GST_MESSAGE_NEW_CLOCK, GST_MESSAGE_STRUCTURE_CHANGE, GST_MESSAGE_STREAM_STATUS, GST_MESSAGE_APPLICATION, GST_MESSAGE_ELEMENT, GST_MESSAGE_SEGMENT_START, GST_MESSAGE_SEGMENT_DONE, GST_MESSAGE_DURATION_CHANGED, GST_MESSAGE_LATENCY, GST_MESSAGE_ASYNC_START, GST_MESSAGE_ASYNC_DONE, GST_MESSAGE_REQUEST_STATE, GST_MESSAGE_STEP_START, GST_MESSAGE_QOS, GST_MESSAGE_PROGRESS, GST_MESSAGE_TOC, GST_MESSAGE_RESET_TIME, GST_MESSAGE_STREAM_START, GST_MESSAGE_NEED_CONTEXT, GST_MESSAGE_HAVE_CONTEXT, GST_MESSAGE_ANY}; static GstMessageType message_type_of_int(int n) { return message_types[n]; } static int int_of_message_type(GstMessageType msg) { int i; for (i = 0; i < message_types_len; i++) { if (msg == message_types[i]) return i; } printf("error in message: %d\n", msg); assert(0); } #define Message_val(v) (*(GstMessage **)Data_custom_val(v)) static void finalize_message(value v) { GstMessage *e = Message_val(v); gst_message_unref(e); } static struct custom_operations message_ops = { "ocaml_gstreamer_message", finalize_message, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; #define value_of_message(msg, ans) \ ans = caml_alloc_custom(&message_ops, sizeof(GstMessage *), 0, 1); \ Message_val(ans) = msg; CAMLprim value ocaml_gstreamer_message_type(value _msg) { CAMLparam1(_msg); GstMessage *msg = Message_val(_msg); CAMLreturn(Val_int(int_of_message_type(GST_MESSAGE_TYPE(msg)))); } CAMLprim value ocaml_gstreamer_message_source_name(value _msg) { CAMLparam1(_msg); GstMessage *msg = Message_val(_msg); CAMLreturn(caml_copy_string(GST_MESSAGE_SRC_NAME(msg))); } CAMLprim value ocaml_gstreamer_message_parse_error(value _err) { CAMLparam1(_err); CAMLlocal1(ans); GError *err = NULL; gst_message_parse_error(Message_val(_err), &err, NULL); ans = caml_copy_string(err->message); g_error_free(err); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_message_parse_buffering(value _msg) { CAMLparam1(_msg); gint percent; gst_message_parse_buffering(Message_val(_msg), &percent); CAMLreturn(Val_int(percent)); } CAMLprim value ocaml_gstreamer_message_parse_state_changed(value _msg) { CAMLparam1(_msg); CAMLlocal1(ans); GstState old_state, new_state, pending; gst_message_parse_state_changed(Message_val(_msg), &old_state, &new_state, &pending); ans = caml_alloc_tuple(3); Store_field(ans, 0, val_of_state(old_state)); Store_field(ans, 1, val_of_state(new_state)); Store_field(ans, 2, val_of_state(pending)); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_message_parse_tag(value _msg) { CAMLparam1(_msg); CAMLlocal4(v, s, t, ans); GstMessage *msg = Message_val(_msg); GstTagList *tags = NULL; const GValue *val; const gchar *tag; int taglen; int i, j, n; caml_release_runtime_system(); gst_message_parse_tag(msg, &tags); taglen = gst_tag_list_n_tags(tags); caml_acquire_runtime_system(); ans = caml_alloc_tuple(taglen); for (i = 0; i < taglen; i++) { t = caml_alloc_tuple(2); // Tag name tag = gst_tag_list_nth_tag_name(tags, i); Store_field(t, 0, caml_copy_string(tag)); // Tag fields n = gst_tag_list_get_tag_size(tags, tag); v = caml_alloc_tuple(n); for (j = 0; j < n; j++) { val = gst_tag_list_get_value_index(tags, tag, j); if (G_VALUE_HOLDS_STRING(val)) { s = caml_copy_string(g_value_get_string(val)); } else if (GST_VALUE_HOLDS_DATE_TIME(val)) { GstDateTime *dt = g_value_get_boxed(val); gchar *dt_str = gst_date_time_to_iso8601_string(dt); s = caml_copy_string(dt_str); g_free(dt_str); } else { // TODO: better typed handling of non-string values? char *vc = g_strdup_value_contents(val); s = caml_copy_string(vc); free(vc); } Store_field(v, j, s); } Store_field(t, 1, v); Store_field(ans, i, t); } gst_tag_list_unref(tags); CAMLreturn(ans); } /**** Main Loop ****/ #define Loop_val(v) (*(GMainLoop **)Data_custom_val(v)) static void finalize_loop(value v) { GMainLoop *loop = Loop_val(v); g_main_loop_unref(loop); } static struct custom_operations loop_ops = { "ocaml_gstreamer_loop", finalize_loop, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; CAMLprim value ocaml_gstreamer_loop_create(value unit) { CAMLparam0(); CAMLlocal1(ans); GMainLoop *loop = g_main_loop_new(NULL, FALSE); if (!loop) caml_raise_out_of_memory(); ans = caml_alloc_custom(&loop_ops, sizeof(GMainLoop *), 0, 1); Loop_val(ans) = loop; CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_loop_run(value l) { CAMLparam1(l); GMainLoop *loop = Loop_val(l); caml_release_runtime_system(); g_main_loop_run(loop); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_loop_quit(value l) { CAMLparam1(l); GMainLoop *loop = Loop_val(l); caml_release_runtime_system(); g_main_loop_quit(loop); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } /**** Bus ****/ #define Bus_val(v) (*(GstBus **)Data_custom_val(v)) static void finalize_bus(value v) { GstBus *bus = Bus_val(v); gst_object_unref(bus); } static struct custom_operations bus_ops = { "ocaml_gstreamer_bus", finalize_bus, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; CAMLprim value ocaml_gstreamer_bus_of_element(value _e) { CAMLparam1(_e); CAMLlocal1(ans); GstElement *e = Element_val(_e); ans = caml_alloc_custom(&bus_ops, sizeof(GstBus *), 0, 1); Bus_val(ans) = gst_element_get_bus(e); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_bus_pop_filtered(value _bus, value _filter) { CAMLparam2(_bus, _filter); CAMLlocal2(ans, ret); GstBus *bus = Bus_val(_bus); GstMessageType filter = 0; GstMessage *msg; int i; for (i = 0; i < Wosize_val(_filter); i++) filter |= message_type_of_int(Int_val(Field(_filter, i))); caml_release_runtime_system(); msg = gst_bus_pop_filtered(bus, filter); caml_acquire_runtime_system(); if (!msg) ans = Val_int(0); else { value_of_message(msg, ret); ans = caml_alloc_tuple(1); Store_field(ans, 0, ret); } CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_bus_timed_pop_filtered(value _bus, value _timeout, value _filter) { CAMLparam3(_bus, _timeout, _filter); CAMLlocal1(ans); GstBus *bus = Bus_val(_bus); GstClockTime timeout = GST_CLOCK_TIME_NONE; GstMessageType filter = 0; GstMessage *msg; int i; if (Is_block(_timeout)) { timeout = (GstClockTime)Int64_val(Field(_timeout, 0)); } for (i = 0; i < Wosize_val(_filter); i++) filter |= message_type_of_int(Int_val(Field(_filter, i))); caml_release_runtime_system(); msg = gst_bus_timed_pop_filtered(bus, timeout, filter); caml_acquire_runtime_system(); if (!msg) caml_raise_constant(*caml_named_value("gstreamer_exn_timeout")); value_of_message(msg, ans); CAMLreturn(ans); } /***** Bin ******/ #define Bin_val(v) GST_BIN(Element_val(v)) CAMLprim value ocaml_gstreamer_bin_add(value _bin, value _e) { CAMLparam2(_bin, _e); GstBin *bin = Bin_val(_bin); GstElement *e = Element_val(_e); gboolean ret; caml_release_runtime_system(); /* gst_bin_add takes ownership but we want to keep it alive * and clean it with the Gc. */ gst_object_ref(e); ret = gst_bin_add(bin, e); caml_acquire_runtime_system(); if (!ret) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_bin_get_by_name(value _bin, value _name) { CAMLparam2(_bin, _name); CAMLlocal1(ans); GstBin *bin = Bin_val(_bin); GstElement *e; e = gst_bin_get_by_name(bin, String_val(_name)); value_of_element(e, ans); CAMLreturn(ans); } /***** Pipeline *****/ #define Pipeline_val(v) GST_PIPELINE(Element_val(v)) CAMLprim value ocaml_gstreamer_pipeline_create(value s) { CAMLparam1(s); CAMLlocal1(ans); GstElement *e; e = gst_pipeline_new(String_val(s)); value_of_element(e, ans); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_pipeline_parse_launch(value s) { CAMLparam1(s); CAMLlocal2(ans, _err); GError *err = NULL; GstElement *e; e = gst_parse_launch(String_val(s), &err); if (err || e == NULL) { _err = caml_copy_string(err->message); g_error_free(err); caml_raise_with_arg(*caml_named_value("gstreamer_exn_error"), _err); } value_of_element(e, ans); CAMLreturn(ans); } /***** Buffer ******/ #define Buffer_val(v) (*(GstBuffer **)Data_custom_val(v)) static void finalize_buffer(value v) { GstBuffer *b = Buffer_val(v); gst_buffer_unref(b); } static struct custom_operations buffer_ops = { "ocaml_gstreamer_buffer", finalize_buffer, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; #define value_of_buffer(b, ans) \ ans = caml_alloc_custom(&buffer_ops, sizeof(GstElement *), 0, 1); \ Buffer_val(ans) = b; #define buffer_fill(gstbuf, data, ofs, len) \ GstMapInfo map; \ gboolean bret; \ caml_release_runtime_system(); \ bret = gst_buffer_map(gstbuf, &map, GST_MAP_WRITE); \ caml_acquire_runtime_system(); \ if (!bret) \ caml_raise_out_of_memory(); \ memcpy(map.data, (unsigned char *)data + ofs, len); \ caml_release_runtime_system(); \ gst_buffer_unmap(gstbuf, &map); \ caml_acquire_runtime_system(); CAMLprim value ocaml_gstreamer_buffer_create(value _len) { CAMLparam0(); CAMLlocal1(ans); int len = Int_val(_len); GstBuffer *gstbuf; caml_release_runtime_system(); gstbuf = gst_buffer_new_allocate(NULL, len, NULL); caml_acquire_runtime_system(); if (!gstbuf) caml_raise_out_of_memory(); value_of_buffer(gstbuf, ans); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_buffer_set_data(value _buf, value _bufoff, value _ba, value _baoff, value _len) { CAMLparam2(_buf, _ba); CAMLlocal1(ans); GstBuffer *buf = Buffer_val(_buf); int buf_off = Int_val(_bufoff); unsigned char *data = Caml_ba_data_val(_ba); int data_off = Int_val(_baoff); int len = Int_val(_len); GstMapInfo map; gboolean bret; caml_release_runtime_system(); bret = gst_buffer_map(buf, &map, GST_MAP_WRITE); caml_acquire_runtime_system(); if (!bret) caml_raise_out_of_memory(); caml_release_runtime_system(); memcpy(map.data + buf_off, data + data_off, len); gst_buffer_unmap(buf, &map); caml_acquire_runtime_system(); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_buffer_of_string(value s, value _off, value _len) { CAMLparam1(s); CAMLlocal1(ans); int bufoff = Int_val(_off); int buflen = Int_val(_len); GstBuffer *gstbuf; char *data; assert(buflen + bufoff <= caml_string_length(s)); caml_release_runtime_system(); gstbuf = gst_buffer_new_allocate(NULL, buflen, NULL); caml_acquire_runtime_system(); if (!gstbuf) caml_raise_out_of_memory(); data = (char *)Bytes_val(s); buffer_fill(gstbuf, data, bufoff, buflen); value_of_buffer(gstbuf, ans); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_buffer_of_data(value _ba, value _off, value _len) { CAMLparam1(_ba); CAMLlocal1(ans); int bufoff = Int_val(_off); int buflen = Int_val(_len); GstBuffer *gstbuf; char *data; assert(buflen + bufoff <= Caml_ba_array_val(_ba)->dim[0]); caml_release_runtime_system(); gstbuf = gst_buffer_new_allocate(NULL, buflen, NULL); caml_acquire_runtime_system(); if (!gstbuf) caml_raise_out_of_memory(); data = Caml_ba_data_val(_ba); buffer_fill(gstbuf, data, bufoff, buflen); value_of_buffer(gstbuf, ans); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_buffer_of_data_list(value dol) { CAMLparam1(dol); CAMLlocal2(tmp, ans); int buflen = 0; // Compute the total length; tmp = dol; while (Is_block(tmp)) { buflen += Int_val(Field(Field(tmp, 0), 2)); tmp = Field(tmp, 1); } GstBuffer *gstbuf; caml_release_runtime_system(); gstbuf = gst_buffer_new_allocate(NULL, buflen, NULL); caml_acquire_runtime_system(); if (!gstbuf) caml_raise_out_of_memory(); tmp = dol; GstMapInfo map; gboolean bret; int bufoff = 0; caml_release_runtime_system(); bret = gst_buffer_map(gstbuf, &map, GST_MAP_WRITE); caml_acquire_runtime_system(); if (!bret) caml_raise_out_of_memory(); while (Is_block(tmp)) { unsigned char *data = Caml_ba_data_val(Field(Field(tmp, 0), 0)); int off = Int_val(Field(Field(tmp, 0), 1)); int len = Int_val(Field(Field(tmp, 0), 2)); assert(off + len <= Caml_ba_array_val(Field(Field(tmp, 0), 0))->dim[0]); memcpy(map.data + bufoff, data + off, len); bufoff += len; tmp = Field(tmp, 1); } caml_release_runtime_system(); gst_buffer_unmap(gstbuf, &map); caml_acquire_runtime_system(); value_of_buffer(gstbuf, ans); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_buffer_to_string(value _buf) { CAMLparam1(_buf); CAMLlocal1(ans); GstBuffer *buf = Buffer_val(_buf); GstMapInfo map; caml_release_runtime_system(); gboolean ret = gst_buffer_map(buf, &map, GST_MAP_READ); caml_acquire_runtime_system(); if (!ret) caml_raise_out_of_memory(); intnat len = map.size; ans = caml_alloc_string(len); memcpy(Bytes_val(ans), map.data, len); caml_release_runtime_system(); gst_buffer_unmap(buf, &map); caml_acquire_runtime_system(); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_buffer_to_data(value _buf) { CAMLparam1(_buf); CAMLlocal1(ans); GstBuffer *buf = Buffer_val(_buf); GstMapInfo map; caml_release_runtime_system(); gboolean ret = gst_buffer_map(buf, &map, GST_MAP_READ); caml_acquire_runtime_system(); if (!ret) caml_raise_out_of_memory(); intnat len = map.size; ans = caml_ba_alloc(CAML_BA_C_LAYOUT | CAML_BA_UINT8, 1, NULL, &len); memcpy(Caml_ba_data_val(ans), map.data, len); caml_release_runtime_system(); gst_buffer_unmap(buf, &map); caml_acquire_runtime_system(); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_buffer_set_presentation_time(value _buf, value _t) { CAMLparam2(_buf, _t); GstBuffer *b = Buffer_val(_buf); GstClockTime t = Int64_val(_t); b->pts = t; CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_buffer_set_decoding_time(value _buf, value _t) { CAMLparam2(_buf, _t); GstBuffer *b = Buffer_val(_buf); GstClockTime t = Int64_val(_t); b->dts = t; CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_buffer_set_duration(value _buf, value _t) { CAMLparam2(_buf, _t); GstBuffer *b = Buffer_val(_buf); GstClockTime t = Int64_val(_t); b->duration = t; CAMLreturn(Val_unit); } /***** Appsrc *****/ typedef struct { GstAppSrc *appsrc; value element; value need_data_cb; // Callback function gulong need_data_hid; // Callback handler ID } appsrc; #define Appsrc_val(v) (*(appsrc **)Data_custom_val(v)) static void disconnect_need_data(appsrc *as) { if (as->need_data_hid) { g_signal_handler_disconnect(as->appsrc, as->need_data_hid); as->need_data_hid = 0; } if (as->need_data_cb) { caml_remove_generational_global_root(&as->need_data_cb); as->need_data_cb = 0; } } static void finalize_appsrc(value v) { appsrc *as = Appsrc_val(v); disconnect_need_data(as); if (as->element) { caml_remove_generational_global_root(&as->element); as->element = 0; } free(as); } static struct custom_operations appsrc_ops = { "ocaml_gstreamer_appsrc", finalize_appsrc, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; CAMLprim value ocaml_gstreamer_appsrc_of_element(value _e) { CAMLparam1(_e); CAMLlocal1(ans); GstElement *e = Element_val(_e); appsrc *as = malloc(sizeof(appsrc)); if (as == NULL) caml_raise_out_of_memory(); as->appsrc = GST_APP_SRC(e); as->need_data_cb = 0; as->need_data_hid = 0; as->element = _e; caml_register_global_root(&as->element); ans = caml_alloc_custom(&appsrc_ops, sizeof(appsrc *), 0, 1); Appsrc_val(ans) = as; CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_appsrc_to_element(value _as) { CAMLparam1(_as); CAMLlocal1(ans); appsrc *as = Appsrc_val(_as); GstElement *e = GST_ELEMENT(as->appsrc); value_of_element(e, ans); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_appsrc_push_buffer_bytes_n( value _as, value _pres_time, value _dur, value _buf, value _ofs, value _len) { CAMLparam4(_as, _pres_time, _dur, _buf); appsrc *as = Appsrc_val(_as); GstBuffer *gstbuf; GstFlowReturn ret; int64_t pres_time = Int64_val(_pres_time); int64_t dur = Int64_val(_dur); unsigned char *data; caml_release_runtime_system(); gstbuf = gst_buffer_new_allocate(NULL, Int_val(_len), NULL); caml_acquire_runtime_system(); if (!gstbuf) caml_raise_out_of_memory(); if (pres_time >= 0) gstbuf->pts = pres_time; if (dur >= 0) gstbuf->duration = dur; data = Bytes_val(_buf); buffer_fill(gstbuf, data, Int_val(_ofs), Int_val(_len)); caml_release_runtime_system(); ret = gst_app_src_push_buffer(as->appsrc, gstbuf); caml_acquire_runtime_system(); if (ret != GST_FLOW_OK) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_appsrc_push_buffer_bytes_b(value *argv, int argn) { return ocaml_gstreamer_appsrc_push_buffer_bytes_n(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); } CAMLprim value ocaml_gstreamer_appsrc_push_buffer(value _as, value _buf) { CAMLparam2(_as, _buf); appsrc *as = Appsrc_val(_as); GstBuffer *gstbuf = Buffer_val(_buf); GstFlowReturn ret; caml_release_runtime_system(); g_signal_emit_by_name(GST_ELEMENT(as->appsrc), "push-buffer", gstbuf, &ret); caml_acquire_runtime_system(); if (ret != GST_FLOW_OK) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_appsrc_push_buffer_data_n(value _as, value _pres_time, value _dur, value _buf, value _ofs, value _len) { CAMLparam4(_as, _pres_time, _dur, _buf); appsrc *as = Appsrc_val(_as); GstBuffer *gstbuf; GstFlowReturn ret; int64_t pres_time = Int64_val(_pres_time); int64_t dur = Int64_val(_dur); char *data; caml_release_runtime_system(); gstbuf = gst_buffer_new_allocate(NULL, Int_val(_len), NULL); caml_acquire_runtime_system(); if (!gstbuf) caml_raise_out_of_memory(); if (pres_time >= 0) gstbuf->pts = pres_time; if (dur >= 0) gstbuf->duration = dur; data = Caml_ba_data_val(_buf); buffer_fill(gstbuf, data, Int_val(_ofs), Int_val(_len)); caml_release_runtime_system(); ret = gst_app_src_push_buffer(as->appsrc, gstbuf); caml_acquire_runtime_system(); if (ret != GST_FLOW_OK) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_appsrc_push_buffer_data_b(value *argv, int argn) { return ocaml_gstreamer_appsrc_push_buffer_data_n(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); } static void appsrc_need_data_cb(GstAppSrc *gas, guint length, gpointer user_data) { appsrc *as = (appsrc *)user_data; ocaml_gstreamer_register_thread(); caml_acquire_runtime_system(); caml_callback(as->need_data_cb, Val_int(length)); caml_release_runtime_system(); } CAMLprim value ocaml_gstreamer_appsrc_connect_need_data(value _as, value f) { CAMLparam2(_as, f); appsrc *as = Appsrc_val(_as); disconnect_need_data(as); as->need_data_cb = f; caml_register_generational_global_root(&as->need_data_cb); caml_release_runtime_system(); as->need_data_hid = g_signal_connect(as->appsrc, "need-data", G_CALLBACK(appsrc_need_data_cb), as); caml_acquire_runtime_system(); if (!as->need_data_hid) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_appsrc_end_of_stream(value _as) { CAMLparam1(_as); appsrc *as = Appsrc_val(_as); GstFlowReturn ret; caml_release_runtime_system(); g_signal_emit_by_name(as->appsrc, "end-of-stream", &ret); caml_acquire_runtime_system(); if (ret != GST_FLOW_OK) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_appsrc_set_format(value _as, value _fmt) { CAMLparam2(_as, _fmt); appsrc *as = Appsrc_val(_as); GstFormat fmt = format_val(_fmt); caml_release_runtime_system(); g_object_set(G_OBJECT(as->appsrc), "format", fmt, NULL); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } /***** Appsink *****/ typedef struct { GstAppSink *appsink; value element; value new_sample_cb; // Callback function gulong new_sample_hid; // Callback handler ID } appsink; #define Appsink_val(v) (*(appsink **)Data_custom_val(v)) static void disconnect_new_sample(appsink *as) { if (as->new_sample_hid) { g_signal_handler_disconnect(as->appsink, as->new_sample_hid); as->new_sample_hid = 0; } if (as->new_sample_cb) { caml_remove_generational_global_root(&as->new_sample_cb); as->new_sample_cb = 0; } } static void finalize_appsink(value v) { appsink *as = Appsink_val(v); disconnect_new_sample(as); if (as->element) { caml_remove_generational_global_root(&as->element); as->element = 0; } free(as); } static struct custom_operations appsink_ops = { "ocaml_gstreamer_appsink", finalize_appsink, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; CAMLprim value ocaml_gstreamer_appsink_of_element(value _e) { CAMLparam1(_e); CAMLlocal1(ans); GstElement *e = Element_val(_e); appsink *as = malloc(sizeof(appsink)); if (as == NULL) caml_raise_out_of_memory(); as->appsink = GST_APP_SINK(e); as->element = _e; as->new_sample_cb = 0; as->new_sample_hid = 0; as->element = _e; caml_register_generational_global_root(&as->element); ans = caml_alloc_custom(&appsink_ops, sizeof(appsink *), 0, 1); Appsink_val(ans) = as; CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_appsink_emit_signals(value _as) { CAMLparam0(); appsink *as = Appsink_val(_as); caml_release_runtime_system(); gst_app_sink_set_emit_signals(as->appsink, TRUE); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_appsink_pull_buffer(value _as) { CAMLparam1(_as); CAMLlocal1(ans); appsink *as = Appsink_val(_as); GstSample *gstsample; GstBuffer *gstbuf; caml_release_runtime_system(); gstsample = gst_app_sink_pull_sample(as->appsink); caml_acquire_runtime_system(); if (!gstsample) { if (gst_app_sink_is_eos(as->appsink)) caml_raise_constant(*caml_named_value("gstreamer_exn_eos")); else caml_raise_constant(*caml_named_value("gstreamer_exn_stopped")); } caml_release_runtime_system(); gstbuf = gst_sample_get_buffer(gstsample); caml_acquire_runtime_system(); if (!gstbuf) caml_raise_out_of_memory(); gst_buffer_ref(gstbuf); gst_sample_unref(gstsample); value_of_buffer(gstbuf, ans); CAMLreturn(ans); } CAMLprim value ocaml_gstreamer_appsink_is_eos(value _as) { CAMLparam1(_as); appsink *as = Appsink_val(_as); gboolean ret; caml_release_runtime_system(); ret = gst_app_sink_is_eos(as->appsink); caml_acquire_runtime_system(); CAMLreturn(Val_bool(ret)); } static GstFlowReturn appsink_new_sample_cb(GstAppSink *gas, gpointer user_data) { appsink *as = (appsink *)user_data; ocaml_gstreamer_register_thread(); caml_acquire_runtime_system(); caml_callback(as->new_sample_cb, Val_unit); caml_release_runtime_system(); return GST_FLOW_OK; } CAMLprim value ocaml_gstreamer_appsink_connect_new_sample(value _as, value f) { CAMLparam2(_as, f); appsink *as = Appsink_val(_as); disconnect_new_sample(as); as->new_sample_cb = f; caml_register_generational_global_root(&as->new_sample_cb); caml_release_runtime_system(); as->new_sample_hid = g_signal_connect(as->appsink, "new-sample", G_CALLBACK(appsink_new_sample_cb), as); caml_acquire_runtime_system(); if (!as->new_sample_hid) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } CAMLprim value ocaml_gstreamer_appsink_set_max_buffers(value _as, value _n) { CAMLparam2(_as, _n); appsink *as = Appsink_val(_as); int n = Int_val(_n); caml_release_runtime_system(); gst_app_sink_set_max_buffers(as->appsink, n); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } /***** GstCaps *****/ #define Caps_val(v) (*(GstCaps **)Data_custom_val(v)) static void finalize_caps(value v) { GstCaps *c = Caps_val(v); gst_caps_unref(c); } static struct custom_operations caps_ops = { "ocaml_gstreamer_caps", finalize_caps, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; static value value_of_caps(GstCaps *c) { value ans = caml_alloc_custom(&caps_ops, sizeof(GstCaps *), 0, 1); Caps_val(ans) = c; return ans; } CAMLprim value ocaml_gstreamer_caps_to_string(value _c) { CAMLparam1(_c); CAMLlocal1(ans); GstCaps *c = Caps_val(_c); char *s; caml_release_runtime_system(); s = gst_caps_to_string(c); caml_acquire_runtime_system(); ans = caml_copy_string(s); free(s); CAMLreturn(ans); } /***** Typefind element *****/ typedef struct { GstElement *tf; value have_type_cb; // Callback function gulong have_type_hid; // Callback handler ID } typefind_element; #define Typefind_element_data_val(v) (*(typefind_element **)Data_custom_val(v)) #define Typefind_element_val(v) (Typefind_element_data_val(v)->tf) static void disconnect_have_type(typefind_element *tf) { if (tf->have_type_hid) { g_signal_handler_disconnect(tf->tf, tf->have_type_hid); tf->have_type_hid = 0; } if (tf->have_type_cb) { caml_remove_global_root(&tf->have_type_cb); tf->have_type_cb = 0; } } static void finalize_typefind_element(value v) { typefind_element *tf = Typefind_element_data_val(v); disconnect_have_type(tf); free(tf); } static struct custom_operations typefind_element_ops = { "ocaml_gstreamer_typefind_element", finalize_typefind_element, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default}; static value value_of_typefind_element(GstElement *e) { value ans = caml_alloc_custom(&typefind_element_ops, sizeof(typefind_element *), 0, 1); typefind_element *tf = malloc(sizeof(typefind_element)); tf->tf = e; tf->have_type_cb = 0; tf->have_type_hid = 0; Typefind_element_data_val(ans) = tf; return ans; } CAMLprim value ocaml_gstreamer_typefind_element_of_element(value _e) { CAMLparam1(_e); GstElement *e = Element_val(_e); // TODO: we don't have access to GST_TYPE_FIND_ELEMENT... CAMLreturn(value_of_typefind_element(GST_ELEMENT(e))); } static void typefind_element_have_type_cb(GstElement *_typefind, guint probability, GstCaps *caps, gpointer user_data) { typefind_element *tf = (typefind_element *)user_data; assert(_typefind); assert(caps); caml_acquire_runtime_system(); caml_callback2(tf->have_type_cb, Val_int(probability), value_of_caps(caps)); caml_release_runtime_system(); } CAMLprim value ocaml_gstreamer_typefind_element_connect_have_type(value _tf, value f) { CAMLparam2(_tf, f); typefind_element *tf = Typefind_element_data_val(_tf); disconnect_have_type(tf); tf->have_type_cb = f; caml_register_global_root(&tf->have_type_cb); caml_release_runtime_system(); tf->have_type_hid = g_signal_connect( tf->tf, "have-type", G_CALLBACK(typefind_element_have_type_cb), tf); caml_acquire_runtime_system(); if (!tf->have_type_hid) caml_raise_constant(*caml_named_value("gstreamer_exn_failed")); CAMLreturn(Val_unit); } /***** TagSetter element *****/ #define TagSetter_val(v) GST_TAG_SETTER(Element_val(v)) #define merge_modes_len 8 static const GstTagMergeMode merge_modes[merge_modes_len] = { GST_TAG_MERGE_UNDEFINED, GST_TAG_MERGE_REPLACE_ALL, GST_TAG_MERGE_REPLACE, GST_TAG_MERGE_APPEND, GST_TAG_MERGE_PREPEND, GST_TAG_MERGE_KEEP, GST_TAG_MERGE_KEEP_ALL, GST_TAG_MERGE_COUNT}; static GstTagMergeMode merge_mode_of_int(int n) { return merge_modes[n]; } /* static int int_of_merge_mode(GstTagMergeMode msg) { int i; for (i = 0; i < merge_modes_len; i++) { if (msg == merge_modes[i]) return i; } printf("error in tag merge mode: %d\n", msg); assert(0); } */ CAMLprim value ocaml_gstreamer_tag_setter_add_tag(value _t, value _mode, value _name, value _v) { gst_tag_setter_add_tags(TagSetter_val(_t), merge_mode_of_int(_mode), String_val(_name), String_val(_v), NULL); return Val_unit; }